techtools

ops3.ts

TypeScript · 171 рядків

1import type pg from 'pg';
2import { allocate, type Mutations, type Row } from './alloc.ts';
3import { PT, ST, TX } from './schema.ts';
4
5// Операції v3: модельний час ($ts) у журналі, архіві й прийманні; журнал без id; тип руху для переміщень.
6// Видача: BEGIN → LOCK product_stock (окремо) → READ записів (окремо) → розподіл у пам'яті → FLUSH одним оператором → COMMIT.
7
8export const TX3 = { RECEIVE: 1, ISSUE: 2, OPEN: 3, TRANSFER_OUT: 8, TRANSFER_IN: 9 } as const;
9
10const DAY = 86_400_000;
11const day = (d: string | null) => (d ? Date.parse(d) / DAY : Infinity);
12
13export interface IssueLine { product_id: number; qty: number }
14export interface IssueResult {
15  issued: number; short: number; opened: number; cut: number; rows: number; journal: number;
16  perProduct: Map<number, { qty: number; expiry: string | null; mfg: string | null }>;
17}
18
19const LOCK = `SELECT product_id FROM wms.product_stock WHERE warehouse_id = $1 AND product_id = ANY($2::int[]) ORDER BY product_id FOR UPDATE`;
20
21const READ = `
22SELECT i.id, i.product_id, i.is_container, i.pack_type, i.pack_size, i.pack_count, i.quantity, i.contained_in_id, i.source_id,
23       i.mfg_date, i.expiry_date, i.received_at, i.location_id
24FROM wms.inventory_item i
25WHERE i.warehouse_id = $1 AND i.product_id = ANY($2::int[]) AND i.status = ${ST.ACTIVE}`;
26
27const FLUSH = `
28WITH nw AS (
29  SELECT * FROM unnest($2::bigint[], $3::int[], $4::int[], $5::bigint[], $6::bigint[], $7::date[], $8::date[], $9::timestamptz[], $10::int[], $11::boolean[], $12::int[])
30    AS n(temp, product_id, quantity, cin, src, mfg, exp, recv, loc, arch, fin)
31), map AS (
32  SELECT temp, nextval('wms.inventory_item_id_seq') AS id FROM nw
33), ins AS (
34  INSERT INTO wms.inventory_item (id, warehouse_id, product_id, is_container, pack_type, status, pack_size, pack_count, quantity,
35                                  contained_in_id, source_id, mfg_date, expiry_date, received_at, location_id)
36  SELECT m.id, $1, n.product_id, false, ${PT.unit}, ${ST.ACTIVE}, 1, n.quantity, n.quantity, n.cin, n.src, n.mfg, n.exp, n.recv, n.loc
37  FROM nw n JOIN map m USING (temp) WHERE NOT n.arch
38  RETURNING 1
39), ains AS (
40  INSERT INTO wms.inventory_item_archive (id, warehouse_id, product_id, is_container, pack_type, status, pack_size, pack_count, quantity,
41                                          contained_in_id, source_id, mfg_date, expiry_date, received_at, location_id, archived_at, quantity_final)
42  SELECT m.id, $1, n.product_id, false, ${PT.unit}, ${ST.ISSUED}, 1, 0, 0, n.cin, n.src, n.mfg, n.exp, n.recv, n.loc, $29, n.fin
43  FROM nw n JOIN map m USING (temp) WHERE n.arch
44  RETURNING 1
45), upd AS (
46  UPDATE wms.inventory_item i SET pack_count = u.pc, quantity = u.q, contained_in_id = u.cin
47  FROM unnest($13::bigint[], $14::int[], $15::int[], $16::bigint[]) AS u(id, pc, q, cin)
48  WHERE i.id = u.id
49  RETURNING 1
50), f AS (
51  SELECT * FROM unnest($17::bigint[], $18::smallint[], $19::int[]) AS f(id, st, fin)
52), del AS (
53  DELETE FROM wms.inventory_item i USING f WHERE i.id = f.id
54  RETURNING i.*, f.st, f.fin
55), arc AS (
56  INSERT INTO wms.inventory_item_archive (id, warehouse_id, product_id, is_container, pack_type, status, pack_size, pack_count, quantity,
57                                          contained_in_id, source_id, receipt_id, mfg_date, expiry_date, received_at, location_id,
58                                          label_code, serial_number, archived_at, quantity_final)
59  SELECT id, warehouse_id, product_id, is_container, pack_type, st, pack_size,
60         CASE WHEN is_container THEN pack_count ELSE 0 END, CASE WHEN is_container THEN quantity ELSE 0 END,
61         contained_in_id, source_id, receipt_id, mfg_date, expiry_date, received_at, location_id, label_code, serial_number, $29, fin
62  FROM del
63  RETURNING 1
64), jr AS (
65  INSERT INTO wms.inventory_transaction (created_at, warehouse_id, type, product_id, item_id, qty_delta, doc_id, related_item_id, user_id)
66  SELECT $29, $1, CASE WHEN j.type = ${TX.ISSUE} THEN $30::smallint ELSE j.type END, j.pid, coalesce(m1.id, j.item), j.d, $25, coalesce(m2.id, j.rel), $26
67  FROM unnest($20::smallint[], $21::int[], $22::bigint[], $23::int[], $24::bigint[]) AS j(type, pid, item, d, rel)
68  LEFT JOIN map m1 ON m1.temp = j.item LEFT JOIN map m2 ON m2.temp = j.rel
69  RETURNING 1
70), st AS (
71  UPDATE wms.product_stock s SET quantity = s.quantity + d.d, available = s.available + d.d
72  FROM unnest($27::int[], $28::int[]) AS d(pid, d)
73  WHERE s.warehouse_id = $1 AND s.product_id = d.pid
74  RETURNING 1
75)
76SELECT (SELECT count(*) FROM ins) + (SELECT count(*) FROM ains) + (SELECT count(*) FROM upd) + (SELECT count(*) FROM arc) AS rows,
77       (SELECT count(*) FROM jr) AS journal`;
78
79/** Видача замовлення / переміщення однією транзакцією. outType: ISSUE (продаж) або TRANSFER_OUT. */
80export async function issueOrder(c: pg.PoolClient, wh: number, lines: IssueLine[], doc: number, user: number, ts: string, outType: number): Promise<IssueResult> {
81  const pids = [...new Set(lines.map((l) => l.product_id))].sort((a, b) => a - b);
82  await c.query('BEGIN');
83  try {
84    const locked = await c.query(LOCK, [wh, pids]);
85    const read = await c.query(READ, [wh, locked.rows.map((r) => r.product_id)]);
86    const byProduct = new Map<number, Row[]>();
87    const raw = new Map<number, any>();
88    for (const r of read.rows) {
89      raw.set(r.id, r);
90      const row: Row = {
91        id: r.id, product_id: r.product_id, is_container: r.is_container, pack_type: r.pack_type, pack_size: r.pack_size,
92        pack_count: r.pack_count, quantity: r.quantity, contained_in_id: r.contained_in_id, source_id: r.source_id,
93        expiry: day(r.expiry_date), received: Date.parse(r.received_at),
94      };
95      (byProduct.get(r.product_id) ?? byProduct.set(r.product_id, []).get(r.product_id)!).push(row);
96    }
97    const m: Mutations = { rows: [], journal: [], stockDelta: new Map(), opened: 0, cut: 0, issued: 0, short: 0 };
98    for (const l of lines) allocate(byProduct.get(l.product_id) ?? [], l.product_id, l.qty, m);
99
100    // Що видано по товарах (для приймання переміщення на іншому складі) — з датами найстарішої виданої партії.
101    const perProduct = new Map<number, { qty: number; expiry: string | null; mfg: string | null }>();
102    for (const j of m.journal) {
103      if (j.type !== TX.ISSUE || j.qty_delta >= 0) continue;
104      const src = raw.get(j.item_id) ?? raw.get(byProduct.get(j.product_id)?.find((r) => r.id === j.item_id)?.source_id ?? -1);
105      const cur = perProduct.get(j.product_id) ?? { qty: 0, expiry: src?.expiry_date ?? null, mfg: src?.mfg_date ?? null };
106      cur.qty += -j.qty_delta;
107      perProduct.set(j.product_id, cur);
108    }
109
110    const nw = m.rows.filter((r) => r.isNew);
111    const src = (r: Row) => raw.get(r.source_id!);
112    const upd = m.rows.filter((r) => !r.isNew && !r.archived && r.dirty);
113    const arc = m.rows.filter((r) => !r.isNew && r.archived);
114    let rows = 0;
115    let journal = 0;
116    if (m.journal.length) {
117      const f = await c.query(FLUSH, [
118        wh,
119        nw.map((r) => r.id), nw.map((r) => r.product_id), nw.map((r) => r.quantity), nw.map((r) => r.contained_in_id), nw.map((r) => r.source_id),
120        nw.map((r) => src(r)?.mfg_date ?? null), nw.map((r) => src(r)?.expiry_date ?? null), nw.map((r) => src(r)?.received_at ?? ts), nw.map((r) => src(r)?.location_id ?? 0),
121        nw.map((r) => !!r.archived), nw.map((r) => r.archived?.final ?? 0),
122        upd.map((r) => r.id), upd.map((r) => r.pack_count), upd.map((r) => r.quantity), upd.map((r) => r.contained_in_id),
123        arc.map((r) => r.id), arc.map((r) => r.archived!.status), arc.map((r) => r.archived!.final),
124        m.journal.map((j) => j.type), m.journal.map((j) => j.product_id), m.journal.map((j) => j.item_id), m.journal.map((j) => j.qty_delta), m.journal.map((j) => j.related),
125        doc, user,
126        [...m.stockDelta.keys()], [...m.stockDelta.values()],
127        ts, outType,
128      ]);
129      rows = Number(f.rows[0].rows);
130      journal = Number(f.rows[0].journal);
131    }
132    await c.query('COMMIT');
133    return { issued: m.issued, short: m.short, opened: m.opened, cut: m.cut, rows, journal, perProduct };
134  } catch (e) {
135    await c.query('ROLLBACK').catch(() => {});
136    throw e;
137  }
138}
139
140export interface LotLine { pack_type: number; pack_size: number; pack_count: number }
141export interface Lot { product_id: number; lines: LotLine[]; mfg: string | null; expiry: string | null; location: number }
142
143const RECEIVE = `
144WITH ins AS (
145  INSERT INTO wms.inventory_item (warehouse_id, product_id, pack_type, status, pack_size, pack_count, quantity,
146                                  receipt_id, mfg_date, expiry_date, received_at, location_id)
147  SELECT $1, $2, l.pt, ${ST.ACTIVE}, l.sz, l.cnt, l.sz * l.cnt, $4, $5, $6, $7, $8
148  FROM unnest($9::smallint[], $10::int[], $11::int[]) AS l(pt, sz, cnt)
149  RETURNING id, quantity
150), j AS (
151  INSERT INTO wms.inventory_transaction (created_at, warehouse_id, type, product_id, item_id, qty_delta, doc_id, user_id)
152  SELECT $7, $1, $12::smallint, $2, id, quantity, $4, $13::int FROM ins
153  RETURNING 1
154), s AS (
155  INSERT INTO wms.product_stock (warehouse_id, product_id, quantity, available) VALUES ($1, $2, $3, $3)
156  ON CONFLICT (warehouse_id, product_id) DO UPDATE
157    SET quantity = wms.product_stock.quantity + EXCLUDED.quantity, available = wms.product_stock.available + EXCLUDED.available
158  RETURNING 1
159)
160SELECT (SELECT count(*) FROM ins) AS rows, (SELECT count(*) FROM j) AS journal`;
161
162/** Приймання однієї партії (потоварно): один оператор, одна транзакція. */
163export async function receiveLot(c: pg.PoolClient, wh: number, lot: Lot, doc: number, user: number, ts: string, type: number): Promise<{ rows: number; journal: number; units: number }> {
164  const total = lot.lines.reduce((s, l) => s + l.pack_size * l.pack_count, 0);
165  const r = await c.query(RECEIVE, [
166    wh, lot.product_id, total, doc, lot.mfg, lot.expiry, ts, lot.location,
167    lot.lines.map((l) => l.pack_type), lot.lines.map((l) => l.pack_size), lot.lines.map((l) => l.pack_count), type, user,
168  ]);
169  return { rows: Number(r.rows[0].rows), journal: Number(r.rows[0].journal), units: total };
170}
171