techtools

issue.ts

TypeScript · 250 рядків

1// POST /api/issues — видача (продаж опт/роздріб) або списання документа з кількох рядків.
2//
3// Чотири звертання до бази незалежно від кількості рядків документа:
4//   1. lock  — рядки product_stock документа, ORDER BY product_id FOR UPDATE (єдиний порядок блокувань у системі);
5//   2. read  — активні записи inventory_item цих товарів;
6//   (відбір — у пам'яті, domain/allocate.ts)
7//   3. write — усі зміни одним оператором: новий розсип (upsert), прирости, видалення вичерпаних, історія, журнал, product_stock;
8//   (4. commit — платформа)
9//
10// Інваріанти, які тримає SQL:
11//   • lock і read — ОКРЕМІ оператори: в READ COMMITTED один оператор бачить знімок до блокування і читає застарілі записи (R-03 §3.4);
12//   • оновлення записів — приростами (quantity + dq), а не абсолютними значеннями: паралельне приймання доливає в розсип;
13//   • історія — ОДИН рядок на запис (R-07 §10.2): перша частина, що пішла (крім постійного розсипу), вставляє клон запису
14//     зі знімка ДО оператора (усі CTE бачать один знімок); наступні додаються до нього (ON CONFLICT DO UPDATE, прирости);
15//   • розділи історії за датою закриття (R-07 §10.3): поки запис лежить — рядок у розділі відкритих (closed_at = infinity);
16//     частина, що вичерпала запис, — DELETE з відкритих + INSERT зведеного рядка в місяць закриття (одне перенесення
17//     за життя запису; ON CONFLICT DO UPDATE не переносить рядки між розділами).
18//     Частини одного запису за документ зводяться заздалегідь (departuresByItem) — один рядок не можна оновити двічі
19//     одним оператором; вичерпаний запис видаляється з inventory_item;
20//   • журнал несе pack_type / pack_size / pack_delta — з якого пакування рух (R-07 §10).
21import { z } from 'zod';
22import { allocate, departuresByItem, newAllocResult, type AllocRow, type IssuedLot } from '../domain/allocate.ts';
23import { PackType, Status, TxType } from '../domain/codes.ts';
24import { DomainError } from '../domain/errors.ts';
25import type { Sql } from '../platform/db.ts';
26import { feature } from '../platform/http.ts';
27import { at, id, now, qty } from '../platform/schema.ts';
28
29export const IssueInput = z.object({
30  warehouseId: id,
31  kind: z.enum(['sale', 'write_off']).default('sale'),
32  lines: z.array(z.object({ productId: id, qty })).min(1),
33  partial: z.boolean().default(true),     // false — нестача будь-якого рядка скасовує весь документ
34  docId: z.number().int().nullish(),
35  userId: z.number().int().nullish(),
36  at,
37});
38export type IssueInput = z.infer<typeof IssueInput>;
39
40export interface IssueOutput {
41  requested: number;
42  issued: number;
43  short: number;
44  openedPacks: number;
45  cutContainers: number;
46  journalRows: number;
47  lots: IssuedLot[];         // що фактично видано: товар, кількість, строк
48}
49
50export default feature({
51  name: 'issue',
52  method: 'POST',
53  path: '/api/issues',
54  summary: 'Видача або списання документа: відбір R-02.7 + FEFO, розкриття пакувань, архів вичерпаних записів',
55  input: IssueInput,
56  tx: 'write',
57  affects: (i) => i.lines.map((l) => l.productId),
58  run: (sql, input) => issue(sql, { ...input, txType: input.kind === 'write_off' ? TxType.WRITE_OFF : TxType.ISSUE }),
59});
60
61export interface IssueDoc {
62  warehouseId: number;
63  lines: { productId: number; qty: number }[];
64  txType: number;            // ISSUE, WRITE_OFF або TRANSFER_OUT (transfer.ts)
65  partial: boolean;
66  docId?: number | null;
67  userId?: number | null;
68  at?: string;
69}
70
71export async function issue(sql: Sql, doc: IssueDoc): Promise<IssueOutput> {
72  const at = doc.at ?? now();
73  const demand = new Map<number, number>();
74  for (const l of doc.lines) demand.set(l.productId, (demand.get(l.productId) ?? 0) + l.qty);
75  const productIds = [...demand.keys()].sort((a, b) => a - b);
76
77  const locked = await sql.query<{ product_id: number }>(`
78    SELECT product_id FROM stock.product_stock
79    WHERE warehouse_id = :warehouseId AND product_id = ANY(:productIds::int[])
80    ORDER BY product_id
81    FOR UPDATE`, { warehouseId: doc.warehouseId, productIds });
82
83  const items = await sql.query(`
84    SELECT id, product_id, is_container, pack_type, pack_size, pack_count, quantity, contained_in_id, location_id,
85           mfg_date, expiry_date, received_at, serial_number IS NOT NULL AS serial
86    FROM stock.inventory_item
87    WHERE warehouse_id = :warehouseId AND product_id = ANY(:productIds::int[]) AND status = ${Status.ACTIVE}`,
88  { warehouseId: doc.warehouseId, productIds: locked.map((r) => r.product_id) });
89
90  const byProduct = new Map<number, AllocRow[]>();
91  for (const r of items) {
92    const list = byProduct.get(r.product_id) ?? [];
93    list.push({
94      id: r.id, productId: r.product_id, isContainer: r.is_container, packType: r.pack_type, packSize: r.pack_size,
95      packCount: r.pack_count, quantity: r.quantity, containedInId: r.contained_in_id, locationId: r.location_id,
96      expiryDate: r.expiry_date, mfgDate: r.mfg_date, receivedAt: r.received_at, serial: r.serial,
97      origCount: r.pack_count, origQuantity: r.quantity,
98    });
99    byProduct.set(r.product_id, list);
100  }
101  const out = newAllocResult();
102  for (const [productId, q] of demand) allocate(byProduct.get(productId) ?? [], productId, q, out, doc.txType);
103  if (out.short && !doc.partial) {
104    throw new DomainError('INSUFFICIENT_STOCK', `Не вистачає ${out.short} од.; документ не проведено`, { short: out.short, issued: out.issued });
105  }
106
107  const rows = [...out.rows];
108  const created = rows.filter((r) => r.isNew);
109  const changed = rows.filter((r) => !r.isNew && !r.archived && (r.packCount !== r.origCount || r.quantity !== r.origQuantity || r.freed));
110  const finished = rows.filter((r) => !r.isNew && r.archived);
111  const gone = departuresByItem(out.departures);
112  let journalRows = 0;
113  if (out.journal.length) {
114    const r = await sql.one<{ journal: number }>(`
115      WITH new_loose AS (
116        SELECT * FROM unnest(:newTempIds::bigint[], :newProductIds::int[], :newQty::int[], :newLocations::int[],
117                             :newMfg::date[], :newExpiry::date[], :newReceived::timestamptz[], :newSources::bigint[])
118          AS n(temp_id, product_id, qty, location_id, mfg_date, expiry_date, received_at, source_id)
119      ), upserted AS (
120        INSERT INTO stock.inventory_item (warehouse_id, product_id, pack_type, status, pack_size, pack_count, quantity,
121                                          source_id, mfg_date, expiry_date, received_at, location_id)
122        SELECT :warehouseId, n.product_id, ${PackType.unit}, ${Status.ACTIVE}, 1, n.qty, n.qty,
123               n.source_id, n.mfg_date, n.expiry_date, n.received_at, n.location_id
124        FROM new_loose n
125        -- ключ постійного розсипу = унікальний індекс ux_item_loose
126        ON CONFLICT (warehouse_id, product_id, location_id, status, (coalesce(expiry_date, 'infinity'::date)))
127                WHERE pack_type = 0 AND NOT is_container AND contained_in_id IS NULL AND serial_number IS NULL
128        DO UPDATE SET quantity   = stock.inventory_item.quantity + EXCLUDED.quantity,
129                      pack_count = stock.inventory_item.pack_count + EXCLUDED.pack_count
130        RETURNING id, product_id, location_id, expiry_date
131      ), id_map AS (
132        -- тимчасовий id відбору (< 0) → справжній id запису
133        SELECT n.temp_id, u.id FROM new_loose n
134        JOIN upserted u ON u.product_id = n.product_id AND u.location_id = n.location_id AND u.expiry_date IS NOT DISTINCT FROM n.expiry_date
135      ), changed AS (
136        UPDATE stock.inventory_item i
137           SET pack_count = i.pack_count + c.d_count,
138               quantity = i.quantity + c.d_qty,
139               contained_in_id = CASE WHEN c.freed THEN NULL ELSE i.contained_in_id END
140        FROM unnest(:changedIds::bigint[], :changedDCount::int[], :changedDQty::int[], :changedFreed::boolean[]) AS c(id, d_count, d_qty, freed)
141        WHERE i.id = c.id
142        RETURNING 1
143      ), removed AS (
144        DELETE FROM stock.inventory_item WHERE id = ANY(:finishedIds::bigint[])
145        RETURNING 1
146      ), gone AS (
147        SELECT * FROM unnest(:goneIds::bigint[], :goneCount::int[], :goneQty::int[], :goneIssued::int[], :goneOpened::int[], :goneWrittenOff::int[],
148                             :goneTransferred::int[], :goneStatus::smallint[], :goneType::smallint[], :goneTo::bigint[], :goneExhausted::boolean[])
149          AS d(item_id, pack_count, quantity, issued, opened, written_off, transferred, status, tx_type, to_item_id, exhausted)
150      ), history_open AS (
151        -- запис ще лежить: рядок у розділі відкритих (closed_at = infinity); перша частина — клон зі знімка до оператора,
152        -- наступні — прирости до того ж рядка
153        INSERT INTO stock.inventory_item_history AS h (id, warehouse_id, product_id, is_container, pack_type, status, pack_size, pack_count, quantity,
154                                                       contained_in_id, source_id, receipt_id, mfg_date, expiry_date, received_at, location_id,
155                                                       label_code, serial_number, received_count, received_quantity,
156                                                       issued_count, opened_count, written_off_count, transferred_count,
157                                                       first_event_at, last_event_at, last_event_type, last_doc_id, to_item_id, exhausted, closed_at)
158        SELECT i.id, i.warehouse_id, i.product_id, i.is_container, i.pack_type, d.status, i.pack_size, d.pack_count, d.quantity,
159               i.contained_in_id, i.source_id, i.receipt_id, i.mfg_date, i.expiry_date, i.received_at, i.location_id,
160               i.label_code, i.serial_number, i.received_count, i.received_quantity,
161               d.issued, d.opened, d.written_off, d.transferred,
162               :at, :at, d.tx_type, :docId, coalesce(m.id, d.to_item_id), false, 'infinity'
163        FROM gone d
164        JOIN stock.inventory_item i ON i.id = d.item_id
165        LEFT JOIN id_map m ON m.temp_id = d.to_item_id
166        WHERE NOT d.exhausted
167        ON CONFLICT (id, closed_at) DO UPDATE
168          SET pack_count        = h.pack_count + EXCLUDED.pack_count,
169              quantity          = h.quantity + EXCLUDED.quantity,
170              issued_count      = h.issued_count + EXCLUDED.issued_count,
171              opened_count      = h.opened_count + EXCLUDED.opened_count,
172              written_off_count = h.written_off_count + EXCLUDED.written_off_count,
173              transferred_count = h.transferred_count + EXCLUDED.transferred_count,
174              status            = EXCLUDED.status,
175              contained_in_id   = EXCLUDED.contained_in_id,
176              last_event_at     = EXCLUDED.last_event_at,
177              last_event_type   = EXCLUDED.last_event_type,
178              last_doc_id       = EXCLUDED.last_doc_id,
179              to_item_id        = coalesce(EXCLUDED.to_item_id, h.to_item_id)
180        RETURNING 1
181      ), history_reopened AS (
182        -- запис вичерпався: забрати його рядок із розділу відкритих (якщо частини йшли раніше) …
183        DELETE FROM stock.inventory_item_history h
184        USING gone d
185        WHERE d.exhausted AND h.id = d.item_id AND h.closed_at = 'infinity'
186        RETURNING h.*
187      ), history_closed AS (
188        -- … і вставити зведений рядок у місяць закриття — єдине перенесення рядка за життя запису
189        INSERT INTO stock.inventory_item_history (id, warehouse_id, product_id, is_container, pack_type, status, pack_size, pack_count, quantity,
190                                                  contained_in_id, source_id, receipt_id, mfg_date, expiry_date, received_at, location_id,
191                                                  label_code, serial_number, received_count, received_quantity,
192                                                  issued_count, opened_count, written_off_count, transferred_count,
193                                                  first_event_at, last_event_at, last_event_type, last_doc_id, to_item_id, exhausted, closed_at)
194        SELECT i.id, i.warehouse_id, i.product_id, i.is_container, i.pack_type, d.status, i.pack_size,
195               coalesce(o.pack_count, 0) + d.pack_count, coalesce(o.quantity, 0) + d.quantity,
196               i.contained_in_id, i.source_id, i.receipt_id, i.mfg_date, i.expiry_date, i.received_at, i.location_id,
197               i.label_code, i.serial_number, i.received_count, i.received_quantity,
198               coalesce(o.issued_count, 0) + d.issued, coalesce(o.opened_count, 0) + d.opened,
199               coalesce(o.written_off_count, 0) + d.written_off, coalesce(o.transferred_count, 0) + d.transferred,
200               coalesce(o.first_event_at, :at), :at, d.tx_type, :docId, coalesce(m.id, d.to_item_id, o.to_item_id), true, :at
201        FROM gone d
202        JOIN stock.inventory_item i ON i.id = d.item_id
203        LEFT JOIN history_reopened o ON o.id = d.item_id
204        LEFT JOIN id_map m ON m.temp_id = d.to_item_id
205        WHERE d.exhausted
206        RETURNING 1
207      ), journal AS (
208        INSERT INTO stock.inventory_transaction (created_at, warehouse_id, type, product_id, item_id, qty_delta, doc_id, related_item_id, user_id,
209                                                 pack_type, pack_size, pack_delta)
210        SELECT :at, :warehouseId, j.type, j.product_id, coalesce(m1.id, j.item_id), j.delta, :docId, coalesce(m2.id, j.related_id), :userId,
211               j.pack_type, j.pack_size, j.pack_delta
212        FROM unnest(:jType::smallint[], :jProductIds::int[], :jItemIds::bigint[], :jDelta::int[], :jRelated::bigint[],
213                    :jPackType::smallint[], :jPackSize::int[], :jPackDelta::int[])
214          AS j(type, product_id, item_id, delta, related_id, pack_type, pack_size, pack_delta)
215        LEFT JOIN id_map m1 ON m1.temp_id = j.item_id
216        LEFT JOIN id_map m2 ON m2.temp_id = j.related_id
217        RETURNING 1
218      ), stock_rows AS (
219        UPDATE stock.product_stock s SET quantity = s.quantity + d.delta, available = s.available + d.delta
220        FROM unnest(:stockProductIds::int[], :stockDelta::int[]) AS d(product_id, delta)
221        WHERE s.warehouse_id = :warehouseId AND s.product_id = d.product_id
222        RETURNING 1
223      )
224      SELECT (SELECT count(*) FROM journal)::int AS journal, (SELECT count(*) FROM changed) AS changed,
225             (SELECT count(*) FROM history_open) + (SELECT count(*) FROM history_closed) AS history, (SELECT count(*) FROM stock_rows) AS stock_rows`, {
226      warehouseId: doc.warehouseId, at, docId: doc.docId ?? null, userId: doc.userId ?? null,
227      newTempIds: created.map((r) => r.id), newProductIds: created.map((r) => r.productId), newQty: created.map((r) => r.quantity),
228      newLocations: created.map((r) => r.locationId), newMfg: created.map((r) => r.mfgDate), newExpiry: created.map((r) => r.expiryDate),
229      newReceived: created.map((r) => r.receivedAt), newSources: created.map((r) => r.sourceId ?? null),
230      changedIds: changed.map((r) => r.id), changedDCount: changed.map((r) => r.packCount - r.origCount),
231      changedDQty: changed.map((r) => r.quantity - r.origQuantity), changedFreed: changed.map((r) => !!r.freed),
232      finishedIds: finished.map((r) => r.id),
233      goneIds: gone.map((d) => d.itemId), goneCount: gone.map((d) => d.packCount), goneQty: gone.map((d) => d.quantity),
234      goneIssued: gone.map((d) => d.issued), goneOpened: gone.map((d) => d.opened), goneWrittenOff: gone.map((d) => d.writtenOff),
235      goneTransferred: gone.map((d) => d.transferred),
236      goneStatus: gone.map((d) => d.status), goneType: gone.map((d) => d.txType), goneTo: gone.map((d) => d.toItemId),
237      goneExhausted: gone.map((d) => d.exhausted),
238      jType: out.journal.map((j) => j.type), jProductIds: out.journal.map((j) => j.productId), jItemIds: out.journal.map((j) => j.itemId),
239      jDelta: out.journal.map((j) => j.delta), jRelated: out.journal.map((j) => j.relatedId),
240      jPackType: out.journal.map((j) => j.packType), jPackSize: out.journal.map((j) => j.packSize), jPackDelta: out.journal.map((j) => j.packDelta),
241      stockProductIds: [...out.stockDelta.keys()], stockDelta: [...out.stockDelta.values()],
242    });
243    journalRows = r.journal;
244  }
245  return {
246    requested: [...demand.values()].reduce((s, q) => s + q, 0), issued: out.issued, short: out.short,
247    openedPacks: out.openedPacks, cutContainers: out.cutContainers, journalRows, lots: [...out.issuedLots.values()],
248  };
249}
250