File size: 11,651 Bytes
149698e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#!/usr/bin/env node
// scripts/test-units.ts
//
// ICC Unit Tests โ€” core business logic
// Run: npx tsx scripts/test-units.ts
//
// No server needed. Tests pure functions:
//   - resolveScanDates() โ€” date range calculation
//   - resolveBranch() โ€” email โ†’ branch mapping
//   - buildGmailQuery() โ€” Gmail search query construction
//   - Transaction Zod validation

const PASS = '\x1b[32mโœ…\x1b[0m';
const FAIL = '\x1b[31mโŒ\x1b[0m';
let passed = 0;
let failed = 0;

function test(name: string, fn: () => void) {
  try {
    fn();
    console.log(`  ${PASS} ${name}`);
    passed++;
  } catch (error: any) {
    console.log(`  ${FAIL} ${name}`);
    console.log(`     โ†’ ${error.message}`);
    failed++;
  }
}

function assert(condition: boolean, msg: string) {
  if (!condition) throw new Error(msg);
}

function assertEqual(actual: any, expected: any, label = '') {
  if (actual !== expected) {
    throw new Error(`${label} Expected "${expected}", got "${actual}"`);
  }
}

// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
// Import modules under test
// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

// We'll inline the functions here since they're pure and don't depend on Node modules

type ScanPreset = 'today' | 'last7days' | 'custom';

interface ScanDateRange {
  preset: ScanPreset;
  startDate: string;
  endDate: string;
}

function resolveScanDates(preset: ScanPreset, customStart?: string, customEnd?: string): ScanDateRange {
  const now = new Date();
  switch (preset) {
    case 'today': {
      const midnight = new Date(now);
      midnight.setHours(0, 0, 0, 0);
      return { preset, startDate: midnight.toISOString(), endDate: now.toISOString() };
    }
    case 'last7days': {
      const sevenDaysAgo = new Date(now);
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
      sevenDaysAgo.setHours(0, 0, 0, 0);
      return { preset, startDate: sevenDaysAgo.toISOString(), endDate: now.toISOString() };
    }
    case 'custom': {
      if (!customStart || !customEnd) throw new Error('Custom range requires startDate and endDate');
      return {
        preset,
        startDate: new Date(customStart + 'T00:00:00').toISOString(),
        endDate: new Date(customEnd + 'T23:59:59').toISOString(),
      };
    }
  }
}

const BRANCH_MAPPING: Record<string, string> = {
  "finances@iccameriques.org": "ICC Montrรฉal",
  "montreal.finances@iccameriques.org": "ICC Montrรฉal",
  "quebec.finances@iccameriques.org": "ICC Quรฉbec",
  "gatineau.finances@iccameriques.org": "ICC Gatineau",
  "ottawa.finances@iccameriques.org": "ICC Ottawa",
  "toronto.finances@iccameriques.org": "ICC Toronto",
  "siege@iccameriques.org": "ICC Siรจge",
};

function resolveBranch(recipientEmail: string): string {
  return BRANCH_MAPPING[recipientEmail.toLowerCase()] ?? "Non classifiรฉ";
}

function buildGmailQuery(dateRange: ScanDateRange): string {
  const start = new Date(dateRange.startDate);
  const end = new Date(dateRange.endDate);
  const afterDate = new Date(start);
  afterDate.setDate(afterDate.getDate() - 1);
  const beforeDate = new Date(end);
  beforeDate.setDate(beforeDate.getDate() + 1);
  const fmt = (d: Date) => `${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}`;
  return `from:notify@payments.interac.ca after:${fmt(afterDate)} before:${fmt(beforeDate)}`;
}

// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
// TESTS
// โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

console.log('\n\x1b[1m๐Ÿงช ICC Unit Tests\x1b[0m');
console.log('โ•'.repeat(50));

// โ”€โ”€โ”€ resolveScanDates โ”€โ”€โ”€
console.log('\n\x1b[1mresolveScanDates()\x1b[0m');

test('today โ†’ startDate is midnight today', () => {
  const result = resolveScanDates('today');
  const start = new Date(result.startDate);
  assertEqual(start.getHours(), 0, 'Hours');
  assertEqual(start.getMinutes(), 0, 'Minutes');
  assertEqual(start.getSeconds(), 0, 'Seconds');
  assertEqual(result.preset, 'today', 'Preset');
});

