techtools
Головна / research / lab / stock-lab / src / features / tasks.test.ts

tasks.test.ts

TypeScript · 173 рядків

1// Черга задач R-09 через API. Кожен тест — на власному складі (черга не змішується з іншими тестами).
2import assert from 'node:assert/strict';
3import { before, test } from 'node:test';
4import { PACK, useLab } from '../../test/lab.ts';
5
6const lab = useLab();
7let nextWh = 100 + (process.pid % 50) * 20;
8let nextWorker = 1;
9
10before(async () => {
11  await lab.api.post('/api/maintenance/partitions', { from: '2026-12-28', to: '2027-01-31' });
12});
13
14async function warehouse(): Promise<number> {
15  const id = nextWh++;
16  await lab.api.post('/api/catalog/import', { warehouses: [{ id, name: `тест черги ${id}` }] });
17  return id;
18}
19const T = (h: number, m = 0) => `2027-01-04T${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:00.000Z`;
20// кожен виклик — новий комірник (у комірника не більше однієї задачі в роботі)
21const take = (warehouseId: number, roles: string[], at: string, extra: Record<string, unknown> = {}) =>
22  lab.api.post('/api/tasks/next', { warehouseId, workerId: nextWorker++, roles, at, ...extra });
23async function finish(task: any, lines: any[], at: string) {
24  let r: any;
25  for (const l of lines) r = await lab.api.post(`/api/tasks/${task.id}/lines/${l.id}/done`, { at });
26  return r;
27}
28
29test('крос-док при прибутті фури: замовлення чекало товар → задача на пакування з терміном і балом клієнта, решта — на полицю', async () => {
30  const wh = await warehouse();
31  const p = await lab.product();
32  const order = await lab.api.post('/api/tasks/customer-orders', { warehouseId: wh, lines: [{ productId: p.id, qty: 12 }], dueAt: T(11), priority: 80, at: T(8) });
33  assert.deepEqual([order.shelf, order.crossdock, order.waiting, order.ready], [0, 0, 12, false]);
34
35  const inb = await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'supply', lines: [{ productId: p.id, qty: 100 }], at: T(9) });
36  assert.deepEqual([inb.crossdockLines, inb.crossdockQty, inb.taskIds.length], [1, 12, 2]);
37
38  const first = await take(wh, ['receiving'], T(9));
39  assert.equal(first.task.type, 'crossdock', 'крос-док під замовлення о 11:00 — раніше за «на полицю» (термін завтра)');
40  assert.equal(first.task.priority, 80);
41  await finish(first.task, first.lines, T(9, 5));
42
43  const pack = await take(wh, ['packing'], T(9, 6));
44  assert.equal(pack.task?.type, 'pack', 'замовлення готове — пакування розблоковано');
45  const r = await finish(pack.task, pack.lines, T(9, 10));
46  assert.equal(r.orderShipped, true);
47
48  const s = await lab.api.get('/api/tasks/report', { warehouseId: wh, at: T(10) });
49  assert.deepEqual([s.orders.shipped, s.orders.on_time], [1, 1]);
50});
51
52test('крос-док на ходу: фура вже на складі, замовлення клієнта з\'явилось потім — частина рядка «на полицю» йде на пакування', async () => {
53  const wh = await warehouse();
54  const p = await lab.product();
55  await lab.receive(p.id, { lines: [{ packType: PACK.unit, packSize: 1, packCount: 50 }] }, wh);   // на полиці є, строку немає
56  await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'supply', lines: [{ productId: p.id, qty: 30 }], at: T(8) });
57  const order = await lab.api.post('/api/tasks/customer-orders', { warehouseId: wh, lines: [{ productId: p.id, qty: 5 }], dueAt: T(12), at: T(9) });
58  assert.deepEqual([order.crossdock, order.shelf], [5, 0], 'R-09.12: завжди крос-док, якщо на полиці строк не спливає');
59  const put = await take(wh, ['receiving'], T(9, 1), { horizon: 'none' });
60  const all = [put];
61  const second = await take(wh, ['receiving'], T(9, 2), { horizon: 'none' });
62  all.push(second);
63  const putaway = all.find((x) => x.task.type === 'putaway');
64  assert.equal(putaway.lines[0].qty, 25, '30 − 5 на крос-док');
65});
66
67test('строк на полиці спливає → замовлення бере з полиці (FEFO), а не з фури', async () => {
68  const wh = await warehouse();
69  const p = await lab.product();
70  await lab.receive(p.id, { lines: [{ packType: PACK.unit, packSize: 1, packCount: 20 }], expiryDate: '2027-01-20' }, wh);
71  await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'supply', lines: [{ productId: p.id, qty: 30 }], at: T(8) });
72  const order = await lab.api.post('/api/tasks/customer-orders', { warehouseId: wh, lines: [{ productId: p.id, qty: 5 }], dueAt: T(12), at: T(9), expiryDays: 30 });
73  assert.deepEqual([order.shelf, order.crossdock, order.ready], [5, 0, true]);
74});
75
76test('черга: один слот → вищий бал; повернення — останні; ролі з напрямками й горизонтом', async () => {
77  const wh = await warehouse();
78  const p = await lab.product();
79  const ret = await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'return', lines: [{ productId: p.id, qty: 1 }], at: T(7), dueAt: T(8) });
80  const low = await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'transfer', lines: [{ productId: p.id, qty: 1 }], at: T(8), dueAt: T(11, 0) });
81  const high = await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'transfer', lines: [{ productId: p.id, qty: 1 }], at: T(8), dueAt: T(11, 20) });
82  // бал однаковий з довідника; підвищимо бал другої задачі через замовлення? — бал транзиту фіксований, тож порядок у слоті — термін
83  const a = await take(wh, ['transfer', 'returns'], T(9), { peek: true });
84  assert.equal(a.task.id, low.taskIds[0], 'однаковий бал → раніший термін у слоті');
85  void high;
86  // приймальник: своя роль порожня → напрямок «міжсклад», потім повернення
87  const r1 = await take(wh, ['receiving', 'transfer', 'returns'], T(9));
88  assert.equal(r1.stage, 'напрямок transfer');
89  await take(wh, ['receiving', 'transfer', 'returns'], T(9));
90  const r3 = await take(wh, ['receiving', 'transfer', 'returns'], T(9));
91  assert.equal(r3.task.id, ret.taskIds[0], 'повернення — коли інших немає, хоча термін повернення найраніший');
92});
93
94test('горизонт «немає на 5 годин»: своя роль має лише задачу на завтра → комірник допомагає іншій ролі', async () => {
95  const wh = await warehouse();
96  const p = await lab.product();
97  await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'supply', lines: [{ productId: p.id, qty: 5 }], at: T(9) });   // термін +24 год
98  const tr = await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'transfer', lines: [{ productId: p.id, qty: 1 }], at: T(9) });
99  const got = await take(wh, ['receiving', 'transfer'], T(9), { horizon: '5h' });
100  assert.equal(got.task.id, tr.taskIds[0]);
101  const none = await take(wh, ['receiving', 'transfer'], T(9), { horizon: 'none' });
102  assert.equal(none.task.type, 'putaway', 'горизонт none — своя роль, будь-який термін');
103});
104
105test('переривання: задача повертається в чергу, прогрес по рядках зберігається, продовжує інший', async () => {
106  const wh = await warehouse();
107  const [p1, p2] = [await lab.product(), await lab.product()];
108  await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'supply', lines: [{ productId: p1.id, qty: 3 }, { productId: p2.id, qty: 4 }], at: T(8) });
109  const t = await take(wh, ['receiving'], T(9), { horizon: 'none' });
110  await lab.api.post(`/api/tasks/${t.task.id}/lines/${t.lines[0].id}/done`, { at: T(9, 1) });
111  await lab.api.post(`/api/tasks/${t.task.id}/pause`, { at: T(9, 2) });
112  const again = await lab.api.post('/api/tasks/next', { warehouseId: wh, workerId: 7, roles: ['receiving'], horizon: 'none', at: T(9, 3) });
113  assert.equal(again.task.id, t.task.id);
114  assert.equal(again.lines.length, 1, 'лишився один невиконаний рядок');
115  await finish(again.task, again.lines, T(9, 4));
116  const s = await lab.api.get('/api/tasks/report', { warehouseId: wh, at: T(10) });
117  const kinds = Object.fromEntries(s.events.map((e: any) => [e.kind, e.n]));
118  assert.deepEqual([kinds.pause, kinds.resume, kinds.done], [1, 1, 1]);
119});
120
121test('SKIP LOCKED: 10 комірників одночасно — 10 різних задач', async () => {
122  const wh = await warehouse();
123  const p = await lab.product();
124  for (let i = 0; i < 10; i++) await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'transfer', lines: [{ productId: p.id, qty: 1 }], at: T(8) });
125  const got = await Promise.all(Array.from({ length: 10 }, (_, i) =>
126    lab.api.post('/api/tasks/next', { warehouseId: wh, workerId: 100 + i, roles: ['transfer'], at: T(9) })));
127  assert.equal(new Set(got.map((g: any) => g.task.id)).size, 10);
128});
129
130test('ескалація: наближається термін → 1, прострочено → 2', async () => {
131  const wh = await warehouse();
132  const p = await lab.product();
133  await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'transfer', lines: [{ productId: p.id, qty: 1 }], at: T(8), dueAt: T(10) });
134  assert.deepEqual(await lab.api.post('/api/tasks/escalate', { warehouseId: wh, at: T(9, 30) }), { near: 1, overdue: 0 });
135  assert.deepEqual(await lab.api.post('/api/tasks/escalate', { warehouseId: wh, at: T(10, 1) }), { near: 0, overdue: 1 });
136});
137
138test('fifo: без крос-доку — товар з фури лише на полицю, замовлення резервує після розкладання', async () => {
139  const wh = await warehouse();
140  const p = await lab.product();
141  const order = await lab.api.post('/api/tasks/customer-orders', { warehouseId: wh, lines: [{ productId: p.id, qty: 4 }], dueAt: T(11), at: T(8), policy: 'fifo' });
142  const inb = await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'supply', lines: [{ productId: p.id, qty: 10 }], at: T(9), policy: 'fifo' });
143  assert.equal(inb.crossdockQty, 0);
144  const put = await take(wh, ['receiving'], T(9), { policy: 'fifo' });
145  const r = await lab.api.post(`/api/tasks/${put.task.id}/lines/${put.lines[0].id}/done`, { at: T(9, 30), policy: 'fifo' });
146  assert.equal(r.ordersReady, 1, 'після розкладання замовлення зарезервувало полицю й готове');
147  void order;
148});
149
150test('комірник із задачею в роботі нову не бере — TASK_WORKER_BUSY', async () => {
151  const wh = await warehouse();
152  const p = await lab.product();
153  for (let i = 0; i < 2; i++) await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'transfer', lines: [{ productId: p.id, qty: 1 }], at: T(8) });
154  await lab.api.post('/api/tasks/next', { warehouseId: wh, workerId: 999, roles: ['transfer'], at: T(9) });
155  await assert.rejects(lab.api.post('/api/tasks/next', { warehouseId: wh, workerId: 999, roles: ['transfer'], at: T(9) }), { status: 422, code: 'TASK_WORKER_BUSY' });
156});
157
158test('крос-док на ходу в задачі, що вже в роботі: рядок «на пакування» в тій самій задачі, підказаний наступним', async () => {
159  const wh = await warehouse();
160  const [p1, p2] = [await lab.product(), await lab.product()];
161  await lab.api.post('/api/tasks/inbound', { warehouseId: wh, kind: 'supply', lines: [{ productId: p1.id, qty: 10 }, { productId: p2.id, qty: 20 }], at: T(8) });
162  const t = await take(wh, ['receiving'], T(8, 1), { horizon: 'none' });
163  const first = await lab.api.post(`/api/tasks/${t.task.id}/lines/${t.lines[0].id}/done`, { at: T(8, 2) });
164  const order = await lab.api.post('/api/tasks/customer-orders', { warehouseId: wh, lines: [{ productId: p2.id, qty: 3 }], dueAt: T(11), at: T(8, 3) });
165  assert.deepEqual([order.crossdock, order.crossdockTaskId], [3, null], 'не окрема задача — рядок у задачі в роботі');
166  const r = await lab.api.post(`/api/tasks/${t.task.id}/lines/${first.next.id}/done`, { at: T(8, 4) });
167  assert.ok(r.next, 'ще є рядок');
168  const fin = await lab.api.post(`/api/tasks/${t.task.id}/lines/${r.next.id}/done`, { at: T(8, 5) });
169  assert.equal(fin.taskDone, true);
170  const pack = await take(wh, ['packing'], T(8, 6));
171  assert.equal(pack.task?.type, 'pack', '3 шт. уже на пакуванні — замовлення готове');
172});
173