-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-e2e.mjs
More file actions
425 lines (394 loc) · 21.7 KB
/
Copy pathtest-e2e.mjs
File metadata and controls
425 lines (394 loc) · 21.7 KB
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/**
* End-to-end test: simulate a real ECM company lifecycle
* Run: node test-e2e.mjs
*/
const BASE = 'http://localhost:3000/api/v1';
const H = { 'Content-Type': 'application/json', 'X-Tenant-ID': 'demo' };
async function api(method, path, body, allowConflict = false) {
const r = await fetch(BASE + path, {
method,
headers: H,
body: body ? JSON.stringify(body) : undefined,
});
const data = await r.json();
if (r.status === 409 && allowConflict) return null; // Already exists, skip
if (r.status >= 400) {
const msg = `${r.status} ${method} ${path}: ${JSON.stringify(data).substring(0, 300)}`;
console.error(' ERROR:', msg);
throw new Error(msg);
}
return data;
}
async function findOrCreate(listPath, createPath, body, matchField = 'name') {
// Try to find existing
const list = await api('GET', listPath + '?search=' + encodeURIComponent(body[matchField]) + '&limit=1');
const existing = (list.data || []).find(r => r[matchField] === body[matchField]);
if (existing) return existing;
// Create
const r = await api('POST', createPath, body);
return r.data;
}
function ok(label) { console.log(' [OK]', label); }
function section(label) { console.log('\n' + '='.repeat(60)); console.log(label); console.log('='.repeat(60)); }
let errors = 0;
async function run() {
// ── LOGIN ──────────────────────────────────────────────────
section('LOGIN');
const login = await api('POST', '/auth/login', { email: 'admin@tenant.local', password: 'admin123' });
H['Authorization'] = 'Bearer ' + login.data.access_token;
ok('Logged in as ' + login.data.user.name);
// ── MANUFACTURERS ──────────────────────────────────────────
section('SETUP MANUFACTURERS');
const mfgs = {};
for (const m of [
{ name: 'Texas Instruments', code: 'TI', website: 'https://ti.com' },
{ name: 'Murata Manufacturing', code: 'MURATA', website: 'https://murata.com' },
{ name: 'Yageo Corporation', code: 'YAGEO', website: 'https://yageo.com' },
{ name: 'Microchip Technology', code: 'MCHP', website: 'https://microchip.com' },
{ name: 'TE Connectivity', code: 'TE', website: 'https://te.com' },
]) {
const data = await findOrCreate('/manufacturers', '/manufacturers', m);
mfgs[m.code] = data;
ok(m.name);
}
// ── PARTS ──────────────────────────────────────────────────
section('CREATE PARTS');
const parts = {};
const partDefs = [
{ internal_pn: 'RES-10K-0402', description: 'Resistor 10K Ohm 0402 1%', part_type: 'component', category: 'Passives', uom: 'each', value: '10K', footprint: '0402', standard_cost: 0.005, min_stock: 5000, reorder_qty: 10000, lead_time_days: 7 },
{ internal_pn: 'RES-100R-0402', description: 'Resistor 100 Ohm 0402 1%', part_type: 'component', category: 'Passives', uom: 'each', value: '100R', footprint: '0402', standard_cost: 0.005, min_stock: 5000, reorder_qty: 10000, lead_time_days: 7 },
{ internal_pn: 'CAP-100NF-0402', description: 'Capacitor 100nF 16V 0402 X7R', part_type: 'component', category: 'Passives', uom: 'each', value: '100nF', footprint: '0402', standard_cost: 0.008, min_stock: 5000, reorder_qty: 10000, lead_time_days: 7 },
{ internal_pn: 'CAP-10UF-0805', description: 'Capacitor 10uF 25V 0805 X5R', part_type: 'component', category: 'Passives', uom: 'each', value: '10uF', footprint: '0805', standard_cost: 0.025, min_stock: 2000, reorder_qty: 5000, lead_time_days: 10 },
{ internal_pn: 'IC-STM32F411', description: 'MCU ARM Cortex-M4 100MHz 512KB Flash LQFP-64', part_type: 'component', category: 'ICs', uom: 'each', footprint: 'LQFP-64', standard_cost: 3.85, min_stock: 200, reorder_qty: 500, lead_time_days: 14 },
{ internal_pn: 'IC-LM3940', description: 'LDO Regulator 3.3V 1A SOT-223', part_type: 'component', category: 'ICs', uom: 'each', footprint: 'SOT-223', standard_cost: 1.20, min_stock: 500, reorder_qty: 1000, lead_time_days: 10 },
{ internal_pn: 'CONN-USB-C', description: 'USB Type-C Receptacle SMD', part_type: 'component', category: 'Connectors', uom: 'each', footprint: 'SMD', standard_cost: 0.65, min_stock: 500, reorder_qty: 1000, lead_time_days: 14 },
{ internal_pn: 'CONN-HDR-2X10', description: 'Header 2x10 Pin 2.54mm Male', part_type: 'component', category: 'Connectors', uom: 'each', footprint: 'THT', standard_cost: 0.35, min_stock: 500, reorder_qty: 2000, lead_time_days: 7 },
{ internal_pn: 'PCB-CTRL-V2', description: 'Controller Board PCB Rev B', part_type: 'component', category: 'PCBs', uom: 'each', standard_cost: 4.50, min_stock: 100, reorder_qty: 250, lead_time_days: 21 },
{ internal_pn: 'ASSY-CTRL-V2', description: 'Controller Board Assembly Rev B', part_type: 'assembly', category: 'Assemblies', uom: 'each', standard_cost: 28.50 },
];
for (const p of partDefs) {
const list = await api('GET', '/parts?search=' + encodeURIComponent(p.internal_pn) + '&limit=1');
const existing = (list.data || []).find(r => r.internal_pn === p.internal_pn);
if (existing) { parts[p.internal_pn] = existing; ok(p.internal_pn + ' (exists)'); continue; }
const r = await api('POST', '/parts', p);
parts[p.internal_pn] = r.data;
ok(p.internal_pn + ' (created)');
}
// ── AML ────────────────────────────────────────────────────
section('CREATE AML ENTRIES');
const amlDefs = [
{ part: 'RES-10K-0402', mfg: 'YAGEO', mpn: 'RC0402FR-0710KL', preference: 1, unit_price: 0.005 },
{ part: 'RES-100R-0402', mfg: 'YAGEO', mpn: 'RC0402FR-07100RL', preference: 1, unit_price: 0.005 },
{ part: 'CAP-100NF-0402', mfg: 'MURATA', mpn: 'GRM155R71C104KA88D', preference: 1, unit_price: 0.008 },
{ part: 'CAP-10UF-0805', mfg: 'MURATA', mpn: 'GRM21BR61E106KA73L', preference: 1, unit_price: 0.025 },
{ part: 'IC-STM32F411', mfg: 'TI', mpn: 'STM32F411CEU6', preference: 2, unit_price: 3.85 },
{ part: 'IC-LM3940', mfg: 'TI', mpn: 'LM3940IMP-3.3/NOPB', preference: 1, unit_price: 1.20 },
{ part: 'CONN-USB-C', mfg: 'TE', mpn: '2171750-1', preference: 1, unit_price: 0.65 },
{ part: 'CONN-HDR-2X10', mfg: 'TE', mpn: '87232-2020', preference: 1, unit_price: 0.35 },
];
for (const a of amlDefs) {
try {
await api('POST', '/parts/' + parts[a.part].id + '/aml', {
manufacturer_id: mfgs[a.mfg].id, mpn: a.mpn, preference: a.preference, unit_price: a.unit_price,
});
ok(a.part + ' -> ' + a.mpn + ' (created)');
} catch (e) {
if (e.message.includes('409')) ok(a.part + ' -> ' + a.mpn + ' (exists)');
else { console.log(' WARN AML:', e.message.substring(0, 80)); errors++; }
}
}
// ── BOM ────────────────────────────────────────────────────
section('SETUP BOM');
// Check if BOM already exists for this part
let bom;
const existingBoms = await api('GET', '/boms?search=ASSY-CTRL&limit=1');
if (existingBoms.data?.length > 0) {
bom = { data: existingBoms.data[0] };
ok('BOM already exists: ' + bom.data.id.substring(0, 8));
} else {
bom = await api('POST', '/boms', {
part_id: parts['ASSY-CTRL-V2'].id,
revision: 'B',
status: 'active',
description: 'Controller Board Assembly BOM Rev B',
lines: [
{ part_id: parts['PCB-CTRL-V2'].id, quantity: 1, reference_designators: 'PCB1', find_number: 1 },
{ part_id: parts['IC-STM32F411'].id, quantity: 1, reference_designators: 'U1', find_number: 2 },
{ part_id: parts['IC-LM3940'].id, quantity: 1, reference_designators: 'U2', find_number: 3 },
{ part_id: parts['RES-10K-0402'].id, quantity: 8, reference_designators: 'R1-R8', find_number: 4 },
{ part_id: parts['RES-100R-0402'].id, quantity: 4, reference_designators: 'R9-R12', find_number: 5 },
{ part_id: parts['CAP-100NF-0402'].id, quantity: 12, reference_designators: 'C1-C12', find_number: 6 },
{ part_id: parts['CAP-10UF-0805'].id, quantity: 4, reference_designators: 'C13-C16', find_number: 7 },
{ part_id: parts['CONN-USB-C'].id, quantity: 1, reference_designators: 'J1', find_number: 8 },
{ part_id: parts['CONN-HDR-2X10'].id, quantity: 2, reference_designators: 'J2,J3', find_number: 9 },
],
});
ok('BOM created: ' + bom.data.id.substring(0, 8) + ' (9 lines)');
} // end else (BOM creation)
// Validate BOM
try {
const val = await api('GET', '/boms/' + bom.data.id + '/validate');
ok('BOM validation: ' + (val.data?.length === 0 ? 'PASS' : val.data?.length + ' issues'));
} catch (e) { console.log(' WARN: BOM validate:', e.message.substring(0, 80)); errors++; }
// ── ECO ────────────────────────────────────────────────────
section('CREATE ECO');
try {
const eco = await api('POST', '/ecos', {
title: 'Update USB-C footprint to latest IPC spec',
description: 'Customer APEX requested updated USB-C footprint per IPC-7351B. Applies to ASSY-CTRL-V2 Rev B.',
effective_date: '2026-04-15',
});
ok('ECO created: ' + (eco.data?.eco_number || eco.data?.id?.substring(0, 8)));
} catch (e) { console.log(' WARN: ECO:', e.message.substring(0, 80)); errors++; }
// ── VENDORS ────────────────────────────────────────────────
section('CREATE VENDORS');
const vendors = {};
for (const v of [
{ name: 'Digi-Key Electronics', code: 'DIGI', vendor_type: 'distributor', payment_terms: 'Net 30', currency: 'USD' },
{ name: 'Mouser Electronics', code: 'MOUSER', vendor_type: 'distributor', payment_terms: 'Net 30', currency: 'USD' },
{ name: 'Arrow Electronics', code: 'ARROW', vendor_type: 'distributor', payment_terms: 'Net 45', currency: 'USD' },
{ name: 'PCBWay', code: 'PCBWAY', vendor_type: 'manufacturer_direct', payment_terms: 'Net 15', currency: 'USD' },
]) {
const data = await findOrCreate('/vendors', '/vendors', v);
vendors[v.code] = data;
ok(v.name);
}
// ── CUSTOMERS ──────────────────────────────────────────────
section('CREATE CUSTOMERS');
const customers = {};
for (const c of [
{ name: 'Apex Robotics Inc.', code: 'APEX', payment_terms: 'Net 30', currency: 'USD' },
{ name: 'NovaTech Medical Devices', code: 'NOVA', payment_terms: 'Net 45', currency: 'USD' },
{ name: 'Summit Aerospace Corp.', code: 'SUMMIT', payment_terms: 'Net 30', currency: 'USD' },
]) {
const data = await findOrCreate('/customers', '/customers', c);
customers[c.code] = data;
ok(c.name);
}
// ── WAREHOUSE ──────────────────────────────────────────────
section('SETUP WAREHOUSE');
const whData = await findOrCreate('/warehouses', '/warehouses', { name: 'Main Warehouse', code: 'WH-MAIN' });
ok('Warehouse: ' + whData.name);
// ── PURCHASE ORDERS ────────────────────────────────────────
section('CREATE PURCHASE ORDERS');
// PO to Digi-Key for passives
const po1 = await api('POST', '/purchase-orders', {
vendor_id: vendors['DIGI'].id,
expected_date: '2026-04-05',
notes: 'Passives for Q2 production',
lines: [
{ part_id: parts['RES-10K-0402'].id, quantity: 10000, unit_price: 0.005 },
{ part_id: parts['RES-100R-0402'].id, quantity: 10000, unit_price: 0.005 },
{ part_id: parts['CAP-100NF-0402'].id, quantity: 15000, unit_price: 0.008 },
{ part_id: parts['CAP-10UF-0805'].id, quantity: 5000, unit_price: 0.025 },
],
});
ok('PO1 (Digi-Key passives): ' + po1.data.po_number + ' $' + (po1.data.total_amount || ''));
// PO to Mouser for ICs
const po2 = await api('POST', '/purchase-orders', {
vendor_id: vendors['MOUSER'].id,
expected_date: '2026-04-10',
notes: 'ICs for controller board',
lines: [
{ part_id: parts['IC-STM32F411'].id, quantity: 600, unit_price: 3.85 },
{ part_id: parts['IC-LM3940'].id, quantity: 1000, unit_price: 1.20 },
],
});
ok('PO2 (Mouser ICs): ' + po2.data.po_number);
// PO to Arrow for connectors
const po3 = await api('POST', '/purchase-orders', {
vendor_id: vendors['ARROW'].id,
expected_date: '2026-04-08',
lines: [
{ part_id: parts['CONN-USB-C'].id, quantity: 1000, unit_price: 0.65 },
{ part_id: parts['CONN-HDR-2X10'].id, quantity: 2000, unit_price: 0.35 },
],
});
ok('PO3 (Arrow connectors): ' + po3.data.po_number);
// PO to PCBWay for PCBs
const po4 = await api('POST', '/purchase-orders', {
vendor_id: vendors['PCBWAY'].id,
expected_date: '2026-04-12',
lines: [
{ part_id: parts['PCB-CTRL-V2'].id, quantity: 500, unit_price: 4.50 },
],
});
ok('PO4 (PCBWay PCBs): ' + po4.data.po_number);
// Approve POs (bulk approve endpoint)
try {
await api('POST', '/purchase-orders/bulk-approve', { ids: [po1, po2, po3, po4].map(p => p.data.id) });
ok('Approved all 4 POs');
} catch (e) { console.log(' WARN approve:', e.message.substring(0, 100)); errors++; }
// ── RECEIVING ──────────────────────────────────────────────
section('RECEIVE MATERIALS');
// Receive PO1 (passives from Digi-Key)
try {
const po1Detail = await api('GET', '/purchase-orders/' + po1.data.id);
const po1Lines = po1Detail.data.lines || [];
if (po1Lines.length > 0) {
const rcv1 = await api('POST', '/receiving', {
po_id: po1.data.id,
received_date: '2026-04-05',
packing_slip_number: 'DK-2026-88431',
carrier: 'FedEx',
tracking_number: '7489201234567',
lines: po1Lines.map(l => ({
po_line_id: l.id,
quantity_received: Number(l.quantity),
lot_number: 'LOT-DK-' + Date.now(),
})),
});
ok('Received PO1 (Digi-Key): ' + (rcv1.data?.receiving_number || 'OK'));
}
} catch (e) { console.log(' Receiving PO1:', e.message.substring(0, 100)); }
// Receive PO2 (ICs from Mouser)
try {
const po2Detail = await api('GET', '/purchase-orders/' + po2.data.id);
const po2Lines = po2Detail.data.lines || [];
if (po2Lines.length > 0) {
const rcv2 = await api('POST', '/receiving', {
po_id: po2.data.id,
received_date: '2026-04-10',
packing_slip_number: 'MOU-6654321',
lines: po2Lines.map(l => ({
po_line_id: l.id,
quantity_received: Number(l.quantity),
})),
});
ok('Received PO2 (Mouser): ' + (rcv2.data?.receiving_number || 'OK'));
}
} catch (e) { console.log(' Receiving PO2:', e.message.substring(0, 100)); }
// ── SALES ORDERS ───────────────────────────────────────────
section('CREATE SALES ORDERS');
const soData = [
{ customer: 'APEX', qty: 200, note: 'Apex Robotics initial order', expected: '2026-05-01' },
{ customer: 'NOVA', qty: 100, note: 'NovaTech eval batch', expected: '2026-05-10' },
{ customer: 'SUMMIT', qty: 50, note: 'Summit prototype run', expected: '2026-04-25' },
{ customer: 'APEX', qty: 500, note: 'Apex Q2 production order', expected: '2026-06-01' },
{ customer: 'NOVA', qty: 300, note: 'NovaTech production batch 1', expected: '2026-06-15' },
{ customer: 'SUMMIT', qty: 150, note: 'Summit first production', expected: '2026-05-30' },
{ customer: 'APEX', qty: 100, note: 'Apex R&D samples', expected: '2026-04-20' },
];
const salesOrders = [];
for (const so of soData) {
const r = await api('POST', '/sales-orders', {
customer_id: customers[so.customer].id,
expected_date: so.expected,
notes: so.note,
lines: [{
part_id: parts['ASSY-CTRL-V2'].id,
quantity: so.qty,
unit_price: 42.00,
description: 'Controller Board Assembly Rev B',
}],
});
salesOrders.push(r.data);
ok(r.data.so_number + ' - ' + so.customer + ' x' + so.qty + ' ($' + (so.qty * 42).toLocaleString() + ')');
}
// ── JOBS (Work Orders) ─────────────────────────────────────
section('CREATE JOBS FROM SALES ORDERS');
const jobs = [];
for (const so of salesOrders.slice(0, 3)) { // Create jobs for first 3 SOs
try {
const r = await api('POST', '/jobs', {
part_id: parts['ASSY-CTRL-V2'].id,
bom_id: bom.data.id,
sales_order_id: so.id,
customer_id: so.customer_id,
quantity_ordered: Number(so.lines?.[0]?.quantity) || 100,
priority: 'normal',
scheduled_start: '2026-04-10',
scheduled_end: '2026-04-20',
description: 'Build for ' + so.so_number,
});
jobs.push(r.data);
ok(r.data.job_number + ' for ' + so.so_number + ' (qty: ' + r.data.quantity_ordered + ')');
} catch (e) { console.log(' Job creation:', e.message.substring(0, 100)); }
}
// Release jobs
for (const job of jobs) {
try {
await api('PUT', '/jobs/' + job.id, { status: 'released' });
ok('Released: ' + job.job_number);
} catch (e) { console.log(' Release:', e.message.substring(0, 80)); }
}
// ── CHECK DASHBOARD ────────────────────────────────────────
section('VERIFY DASHBOARD');
const dash = await api('GET', '/reports/dashboard');
const d = dash.data;
console.log(' Parts:', d.total_parts);
console.log(' Open POs:', d.total_open_pos);
console.log(' Open SOs:', d.total_open_sos);
console.log(' Active Jobs:', d.total_active_jobs);
ok('Dashboard populated');
// ── CHECK ATP ──────────────────────────────────────────────
section('CHECK ATP (Available to Promise)');
try {
const atp = await api('GET', '/sales-orders/atp/' + parts['ASSY-CTRL-V2'].id);
console.log(' ASSY-CTRL-V2 ATP:', JSON.stringify(atp.data));
ok('ATP calculation working');
} catch (e) { console.log(' ATP: endpoint not available yet (needs route registration)'); }
// ── CHECK MATERIAL READINESS ───────────────────────────────
section('CHECK MATERIAL READINESS');
if (jobs.length > 0) {
try {
const ready = await api('GET', '/jobs/' + jobs[0].id + '/material-readiness');
console.log(' Job', jobs[0].job_number, 'readiness:', JSON.stringify(ready.data).substring(0, 200));
ok('Material readiness working');
} catch (e) { console.log(' Readiness:', e.message.substring(0, 100)); }
}
// ── CHECK PLANNING SUGGESTIONS ─────────────────────────────
section('CHECK PLANNING SUGGESTIONS (from event cascade)');
try {
const suggestions = await api('GET', '/mrp/suggestions?status=pending&limit=10');
console.log(' Pending suggestions:', suggestions.data?.length || 0);
if (suggestions.data?.length > 0) {
for (const s of suggestions.data.slice(0, 5)) {
console.log(' -', s.action_type, s.internal_pn || s.part_id?.substring(0, 8), 'qty:', s.suggested_qty, s.message?.substring(0, 60));
}
}
ok('Planning suggestions present');
} catch (e) { console.log(' Suggestions:', e.message.substring(0, 100)); }
// ── CHECK GL POSTINGS ──────────────────────────────────────
section('CHECK GL POSTINGS (from event cascade)');
try {
const jes = await api('GET', '/journal-entries?limit=10');
console.log(' Journal entries:', jes.data?.length || 0);
if (jes.data?.length > 0) {
for (const je of jes.data.slice(0, 5)) {
console.log(' -', je.entry_number, je.description?.substring(0, 60), 'status:', je.status);
}
}
ok('GL postings present');
} catch (e) { console.log(' JEs:', e.message.substring(0, 100)); }
// ── CHECK NOTIFICATIONS ────────────────────────────────────
section('CHECK NOTIFICATIONS');
try {
const notifs = await api('GET', '/notifications?limit=10');
console.log(' Notifications:', notifs.data?.length || 0);
ok('Notification system working');
} catch (e) { console.log(' Notifications:', e.message.substring(0, 100)); }
// ── SUMMARY ────────────────────────────────────────────────
section('TEST SUMMARY');
console.log('Manufacturers: 5');
console.log('Parts: ' + Object.keys(parts).length);
console.log('AML entries: ' + amlDefs.length);
console.log('BOM: 1 (9 lines)');
console.log('ECOs: 1');
console.log('Vendors: ' + Object.keys(vendors).length);
console.log('Customers: ' + Object.keys(customers).length);
console.log('Purchase Orders: 4');
console.log('Receiving Records: 2');
console.log('Sales Orders: ' + salesOrders.length);
console.log('Jobs: ' + jobs.length);
if (errors > 0) {
console.log('\n' + errors + ' non-critical errors (endpoints returned 500).');
console.log('These need investigation but core flow completed.');
} else {
console.log('\nAll endpoints responded successfully!');
}
}
run().catch(e => {
console.error('\nFATAL:', e.message);
process.exit(1);
});