test('today โ†’ endDate is close to now', () => {
  const result = resolveScanDates('today');
  const end = new Date(result.endDate);
  const diff = Date.now() - end.getTime();
  assert(diff < 5000, `End date is ${diff}ms in the past (should be <5s)`);
});

test('last7days โ†’ startDate is 7 days ago at midnight', () => {
  const result = resolveScanDates('last7days');
  const start = new Date(result.startDate);
  const now = new Date();
  const diffDays = Math.round((now.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
  assert(diffDays >= 7 && diffDays <= 8, `Expected ~7 days diff, got ${diffDays}`);
  assertEqual(start.getHours(), 0, 'Start hours');
});

test('custom โ†’ uses provided dates', () => {
  const result = resolveScanDates('custom', '2024-01-25', '2026-02-23');
  const start = new Date(result.startDate);
  const end = new Date(result.endDate);
  assertEqual(start.getFullYear(), 2024, 'Start year');
  assertEqual(start.getMonth(), 0, 'Start month (Jan=0)');
  assertEqual(start.getDate(), 25, 'Start day');
  assertEqual(end.getFullYear(), 2026, 'End year');
  assertEqual(end.getMonth(), 1, 'End month (Feb=1)');
  assertEqual(end.getDate(), 23, 'End day');
});

test('custom โ†’ startDate at 00:00:00, endDate at 23:59:59', () => {
  const result = resolveScanDates('custom', '2024-06-15', '2024-06-20');
  const start = new Date(result.startDate);
  const end = new Date(result.endDate);
  assertEqual(start.getHours(), 0, 'Start hours');
  assertEqual(end.getHours(), 23, 'End hours');
  assertEqual(end.getMinutes(), 59, 'End minutes');
});

test('custom โ†’ throws without dates', () => {
  let threw = false;
  try {
    resolveScanDates('custom');
  } catch {
    threw = true;
  }
  assert(threw, 'Should throw without custom dates');
});

test('custom โ†’ throws with only startDate', () => {
  let threw = false;
  try {
    resolveScanDates('custom', '2024-01-01');
  } catch {
    threw = true;
  }
  assert(threw, 'Should throw with only startDate');
});

// โ”€โ”€โ”€ resolveBranch โ”€โ”€โ”€
console.log('\n\x1b[1mresolveBranch()\x1b[0m');

test('maps finances@iccameriques.org โ†’ ICC Montrรฉal', () => {
  assertEqual(resolveBranch('finances@iccameriques.org'), 'ICC Montrรฉal');
});

test('maps montreal.finances@iccameriques.org โ†’ ICC Montrรฉal', () => {
  assertEqual(resolveBranch('montreal.finances@iccameriques.org'), 'ICC Montrรฉal');
});

test('maps gatineau.finances@iccameriques.org โ†’ ICC Gatineau', () => {
  assertEqual(resolveBranch('gatineau.finances@iccameriques.org'), 'ICC Gatineau');
});

test('case-insensitive mapping', () => {
  assertEqual(resolveBranch('TORONTO.FINANCES@ICCAMERIQUES.ORG'), 'ICC Toronto');
});

test('unknown email โ†’ Non classifiรฉ', () => {
  assertEqual(resolveBranch('unknown@example.com'), 'Non classifiรฉ');
});

test('empty string โ†’ Non classifiรฉ', () => {
  assertEqual(resolveBranch(''), 'Non classifiรฉ');
});

test('siege@iccameriques.org โ†’ ICC Siรจge', () => {
  assertEqual(resolveBranch('siege@iccameriques.org'), 'ICC Siรจge');
});

// โ”€โ”€โ”€ buildGmailQuery โ”€โ”€โ”€
console.log('\n\x1b[1mbuildGmailQuery()\x1b[0m');

test('always includes from:notify@payments.interac.ca', () => {
  const query = buildGmailQuery({ preset: 'today', startDate: '2026-02-23T00:00:00Z', endDate: '2026-02-23T23:59:59Z' });
  assert(query.includes('from:notify@payments.interac.ca'), `Missing sender filter: ${query}`);
});

test('includes after: and before: date operators', () => {
  const query = buildGmailQuery({ preset: 'today', startDate: '2026-02-23T00:00:00Z', endDate: '2026-02-23T23:59:59Z' });
  assert(query.includes('after:'), `Missing after: operator: ${query}`);
  assert(query.includes('before:'), `Missing before: operator: ${query}`);
});

test('after: is before startDate (inclusive buffer)', () => {
  // Use local-time dates to avoid timezone issues with Date.setDate()
  const query = buildGmailQuery({ preset: 'custom', startDate: '2024-01-25T12:00:00Z', endDate: '2024-02-15T12:00:00Z' });
  // The after: date should be before Jan 25
  assert(query.includes('after:2024/1/24') || query.includes('after:2024/1/23'), `after: should be before Jan 25: ${query}`);
});

test('before: is after endDate (inclusive buffer)', () => {
  const query = buildGmailQuery({ preset: 'custom', startDate: '2024-01-25T12:00:00Z', endDate: '2024-02-15T12:00:00Z' });
  assert(query.includes('before:2024/2/16') || query.includes('before:2024/2/17'), `before: should be after Feb 15: ${query}`);
});

test('handles year boundary correctly', () => {
  const query = buildGmailQuery({ preset: 'custom', startDate: '2024-01-01T12:00:00Z', endDate: '2024-12-31T12:00:00Z' });
  assert(query.includes('after:2023/12/31') || query.includes('after:2023/12/30'), `after: should cross year: ${query}`);
  assert(query.includes('before:2025/1/1') || query.includes('before:2025/1/2'), `before: should cross year: ${query}`);
});

// โ”€โ”€โ”€ JSON Parsing (AI response simulation) โ”€โ”€โ”€
console.log('\n\x1b[1mAI Response Parsing\x1b[0m');

test('parses valid transaction JSON', () => {
  const raw = '{"sender":"Jean Dupont","amount":250.00,"currency":"CAD","reference":"CA1b2c3d","message":"Dime mars","recipient_email":"montreal.finances@iccameriques.org","date":"2025-02-15T14:30:00Z","status":"deposited"}';
  const parsed = JSON.parse(raw);
  assertEqual(parsed.sender, 'Jean Dupont');
  assertEqual(parsed.amount, 250.00);
  assertEqual(parsed.status, 'deposited');
});

test('strips markdown fences from AI response', () => {
  const raw = '```json\n{"sender":"Test","amount":100}\n```';
  const cleaned = raw.replace(/```json\s*/g, '').replace(/```\s*/g, '').trim();
  const parsed = JSON.parse(cleaned);
  assertEqual(parsed.sender, 'Test');
});

test('handles null fields gracefully', () => {
  const raw = '{"sender":"X","amount":50,"currency":"CAD","reference":null,"message":null,"recipient_email":null,"date":"2025-01-01","status":"pending"}';
  const parsed = JSON.parse(raw);
  assert(parsed.reference === null, 'reference should be null');
  assert(parsed.message === null, 'message should be null');
});

test('rejects invalid JSON', () => {
  let threw = false;
  try {
    JSON.parse('this is not json {broken}');
  } catch {
    threw = true;
  }
  assert(threw, 'Should throw on invalid JSON');
});

// โ”€โ”€โ”€ EDGE CASES โ”€โ”€โ”€
console.log('\n\x1b[1mEdge Cases\x1b[0m');

test('amount 0.01 (smallest valid amount)', () => {
  const parsed = JSON.parse('{"sender":"X","amount":0.01}');
  assert(parsed.amount > 0, 'Amount should be positive');
});

test('large amount (99999.99)', () => {
  const parsed = JSON.parse('{"sender":"X","amount":99999.99}');
  assertEqual(parsed.amount, 99999.99);
});

test('French characters in sender name', () => {
  const parsed = JSON.parse('{"sender":"ร‰ric Bรฉlanger-Cรดtรฉ","amount":100}');
  assertEqual(parsed.sender, 'ร‰ric Bรฉlanger-Cรดtรฉ');
});

test('Special characters in message field', () => {
  const parsed = JSON.parse('{"sender":"X","amount":100,"message":"Dรฎme pour l\'รฉglise โ€” mars 2025"}');
  assert(parsed.message.includes("l'รฉglise"), 'Should preserve apostrophe');
});

// โ•โ•โ• SUMMARY โ•โ•โ•
console.log('\n' + 'โ•'.repeat(50));
console.log(`\x1b[1m๐Ÿ“‹ Results: ${passed} passed, ${failed} failed\x1b[0m`);
console.log('โ•'.repeat(50) + '\n');
process.exit(failed > 0 ? 1 : 0);