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

tasks-customer-order.ts

TypeScript · 172 рядків

1// POST /api/tasks/customer-orders — замовлення клієнта: звідки брати кожен рядок і задача пакування.
2//
3// r09 (R-09.11–R-09.13):
4//   • товар є в невиконаних рядках задач «на полицю» (фура вже на складі) і на полиці немає товару, строк якого спливає
5//     (менше expiryDays) → крос-док (зіставлення на ходу — лише для товарів цього замовлення):
6//       задача ще не взята  → частина рядка виділяється в окрему задачу «крос-док на пакування» з терміном і балом замовлення;
7//       задача в роботі     → частина рядка стає рядком «на пакування» тієї самої задачі; сервер підказує його комірнику
8//                             наступним (R-09.13, уточнення 10.10: «не на полицю клади, а на пакування передай»);
9//   • строк на полиці спливає → спершу полиця (FEFO), решта — крос-док;
10//   • чого бракує — резерв з полиці (available), а ще не вистачає — рядок чекає наступної поставки.
11// fifo: лише полиця, решта чекає.
12// Задача пакування створюється одразу; заблокована (стан 4), поки всі рядки не на місці.
13//
14// Порядок блокувань: product_stock товарів (ORDER BY product_id) → рядки задач → рядки замовлень (як у виконанні рядка).
15import { z } from 'zod';
16import { takeFromInbound } from '../domain/queue.ts';
17import type { Sql } from '../platform/db.ts';
18import { feature } from '../platform/http.ts';
19import { at, id, now, qty } from '../platform/schema.ts';
20import { PACK_LOCATION, Policy, insertTask } from './tasks-shared.ts';
21
22export const CustomerOrderInput = z.object({
23  warehouseId: id,
24  lines: z.array(z.object({ productId: id, qty })).min(1),
25  dueAt: z.iso.datetime({ offset: true }),
26  priority: z.number().int().default(50),
27  expiryDays: z.number().int().min(0).default(30),     // «строк спливає» на полиці (R-09.12, відкрите питання 2)
28  policy: Policy,
29  at,
30});
31export type CustomerOrderInput = z.infer<typeof CustomerOrderInput>;
32
33export interface CustomerOrderOutput { orderId: number; packTaskId: number; crossdockTaskId: number | null; shelf: number; crossdock: number; waiting: number; ready: boolean }
34
35export default feature({
36  name: 'tasksCustomerOrder',
37  method: 'POST',
38  path: '/api/tasks/customer-orders',
39  summary: 'R-09: замовлення клієнта — полиця / крос-док з фури (на ходу) / чекає; задача пакування',
40  input: CustomerOrderInput,
41  tx: 'write',
42  run: (sql, input) => customerOrder(sql, input),
43});
44
45export async function customerOrder(sql: Sql, input: CustomerOrderInput): Promise<CustomerOrderOutput> {
46  const time = input.at ?? now();
47  const demand = new Map<number, number>();
48  for (const l of input.lines) demand.set(l.productId, (demand.get(l.productId) ?? 0) + l.qty);
49  const productIds = [...demand.keys()].sort((a, b) => a - b);
50
51  const { id: orderId } = await sql.one<{ id: number }>(`
52    INSERT INTO stock.customer_order (warehouse_id, created_at, due_at, priority) VALUES (:warehouseId, :at, :dueAt, :priority)
53    RETURNING id`, { warehouseId: input.warehouseId, at: time, dueAt: input.dueAt, priority: input.priority });
54
55  await sql.query(`
56    INSERT INTO stock.product_stock (warehouse_id, product_id, quantity, available)
57    SELECT :warehouseId, p, 0, 0 FROM unnest(:productIds::int[]) AS p ORDER BY p
58    ON CONFLICT (warehouse_id, product_id) DO NOTHING`, { warehouseId: input.warehouseId, productIds });
59  const stock = new Map((await sql.query<{ product_id: number; available: number }>(`
60    SELECT product_id, available FROM stock.product_stock
61    WHERE warehouse_id = :warehouseId AND product_id = ANY(:productIds::int[])
62    ORDER BY product_id FOR UPDATE`, { warehouseId: input.warehouseId, productIds })).map((r) => [r.product_id, r.available]));
63
64  const inboundByProduct = new Map<number, { lineId: number; taskId: number; qty: number }[]>();
65  const taskStatus = new Map<number, number>();
66  const expiring = new Set<number>();
67  if (input.policy === 'r09') {
68    for (const r of await sql.query<{ id: number; task_id: number; product_id: number; qty: number; status: number }>(`
69      SELECT tl.id, tl.task_id, tl.product_id, tl.qty, t.status
70      FROM stock.task_line tl JOIN stock.task t ON t.id = tl.task_id
71      WHERE t.warehouse_id = :warehouseId AND t.status IN (0, 1, 2) AND t.type IN ('putaway', 'transfer_in')
72        AND NOT tl.done AND tl.customer_line_id IS NULL AND tl.product_id = ANY(:productIds::int[])
73      ORDER BY t.status, tl.id
74      FOR UPDATE OF tl`, { warehouseId: input.warehouseId, productIds })) {
75      inboundByProduct.set(r.product_id, [...(inboundByProduct.get(r.product_id) ?? []), { lineId: r.id, taskId: r.task_id, qty: r.qty }]);
76      taskStatus.set(r.task_id, r.status);
77    }
78    for (const r of await sql.query<{ product_id: number }>(`
79      SELECT DISTINCT product_id FROM stock.inventory_item
80      WHERE warehouse_id = :warehouseId AND product_id = ANY(:productIds::int[]) AND quantity > 0 AND location_id <> :pack
81        AND expiry_date < :at::date + :expiryDays::int`,
82    { warehouseId: input.warehouseId, productIds, pack: PACK_LOCATION, at: time, expiryDays: input.expiryDays })) expiring.add(r.product_id);
83  }
84
85  // рішення по кожному рядку
86  const plan = productIds.map((productId) => {
87    const qtyNeeded = demand.get(productId)!;
88    let available = stock.get(productId) ?? 0;
89    let shelf = 0;
90    let cross: { lineId: number; taskId: number; qty: number }[] = [];
91    const fromShelf = (n: number) => { const q = Math.min(n, available); available -= q; shelf += q; return n - q; };
92    const fromInbound = (n: number) => { cross = takeFromInbound(inboundByProduct.get(productId) ?? [], n); return n - cross.reduce((s, c) => s + c.qty, 0); };
93    let left = qtyNeeded;
94    if (input.policy === 'r09' && !expiring.has(productId)) left = fromShelf(fromInbound(left));
95    else if (input.policy === 'r09') left = fromInbound(fromShelf(left));
96    else left = fromShelf(left);
97    return { productId, qty: qtyNeeded, shelf, cross, crossQty: cross.reduce((s, c) => s + c.qty, 0), waiting: left };
98  });
99
100  const lines = await sql.query<{ id: number; product_id: number }>(`
101    INSERT INTO stock.customer_line (order_id, product_id, qty, shelf_qty, crossdock_qty)
102    SELECT :orderId, p, q, s, c FROM unnest(:productIds::int[], :qtys::int[], :shelf::int[], :cross::int[]) AS x(p, q, s, c)
103    RETURNING id, product_id`, {
104    orderId, productIds: plan.map((p) => p.productId), qtys: plan.map((p) => p.qty), shelf: plan.map((p) => p.shelf), cross: plan.map((p) => p.crossQty),
105  });
106  const lineOf = new Map(lines.map((l) => [l.product_id, l.id]));
107
108  // резерв полиці
109  const reserve = plan.filter((p) => p.shelf > 0);
110  if (reserve.length) {
111    await sql.query(`
112      UPDATE stock.product_stock s SET available = s.available - r.q
113      FROM unnest(:productIds::int[], :qtys::int[]) AS r(p, q)
114      WHERE s.warehouse_id = :warehouseId AND s.product_id = r.p`,
115    { warehouseId: input.warehouseId, productIds: reserve.map((p) => p.productId), qtys: reserve.map((p) => p.shelf) });
116  }
117
118  // крос-док на ходу: виділити частини з рядків задач «на полицю» (рядок, що спорожнів, — видалити; задача без рядків — виконана)
119  const parts = plan.flatMap((p) => p.cross);
120  let crossdockTaskId: number | null = null;
121  if (parts.length) {
122    await sql.query(`
123      WITH taken AS (
124        SELECT * FROM unnest(:lineIds::bigint[], :qtys::int[]) AS t(id, q)
125      ), shrunk AS (
126        UPDATE stock.task_line tl SET qty = tl.qty - t.q FROM taken t WHERE tl.id = t.id AND tl.qty > t.q RETURNING tl.id
127      ), dropped AS (
128        DELETE FROM stock.task_line tl USING taken t WHERE tl.id = t.id AND tl.qty = t.q RETURNING tl.task_id
129      ), events AS (
130        INSERT INTO stock.task_event (task_id, at, kind)
131        SELECT DISTINCT tid, :at::timestamptz, 'split' FROM unnest(:taskIds::bigint[]) AS tid
132        RETURNING 1
133      )
134      SELECT (SELECT count(*) FROM shrunk) + (SELECT count(*) FROM dropped) AS n`,
135    { lineIds: parts.map((c) => c.lineId), qtys: parts.map((c) => c.qty), taskIds: parts.map((c) => c.taskId), at: time });
136    await sql.query(`
137      UPDATE stock.task t SET status = 3, done_at = :at
138      WHERE t.id = ANY(:taskIds::bigint[]) AND t.status = 0 AND NOT EXISTS (SELECT 1 FROM stock.task_line tl WHERE tl.task_id = t.id)`,
139    { taskIds: [...new Set(parts.map((c) => c.taskId))], at: time });
140    // задачі в роботі: рядок «на пакування» в тій самій задачі
141    const inWork = plan.flatMap((p) => p.cross.filter((c) => taskStatus.get(c.taskId) !== 0).map((c) => ({ ...c, productId: p.productId })));
142    if (inWork.length) {
143      await sql.query(`
144        INSERT INTO stock.task_line (task_id, product_id, qty, customer_line_id, source)
145        SELECT t, p, q, cl, 'crossdock' FROM unnest(:taskIds::bigint[], :productIds::int[], :qtys::int[], :customerLineIds::bigint[]) AS x(t, p, q, cl)`, {
146        taskIds: inWork.map((c) => c.taskId), productIds: inWork.map((c) => c.productId), qtys: inWork.map((c) => c.qty),
147        customerLineIds: inWork.map((c) => lineOf.get(c.productId)!),
148      });
149    }
150    // ще не взяті: окрема задача крос-доку з терміном і балом замовлення
151    const separate = plan.map((p) => ({ productId: p.productId, qty: p.cross.filter((c) => taskStatus.get(c.taskId) === 0).reduce((s, c) => s + c.qty, 0) }))
152      .filter((x) => x.qty > 0);
153    if (separate.length) {
154      crossdockTaskId = await insertTask(sql, {
155        warehouseId: input.warehouseId, type: 'crossdock', at: time, dueAt: input.dueAt, priority: input.priority, orderId,
156        lines: separate.map((x) => ({ productId: x.productId, qty: x.qty, customerLineId: lineOf.get(x.productId)! })),
157      });
158    }
159  }
160
161  const ready = plan.every((p) => p.shelf === p.qty);
162  await sql.query('UPDATE stock.customer_order SET status = CASE WHEN :ready THEN 1 ELSE 0 END, waited = NOT :ready WHERE id = :orderId', { orderId, ready });
163  const packTaskId = await insertTask(sql, {
164    warehouseId: input.warehouseId, type: 'pack', at: time, dueAt: input.dueAt, priority: input.priority, orderId, status: ready ? 0 : 4,
165    lines: plan.map((p) => ({ productId: p.productId, qty: p.qty, customerLineId: lineOf.get(p.productId)!, source: p.crossQty ? 'crossdock' : 'shelf' })),
166  });
167  return {
168    orderId, packTaskId, crossdockTaskId, ready,
169    shelf: plan.reduce((s, p) => s + p.shelf, 0), crossdock: plan.reduce((s, p) => s + p.crossQty, 0), waiting: plan.reduce((s, p) => s + p.waiting, 0),
170  };
171}
172