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

tasks-inbound.ts

TypeScript · 89 рядків

1// POST /api/tasks/inbound — документ надходження (поставка у фурі, міжсклад, повернення) → задачі.
2//
3// r09: поставка й міжсклад спершу зіставляються з рядками замовлень клієнтів, що чекають товар (R-09.11, R-09.14):
4//      частина рядка поставки → задача «крос-док на пакування» з терміном і балом замовлення клієнта;
5//      решта → задача «на полицю» з нормативом терміну типу. Повернення — окрема задача класу 9 (R-09.6).
6// fifo: усе — на полицю.
7import { z } from 'zod';
8import { matchSupply, type WaitingLine } from '../domain/queue.ts';
9import type { Sql } from '../platform/db.ts';
10import { feature } from '../platform/http.ts';
11import { at, id, now, qty } from '../platform/schema.ts';
12import { Policy, insertTask } from './tasks-shared.ts';
13
14export const InboundInput = z.object({
15  warehouseId: id,
16  kind: z.enum(['supply', 'transfer', 'return']),
17  lines: z.array(z.object({ productId: id, qty })).min(1),
18  dueAt: z.iso.datetime({ offset: true }).nullish(),
19  policy: Policy,
20  at,
21});
22export type InboundInput = z.infer<typeof InboundInput>;
23
24export interface InboundOutput { docId: number; taskIds: number[]; crossdockLines: number; crossdockQty: number }
25
26export default feature({
27  name: 'tasksInbound',
28  method: 'POST',
29  path: '/api/tasks/inbound',
30  summary: 'R-09: документ надходження → задачі «на полицю» / «крос-док на пакування» / «огляд повернення»',
31  input: InboundInput,
32  tx: 'write',
33  run: (sql, input) => inbound(sql, input),
34});
35
36const TYPE = { supply: 'putaway', transfer: 'transfer_in', return: 'return' } as const;
37
38export async function inbound(sql: Sql, input: InboundInput): Promise<InboundOutput> {
39  const time = input.at ?? now();
40  const type = TYPE[input.kind];
41  const { id: docId } = await sql.one<{ id: number }>(`
42    INSERT INTO stock.inbound_doc (warehouse_id, kind, created_at, due_at)
43    SELECT :warehouseId, :kind, :at, coalesce(:dueAt::timestamptz, :at::timestamptz + norm_minutes * interval '1 minute')
44    FROM stock.task_type WHERE code = :type
45    RETURNING id`, { warehouseId: input.warehouseId, kind: input.kind, at: time, dueAt: input.dueAt ?? null, type });
46
47  const supply = new Map<number, number>();
48  for (const l of input.lines) supply.set(l.productId, (supply.get(l.productId) ?? 0) + l.qty);
49  const taskIds: number[] = [];
50  let crossdockLines = 0;
51  let crossdockQty = 0;
52
53  if (input.policy === 'r09' && input.kind !== 'return') {
54    const waiting = await sql.query<{ id: number; order_id: number; product_id: number; need: number; due_at: string; priority: number }>(`
55      SELECT cl.id, cl.order_id, cl.product_id, cl.qty - cl.shelf_qty - cl.crossdock_qty AS need, o.due_at, o.priority
56      FROM stock.customer_line cl JOIN stock.customer_order o ON o.id = cl.order_id
57      WHERE o.warehouse_id = :warehouseId AND o.status = 0 AND cl.product_id = ANY(:productIds::int[])
58        AND cl.shelf_qty + cl.crossdock_qty < cl.qty
59      ORDER BY cl.id
60      FOR UPDATE OF cl`, { warehouseId: input.warehouseId, productIds: [...supply.keys()] });
61    const assigned = matchSupply(supply, waiting.map((w): WaitingLine => ({
62      customerLineId: w.id, orderId: w.order_id, productId: w.product_id, need: w.need, dueAt: new Date(w.due_at).toISOString(), priority: w.priority,
63    })));
64    if (assigned.length) {
65      await sql.query(`
66        UPDATE stock.customer_line cl SET crossdock_qty = cl.crossdock_qty + a.q
67        FROM unnest(:ids::bigint[], :qtys::int[]) AS a(id, q) WHERE cl.id = a.id`,
68      { ids: assigned.map((a) => a.customerLineId), qtys: assigned.map((a) => a.qty) });
69      // задача крос-доку на кожне замовлення клієнта — з його терміном і балом
70      const byOrder = new Map<number, typeof assigned>();
71      for (const a of assigned) byOrder.set(a.orderId, [...(byOrder.get(a.orderId) ?? []), a]);
72      for (const [orderId, list] of byOrder) {
73        const w = waiting.find((x) => x.order_id === orderId)!;
74        taskIds.push(await insertTask(sql, {
75          warehouseId: input.warehouseId, type: 'crossdock', at: time, dueAt: new Date(w.due_at).toISOString(), priority: w.priority,
76          docId, orderId, lines: list.map((a) => ({ productId: a.productId, qty: a.qty, customerLineId: a.customerLineId })),
77        }));
78      }
79      for (const a of assigned) supply.set(a.productId, supply.get(a.productId)! - a.qty);
80      crossdockLines = assigned.length;
81      crossdockQty = assigned.reduce((s, a) => s + a.qty, 0);
82    }
83  }
84
85  const rest = [...supply].filter(([, q]) => q > 0).map(([productId, q]) => ({ productId, qty: q }));
86  if (rest.length) taskIds.unshift(await insertTask(sql, { warehouseId: input.warehouseId, type, at: time, dueAt: input.dueAt ?? null, docId, lines: rest }));
87  return { docId, taskIds, crossdockLines, crossdockQty };
88}
89