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

tasks-line-done.ts

TypeScript · 105 рядків

1// POST /api/tasks/:taskId/lines/:lineId/done — комірник виконав рядок задачі. Рух запасу — тими самими функціями receive()/issue():
2//
3//   на полицю / міжсклад / повернення → приймання в комірку товару; потім резерв під рядки замовлень, що чекали (satisfyWaiting);
4//   крос-док (задача крос-доку або рядок «на пакування» в задачі «на полицю») → приймання в зону пакування (P-01-01)
5//     і одразу резерв під своє замовлення; замовлення готове → пакування розблоковано;
6//   пакування → по рядку нічого; останній рядок — резерви повертаються в available і замовлення видається (issue, продаж).
7// Останній рядок закриває задачу (стан 3). Прогрес — по рядках (R-09.10: призупинену задачу продовжує будь-хто).
8// Відповідь підказує наступний рядок: спершу «на пакування» (вони могли з'явитись, поки задача в роботі), потім за порядком.
9//
10// Порядок блокувань: product_stock товару (receive / явне блокування) → рядки задачі й замовлення.
11import { z } from 'zod';
12import { PackType, TxType } from '../domain/codes.ts';
13import { DomainError } from '../domain/errors.ts';
14import type { Sql } from '../platform/db.ts';
15import { feature } from '../platform/http.ts';
16import { at, id, now } from '../platform/schema.ts';
17import { issue } from './issue.ts';
18import { receive } from './receive.ts';
19import { PACK_LOCATION, Policy, refreshOrders, satisfyWaiting, shelfLocation } from './tasks-shared.ts';
20
21export const LineDoneInput = z.object({ taskId: id, lineId: id, workerId: z.number().int().nullish(), policy: Policy, at });
22export type LineDoneInput = z.infer<typeof LineDoneInput>;
23
24export interface LineDoneOutput { taskDone: boolean; orderShipped: boolean; ordersReady: number; next: { id: number; product_id: number; qty: number; customer_line_id: number | null; source: string | null; shelf_qty: number | null; crossdock_qty: number | null } | null }
25
26export default feature({
27  name: 'tasksLineDone',
28  method: 'POST',
29  path: '/api/tasks/:taskId/lines/:lineId/done',
30  summary: 'R-09: виконати рядок задачі — приймання на полицю / на пакування, відвантаження замовлення після пакування',
31  input: LineDoneInput,
32  tx: 'write',
33  run: (sql, input) => lineDone(sql, input),
34});
35
36export async function lineDone(sql: Sql, input: LineDoneInput): Promise<LineDoneOutput> {
37  const time = input.at ?? now();
38  const [line] = await sql.query<{ product_id: number; qty: number; customer_line_id: number | null; done: boolean; type: string; warehouse_id: number; order_id: number | null; customer_order_id: number | null; status: number }>(`
39    SELECT tl.product_id, tl.qty, tl.customer_line_id, tl.done, t.type, t.warehouse_id, t.order_id, cl.order_id AS customer_order_id, t.status
40    FROM stock.task_line tl JOIN stock.task t ON t.id = tl.task_id LEFT JOIN stock.customer_line cl ON cl.id = tl.customer_line_id
41    WHERE tl.id = :lineId AND tl.task_id = :taskId`, { lineId: input.lineId, taskId: input.taskId });
42  if (!line) throw new DomainError('TASK_LINE_NOT_FOUND', `Рядка ${input.lineId} у задачі ${input.taskId} немає`);
43  if (line.done) throw new DomainError('TASK_LINE_DONE', 'Рядок уже виконано');
44  if (line.status !== 1) throw new DomainError('TASK_NOT_IN_WORK', 'Задача не в роботі — спершу взяти її (POST /api/tasks/next)');
45
46  const wh = line.warehouse_id;
47  const unit = [{ packType: PackType.unit, packSize: 1, packCount: line.qty }];
48  let ready: number[] = [];
49  const toPack = line.type === 'crossdock' || (line.customer_line_id != null && line.type !== 'pack');
50  if (!toPack && (line.type === 'putaway' || line.type === 'transfer_in' || line.type === 'return')) {
51    await receive(sql, { warehouseId: wh, productId: line.product_id, lines: unit, locationId: shelfLocation(line.product_id), at: time },
52      line.type === 'transfer_in' ? TxType.TRANSFER_IN : TxType.RECEIVE);
53    ready = await satisfyWaiting(sql, wh, line.product_id, input.policy);
54  } else if (toPack) {
55    await receive(sql, { warehouseId: wh, productId: line.product_id, lines: unit, locationId: PACK_LOCATION, at: time });
56    await sql.query(`
57      WITH cl AS (
58        UPDATE stock.customer_line SET crossdock_done = crossdock_done + :qty WHERE id = :customerLineId RETURNING 1
59      )
60      UPDATE stock.product_stock SET available = available - :qty
61      WHERE warehouse_id = :wh AND product_id = :productId AND EXISTS (SELECT 1 FROM cl)`,
62    { qty: line.qty, customerLineId: line.customer_line_id, wh, productId: line.product_id });
63    ready = [line.customer_order_id!];
64  }
65
66  const { left } = await sql.one<{ left: number }>(`
67    WITH d AS (
68      UPDATE stock.task_line SET done = true WHERE id = :lineId RETURNING 1
69    ), e AS (
70      INSERT INTO stock.task_event (task_id, at, kind, worker_id) VALUES (:taskId, :at, 'line', :workerId)
71    )
72    SELECT count(*)::int AS left FROM stock.task_line WHERE task_id = :taskId AND NOT done AND id <> :lineId`,
73  { lineId: input.lineId, taskId: input.taskId, at: time, workerId: input.workerId ?? null });
74  const ordersReady = await refreshOrders(sql, ready);
75
76  let orderShipped = false;
77  if (left === 0) {
78    await sql.query(`
79      WITH t AS (UPDATE stock.task SET status = 3, done_at = :at, worker_id = coalesce(worker_id, :workerId) WHERE id = :taskId RETURNING id)
80      INSERT INTO stock.task_event (task_id, at, kind, worker_id) SELECT id, :at, 'done', :workerId FROM t`,
81    { taskId: input.taskId, at: time, workerId: input.workerId ?? null });
82    if (line.type === 'pack') {
83      const lines = await sql.query<{ product_id: number; qty: number; reserved: number }>(`
84        SELECT product_id, qty, shelf_qty + crossdock_done AS reserved FROM stock.customer_line WHERE order_id = :orderId ORDER BY product_id`,
85      { orderId: line.order_id });
86      // резерви повертаються в available і цим самим оператором видачі списуються з quantity та available
87      await sql.query(`
88        UPDATE stock.product_stock s SET available = s.available + r.q
89        FROM unnest(:productIds::int[], :qtys::int[]) AS r(p, q)
90        WHERE s.warehouse_id = :wh AND s.product_id = r.p`,
91      { wh, productIds: lines.map((l) => l.product_id), qtys: lines.map((l) => l.reserved) });
92      await issue(sql, { warehouseId: wh, lines: lines.map((l) => ({ productId: l.product_id, qty: l.qty })), txType: TxType.ISSUE, partial: false, docId: line.order_id, at: time });
93      await sql.query('UPDATE stock.customer_order SET status = 2, done_at = :at WHERE id = :orderId', { orderId: line.order_id, at: time });
94      orderShipped = true;
95    }
96  }
97  const [next] = left === 0 ? [] : await sql.query<NonNullable<LineDoneOutput['next']>>(`
98    SELECT tl.id, tl.product_id, tl.qty, tl.customer_line_id, tl.source, cl.shelf_qty, cl.crossdock_qty
99    FROM stock.task_line tl LEFT JOIN stock.customer_line cl ON cl.id = tl.customer_line_id
100    WHERE tl.task_id = :taskId AND NOT tl.done
101    ORDER BY tl.customer_line_id IS NULL, tl.id
102    LIMIT 1`, { taskId: input.taskId });
103  return { taskDone: left === 0, orderShipped, ordersReady, next: next ?? null };
104}
105