allocate.test.ts
TypeScript · 154 рядків
1// Відбір перевіряється інваріантами на тисячах випадкових складів, а не лише прикладами:
2// генератор знаходить граничні випадки, яких не придумає ні людина, ні агент. Падіння друкує seed для повтору.
3import assert from 'node:assert/strict';
4import { test } from 'node:test';
5import { allocate, departuresByItem, newAllocResult, type AllocRow } from './allocate.ts';
6import { PackType, Status, TxType } from './codes.ts';
7
8function rng(seed: number) {
9 let s = seed >>> 0;
10 return () => {
11 let t = (s += 0x6d2b79f5);
12 t = Math.imul(t ^ (t >>> 15), t | 1);
13 t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
14 return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
15 };
16}
17
18let nextId = 1;
19function row(p: Partial<AllocRow> & Pick<AllocRow, 'packType' | 'packSize' | 'packCount'>): AllocRow {
20 const r: AllocRow = {
21 id: nextId++, productId: 1, isContainer: false, quantity: p.packSize * p.packCount, containedInId: null, locationId: 10101,
22 expiryDate: null, mfgDate: null, receivedAt: '2027-01-04T08:00:00Z', serial: false, origCount: 0, origQuantity: 0, ...p,
23 };
24 r.origCount = r.packCount;
25 r.origQuantity = r.quantity;
26 return r;
27}
28
29/** Випадковий склад одного товару: групи пакувань, розсип, спайки з вмістом, різні строки. */
30function randomStock(rand: () => number): AllocRow[] {
31 const int = (a: number, b: number) => a + Math.floor(rand() * (b - a + 1));
32 const expiry = () => (rand() < 0.3 ? null : `2027-0${int(2, 9)}-1${int(0, 9)}`);
33 const rows: AllocRow[] = [];
34 for (let i = int(0, 4); i > 0; i--) rows.push(row({ packType: int(1, 3), packSize: [5, 10, 20, 50][int(0, 3)], packCount: int(1, 6), expiryDate: expiry() }));
35 if (rand() < 0.7) rows.push(row({ packType: PackType.unit, packSize: 1, packCount: int(0, 30), expiryDate: expiry() }));
36 for (let i = int(0, 2); i > 0; i--) {
37 const e = expiry();
38 const c = row({ packType: PackType.bundle, packSize: 0, packCount: 1, isContainer: true, expiryDate: e });
39 const kids = [row({ packType: PackType.box, packSize: 10, packCount: int(1, 5), containedInId: c.id, expiryDate: e })];
40 if (rand() < 0.5) kids.push(row({ packType: PackType.unit, packSize: 1, packCount: int(1, 9), containedInId: c.id, expiryDate: e }));
41 c.quantity = c.packSize = c.origQuantity = kids.reduce((s, k) => s + k.quantity, 0);
42 rows.push(c, ...kids);
43 }
44 return rows;
45}
46
47const leafUnits = (rows: AllocRow[]) => rows.filter((r) => !r.isContainer && !r.archived).reduce((s, r) => s + r.quantity, 0);
48
49test('інваріанти відбору на 5 000 випадкових складів', () => {
50 for (let seed = 1; seed <= 5_000; seed++) {
51 const rand = rng(seed);
52 const rows = randomStock(rand);
53 const before = leafUnits(rows);
54 const qty = 1 + Math.floor(rand() * (before + 10));
55 const out = newAllocResult();
56 allocate(rows, 1, qty, out, rand() < 0.2 ? TxType.WRITE_OFF : TxType.ISSUE);
57 const ctx = `seed=${seed} qty=${qty} before=${before}`;
58
59 assert.equal(out.issued + out.short, qty, `issued + short = qty (${ctx})`);
60 assert.equal(leafUnits(rows), before - out.issued, `Σ листків зменшилась рівно на видане (${ctx})`);
61 assert.equal(out.short, Math.max(0, qty - before), `нестача лише коли товару немає (${ctx})`);
62 for (const r of rows) {
63 assert.ok(r.quantity >= 0 && r.packCount >= 0, `від'ємна кількість у записі ${r.id} (${ctx})`);
64 if (!r.isContainer) assert.equal(r.quantity, r.packSize * r.packCount, `quantity = size × count у записі ${r.id} (${ctx})`);
65 if (r.archived && !r.isContainer) assert.equal(r.quantity, 0, `в архів — лише вичерпаний запис ${r.id} (${ctx})`);
66 }
67 const loose = rows.filter((r) => !r.archived && r.packType === PackType.unit && !r.isContainer && r.containedInId == null);
68 const keys = loose.map((r) => `${r.locationId}|${r.expiryDate}`);
69 assert.equal(new Set(keys).size, keys.length, `один постійний розсип на адресу й строк (${ctx})`);
70 for (const r of rows) {
71 if (r.isNew || (r.packType === PackType.unit && !r.isContainer && r.containedInId == null && !r.serial)) continue;
72 const gone = out.departures.filter((d) => d.itemId === r.id);
73 const live = r.archived ? 0 : r.quantity;
74 assert.equal(live + gone.reduce((s, d) => s + d.quantity, 0), r.origQuantity, `запис ${r.id}: лежить + історія = було (${ctx})`);
75 assert.equal(gone.some((d) => d.exhausted), !!r.archived, `exhausted ↔ запис вичерпано ${r.id} (${ctx})`);
76 }
77 for (const j of out.journal) {
78 if (j.delta) assert.equal(j.packDelta * j.packSize, j.delta, `pack_delta × pack_size = qty_delta (${ctx})`);
79 }
80 const journalSum = out.journal.reduce((s, j) => s + j.delta, 0);
81 assert.equal(journalSum + out.issued, 0, `Σ журналу = − видане (${ctx})`);
82 }
83});
84
85test('FEFO: товар із пізнішим строком не береться, поки є раніший', () => {
86 for (let seed = 1; seed <= 2_000; seed++) {
87 const rand = rng(seed);
88 const rows = randomStock(rand);
89 const out = newAllocResult();
90 allocate(rows, 1, 1 + Math.floor(rand() * 30), out);
91 const issuedExpiries = [...out.issuedLots.values()].map((l) => l.expiryDate ?? '9999');
92 const latestIssued = issuedExpiries.sort().at(-1);
93 if (!latestIssued) continue;
94 const leftEarlier = rows.filter((r) => !r.archived && !r.isContainer && r.quantity > 0 && (r.expiryDate ?? '9999') < latestIssued);
95 assert.deepEqual(leftEarlier.map((r) => r.id), [], `seed=${seed}: лишились записи з ранішим строком, ніж видане`);
96 }
97});
98
99test('спайка 10×100: видача 1 розрізає спайку і розкриває одну коробку', () => {
100 const c = row({ packType: PackType.bundle, packSize: 1000, packCount: 1, isContainer: true });
101 const boxes = row({ packType: PackType.box, packSize: 100, packCount: 10, containedInId: c.id });
102 const rows = [c, boxes];
103 const out = newAllocResult();
104 allocate(rows, 1, 1, out);
105 assert.equal(out.cutContainers, 1);
106 assert.equal(out.openedPacks, 1);
107 assert.deepEqual(c.archived, { status: Status.OPENED, final: 1000 });
108 assert.equal(boxes.containedInId, null);
109 assert.equal(boxes.packCount, 9);
110 const loose = rows.find((r) => r.isNew)!;
111 assert.equal(loose.quantity, 99, 'з розкритої коробки 99 штук лишились у постійному розсипі');
112});
113
114test('списання архівує вичерпані записи зі станом WRITTEN_OFF', () => {
115 const box = row({ packType: PackType.box, packSize: 10, packCount: 1 });
116 const out = newAllocResult();
117 allocate([box], 1, 10, out, TxType.WRITE_OFF);
118 assert.deepEqual(box.archived, { status: Status.WRITTEN_OFF, final: 10 });
119 assert.equal(out.journal[0].type, TxType.WRITE_OFF);
120});
121
122test('B: цілі пакування — від більшого (коробка 100, потім пакети 10)', () => {
123 const boxes = row({ packType: PackType.box, packSize: 100, packCount: 2 });
124 const bags = row({ packType: PackType.bag, packSize: 10, packCount: 10 });
125 const out = newAllocResult();
126 allocate([boxes, bags], 1, 120, out);
127 assert.deepEqual([boxes.packCount, bags.packCount, out.openedPacks], [1, 8, 0], '1 коробка + 2 пакети, нічого не розкрито');
128});
129
130test('історія на прикладі: 5 коробок по 10, видача 12 → 3 лежать, в історії 1 видана + 1 розкрита', () => {
131 const boxes = row({ packType: PackType.box, packSize: 10, packCount: 5 });
132 const rows = [boxes];
133 const out = newAllocResult();
134 allocate(rows, 1, 12, out);
135 assert.equal(boxes.packCount, 3);
136 const loose = rows.find((r) => r.isNew)!;
137 assert.equal(loose.quantity, 8);
138 assert.deepEqual(out.departures.map((d) => [d.itemId, d.packCount, d.quantity, d.status, d.toItemId]), [
139 [boxes.id, 1, 10, Status.ISSUED, null],
140 [boxes.id, 1, 10, Status.OPENED, loose.id],
141 ], 'розсип в історію не пишеться — лише журнал');
142 const open = out.journal.find((j) => j.type === TxType.OPEN && j.itemId === boxes.id)!;
143 assert.deepEqual([open.packType, open.packSize, open.packDelta, open.delta], [PackType.box, 10, -1, -10], 'журнал: з якої коробки розкрито');
144});
145
146test('departuresByItem: частини одного запису зводяться в один рядок історії', () => {
147 const boxes = row({ packType: PackType.box, packSize: 10, packCount: 5 });
148 const out = newAllocResult();
149 allocate([boxes], 1, 12, out);
150 const [h, ...rest] = departuresByItem(out.departures);
151 assert.equal(rest.length, 0);
152 assert.deepEqual([h.itemId, h.packCount, h.quantity, h.issued, h.opened, h.status, h.exhausted], [boxes.id, 2, 20, 1, 1, Status.OPENED, false]);
153});
154