techtools
Головна / research / lab / stock-sim / src / inventory.ts

inventory.ts

TypeScript · 856 рядків

1import type { DatabaseSync } from 'node:sqlite';
2
3export class ApiError extends Error {
4  status: number;
5  constructor(status: number, message: string) {
6    super(message);
7    this.status = status;
8  }
9}
10
11export interface Item {
12  id: number;
13  product_id: number;
14  is_container: number;
15  pack_type: string;
16  pack_size: number;
17  pack_count: number;
18  quantity: number;
19  status: string;
20  contained_in_id: number | null;
21  source_inventory_id: number | null;
22  origin_doc: string | null;
23  serial_number: string | null;
24  label_code: string | null;
25  mfg_day: number | null;
26  expiry_day: number | null;
27  received_day: number;
28  location: string;
29}
30
31export interface Product {
32  id: number;
33  brand: string;
34  sku: string;
35  name: string;
36  category: string;
37  is_serial: number;
38  shelf_life_days: number | null;
39  std_pack_type: string | null;
40  std_pack_size: number | null;
41}
42
43export interface ProductKey { product_id?: number; brand?: string; sku?: string }
44
45export interface ProductIn {
46  brand: string; sku: string; name: string; category: string;
47  is_serial?: boolean; shelf_life_days?: number | null;
48  std_pack_type?: string | null; std_pack_size?: number | null;
49}
50
51// Рядок приймання: «коробка × 9 по 100». Серійні товари — unit × N з N серійниками.
52export interface LineIn { pack_type: string; pack_size: number; pack_count: number; label?: string; serials?: string[] }
53
54// Партія: один товар, одні дати, необов'язкове пакування партії (спайка/палета), що об'єднує рядки.
55export interface LotIn extends ProductKey {
56  mfg_day?: number; expiry_day?: number; location: string;
57  container?: { type: string; total: number; label?: string };
58  lines: LineIn[];
59}
60
61export interface ReceiptIn { doc: string; day: number; lots: LotIn[] }
62
63// fefo — для товарів зі строком спершу найстаріший строк, навіть ціною розкриття; pack-first — спершу цілі пакування.
64export type IssuePolicy = 'fefo' | 'pack-first';
65export interface IssueLineIn extends ProductKey { order: string; qty: number; policy?: IssuePolicy }
66
67export interface Pick {
68  item_id: number; kind: 'container' | 'pack' | 'loose' | 'serial';
69  pack_type: string; packs: number; qty: number;
70  label: string | null; serial: string | null;
71  mfg_day: number | null; expiry_day: number | null;
72}
73
74export interface IssueResult {
75  order: string; product_id: number; requested: number; issued: number; short: number;
76  picks: Pick[]; opened_packs: number; opened_containers: number; fefo_violation: boolean;
77  scanned: number; // скільки записів запасу прочитано для рядка
78}
79
80export interface ReturnIn { order: string; source_item_id: number; qty: number; sealed_pack?: { pack_type: string; pack_size: number } }
81
82export interface Violation { check: string; detail: string }
83
84const CONTAINER_TYPES = new Set(['bundle', 'pallet']);
85const FINAL_STATUS: Record<string, string> = { ISSUE: 'ISSUED', OPEN: 'OPENED', ADJUSTMENT: 'ADJUSTED', REPACK: 'REPACKED', SPLIT: 'SPLIT' };
86const FAR = 1e9;
87
88function pickOf(it: Item, kind: Pick['kind'], packs: number, qty: number): Pick {
89  return { item_id: it.id, kind, pack_type: it.pack_type, packs, qty, label: it.label_code, serial: it.serial_number, mfg_day: it.mfg_day, expiry_day: it.expiry_day };
90}
91
92function fefo(a: Item, b: Item): number {
93  return (a.expiry_day ?? FAR) - (b.expiry_day ?? FAR) || a.received_day - b.received_day || a.id - b.id;
94}
95
96interface Stmt { run(...a: any[]): any; get(...a: any[]): any; all(...a: any[]): any[] }
97export interface ProfileEntry { calls: number; ms: number; rows: number }
98
99/** Оптимізації, що вмикаються для порівняння з базовою реалізацією. */
100export interface InventoryOptions {
101  orderTx?: boolean;              // одна транзакція БД на замовлення замість транзакції на рядок
102  fastIssue?: boolean;            // відбір: 2 запити на ітерацію, строк FEFO з уже прочитаних записів
103  incrementalReconcile?: boolean; // звірка журналу від контрольної точки
104  fastSummary?: boolean;          // зведення залишку одним GROUP BY
105  indexes?: boolean;              // індекс (status, expiry_day) для щоденної перевірки строків
106}
107
108export class Inventory {
109  db: DatabaseSync;
110  opts: InventoryOptions;
111  private cache = new Map<string, Stmt>();
112  private labelSeq = 0;
113  ops = 0;                                      // виконаних SQL-операторів
114  scannedRows = 0;                              // записів запасу, прочитаних відбором
115  profile = new Map<string, ProfileEntry>();    // час і кількість за кожним SQL-оператором
116
117  constructor(db: DatabaseSync, opts: InventoryOptions = {}) {
118    this.db = db;
119    this.opts = opts;
120    if (opts.indexes) db.exec('CREATE INDEX IF NOT EXISTS ix_item_expiry ON inventory_item (status, expiry_day)');
121  }
122
123  private rec(key: string): ProfileEntry {
124    return this.profile.get(key) ?? this.profile.set(key, { calls: 0, ms: 0, rows: 0 }).get(key)!;
125  }
126
127  private q(sql: string): Stmt {
128    this.ops++;
129    let w = this.cache.get(sql);
130    if (!w) {
131      const st = this.db.prepare(sql);
132      const r = this.rec(sql.replace(/\s+/g, ' ').trim());
133      const time = <T>(f: () => T, rows: (x: T) => number): T => {
134        const t = performance.now();
135        const x = f();
136        r.ms += performance.now() - t;
137        r.calls++;
138        r.rows += rows(x);
139        return x;
140      };
141      w = {
142        run: (...a) => time(() => st.run(...a), (x) => Number(x.changes)),
143        get: (...a) => time(() => st.get(...a), (x) => (x ? 1 : 0)),
144        all: (...a) => time(() => st.all(...a), (x) => x.length),
145      };
146      this.cache.set(sql, w);
147    }
148    return w;
149  }
150
151  private exec(sql: string): void {
152    const t = performance.now();
153    this.db.exec(sql);
154    const r = this.rec(sql);
155    r.ms += performance.now() - t;
156    r.calls++;
157  }
158
159  // R-01.10: будь-яка зміна залишку — одна транзакція БД. COMMIT профілюється окремо: тут fsync.
160  tx<T>(fn: () => T): T {
161    this.exec('BEGIN');
162    try {
163      const r = fn();
164      this.exec('COMMIT');
165      return r;
166    } catch (e) {
167      this.exec('ROLLBACK');
168      throw e;
169    }
170  }
171
172  // ---------- довідник ----------
173
174  addProducts(list: ProductIn[]): Product[] {
175    return this.tx(() => list.map((p) => {
176      const r = this.q(`INSERT INTO product (brand, sku, name, category, is_serial, shelf_life_days, std_pack_type, std_pack_size)
177                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
178        .run(p.brand, p.sku, p.name, p.category, p.is_serial ? 1 : 0, p.shelf_life_days ?? null, p.std_pack_type ?? null, p.std_pack_size ?? null);
179      const id = Number(r.lastInsertRowid);
180      this.q('INSERT INTO product_stock (product_id, quantity, updated_day) VALUES (?, 0, 0)').run(id);
181      return this.product({ product_id: id });
182    }));
183  }
184
185  product(key: ProductKey): Product {
186    const p = key.product_id != null
187      ? this.q('SELECT * FROM product WHERE id = ?').get(key.product_id)
188      : this.q('SELECT * FROM product WHERE brand = ? AND sku = ?').get(key.brand ?? null, key.sku ?? null);
189    if (!p) throw new ApiError(404, `товар не знайдено: ${JSON.stringify(key)}`);
190    return p as unknown as Product;
191  }
192
193  // ---------- низькорівневі операції ----------
194
195  private item(id: number): Item {
196    const it = this.q('SELECT * FROM inventory_item WHERE id = ?').get(id);
197    if (!it) throw new ApiError(404, `запис запасу ${id} не знайдено`);
198    return it as unknown as Item;
199  }
200
201  private anyItem(id: number): Item | undefined {
202    return (this.q('SELECT * FROM inventory_item WHERE id = ?').get(id)
203      ?? this.q('SELECT * FROM inventory_item_archive WHERE id = ?').get(id)) as unknown as Item | undefined;
204  }
205
206  private insertItem(it: Omit<Item, 'id'>): number {
207    const r = this.q(`INSERT INTO inventory_item (product_id, is_container, pack_type, pack_size, pack_count, quantity, status,
208        contained_in_id, source_inventory_id, origin_doc, serial_number, label_code, mfg_day, expiry_day, received_day, location)
209        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
210      .run(it.product_id, it.is_container, it.pack_type, it.pack_size, it.pack_count, it.quantity, it.status,
211        it.contained_in_id, it.source_inventory_id, it.origin_doc, it.serial_number, it.label_code,
212        it.mfg_day, it.expiry_day, it.received_day, it.location);
213    return Number(r.lastInsertRowid);
214  }
215
216  private log(day: number, type: string, productId: number, itemId: number, delta: number, doc: string | null, related: number | null = null, note: string | null = null): void {
217    this.q(`INSERT INTO inventory_transaction (day, type, product_id, item_id, qty_delta, doc, related_item_id, note)
218            VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(day, type, productId, itemId, delta, doc, related, note);
219    if (delta !== 0) {
220      this.q('UPDATE product_stock SET quantity = quantity + ?, updated_day = ? WHERE product_id = ?').run(delta, day, productId);
221    }
222  }
223
224  // R-01.11: запис із нульовою кількістю або розкритий контейнер — в архів із фінальним станом,
225  // що пояснює, чим закінчився запис: ISSUED | OPENED | ADJUSTED | REPACKED | WRITTEN_OFF.
226  // quantity в архіві — що лишилось (0), quantity_final — скільки пішло з записом останньою операцією.
227  private archive(id: number, day: number, status: string, quantityFinal: number): void {
228    this.q('UPDATE inventory_item SET status = ? WHERE id = ?').run(status, id);
229    this.q('INSERT INTO inventory_item_archive SELECT *, ?, ? FROM inventory_item WHERE id = ?').run(day, quantityFinal, id);
230    this.q('DELETE FROM inventory_item WHERE id = ?').run(id);
231  }
232
233  // Зменшити групу цілих пакувань / розсип на n пакувань (для розсипу size = 1).
234  private reduce(it: Item, packs: number, day: number, type: string, doc: string | null, related: number | null = null): void {
235    const qty = packs * it.pack_size;
236    this.log(day, type, it.product_id, it.id, -qty, doc, related);
237    if (packs === it.pack_count) {
238      this.q('UPDATE inventory_item SET pack_count = 0, quantity = 0 WHERE id = ?').run(it.id);
239      this.archive(it.id, day, FINAL_STATUS[type] ?? 'ISSUED', qty);
240    } else {
241      this.q('UPDATE inventory_item SET pack_count = pack_count - ?, quantity = quantity - ? WHERE id = ?').run(packs, qty, it.id);
242    }
243    it.pack_count -= packs;
244    it.quantity -= qty;
245  }
246
247  // R-01.3: розкрити одне пакування з групи; решта групи лишається цілою, вміст — новий запис розсипу.
248  private openPack(it: Item, day: number, doc: string | null): Item {
249    const loose: Omit<Item, 'id'> = {
250      product_id: it.product_id, is_container: 0, pack_type: 'unit', pack_size: 1, pack_count: it.pack_size,
251      quantity: it.pack_size, status: 'ACTIVE', contained_in_id: it.contained_in_id, source_inventory_id: it.id,
252      origin_doc: null, serial_number: null, label_code: null, mfg_day: it.mfg_day, expiry_day: it.expiry_day,
253      received_day: it.received_day, location: it.location,
254    };
255    this.reduce(it, 1, day, 'OPEN', doc);
256    const id = this.insertItem(loose);
257    this.log(day, 'OPEN', it.product_id, id, loose.quantity, doc, it.id);
258    return { id, ...loose };
259  }
260
261  // Розрізати спайку/палету: вміст стає вільним, контейнер — OPENED і в архів.
262  private openContainer(c: Item, day: number, doc: string | null): void {
263    this.q('UPDATE inventory_item SET contained_in_id = NULL WHERE contained_in_id = ?').run(c.id);
264    this.log(day, 'OPEN', c.product_id, c.id, 0, doc);
265    this.archive(c.id, day, 'OPENED', c.quantity);
266  }
267
268  private children(containerId: number): Item[] {
269    return this.q('SELECT * FROM inventory_item WHERE contained_in_id = ?').all(containerId) as unknown as Item[];
270  }
271
272  // ---------- приймання ----------
273
274  receive(r: ReceiptIn): { doc: string; items: number[] } {
275    return this.tx(() => {
276      const created: number[] = [];
277      for (const lot of r.lots) {
278        const p = this.product(lot);
279        if (!lot.lines?.length) throw new ApiError(400, `${r.doc}: партія без рядків`);
280        let total = 0;
281        for (const l of lot.lines) {
282          if (!Number.isInteger(l.pack_size) || !Number.isInteger(l.pack_count) || l.pack_size < 1 || l.pack_count < 1)
283            throw new ApiError(400, `${r.doc}: некоректний рядок ${JSON.stringify(l)}`);
284          if (l.pack_type === 'unit' && l.pack_size !== 1) throw new ApiError(400, `${r.doc}: розсип має pack_size = 1`);
285          if (CONTAINER_TYPES.has(l.pack_type)) throw new ApiError(400, `${r.doc}: контейнер не може бути рядком (вкладеність ≤ 2 рівні)`);
286          if (p.is_serial) {
287            if (l.pack_type !== 'unit' || l.serials?.length !== l.pack_count)
288              throw new ApiError(400, `${r.doc}: серійний товар ${p.brand}/${p.sku} приймається поштучно з серійником на кожну одиницю`);
289          } else if (l.serials?.length) {
290            throw new ApiError(400, `${r.doc}: серійники виробника лише для серійних товарів; для решти — складська етикетка`);
291          }
292          total += l.pack_size * l.pack_count;
293        }
294        if (lot.container && lot.container.total !== total)
295          throw new ApiError(400, `${r.doc}: пакування партії ${lot.container.total} ≠ сумі рядків ${total}`);
296
297        const expiry = lot.expiry_day ?? (lot.mfg_day != null && p.shelf_life_days ? lot.mfg_day + p.shelf_life_days : null);
298        const base = {
299          product_id: p.id, status: 'ACTIVE', mfg_day: lot.mfg_day ?? null, expiry_day: expiry,
300          received_day: r.day, location: lot.location, serial_number: null, label_code: null,
301        };
302
303        let containerId: number | null = null;
304        if (lot.container) {
305          if (!CONTAINER_TYPES.has(lot.container.type)) throw new ApiError(400, `${r.doc}: невідомий тип пакування партії ${lot.container.type}`);
306          containerId = this.insertItem({
307            ...base, is_container: 1, pack_type: lot.container.type, pack_size: total, pack_count: 1, quantity: total,
308            contained_in_id: null, source_inventory_id: null, origin_doc: r.doc, label_code: lot.container.label ?? null,
309          });
310          this.log(r.day, 'RECEIVE', p.id, containerId, 0, r.doc, null, `${lot.container.type} ${total}`);
311          created.push(containerId);
312        }
313        for (const l of lot.lines) {
314          const child = {
315            ...base, is_container: 0, contained_in_id: containerId, source_inventory_id: containerId,
316            origin_doc: containerId ? null : r.doc,
317          };
318          if (p.is_serial) {
319            for (const s of l.serials!) {
320              const id = this.insertItem({ ...child, pack_type: 'unit', pack_size: 1, pack_count: 1, quantity: 1, serial_number: s });
321              this.log(r.day, 'RECEIVE', p.id, id, 1, r.doc);
322              created.push(id);
323            }
324          } else {
325            const id = this.insertItem({
326              ...child, pack_type: l.pack_type, pack_size: l.pack_size, pack_count: l.pack_count,
327              quantity: l.pack_size * l.pack_count, label_code: l.label ?? null,
328            });
329            this.log(r.day, 'RECEIVE', p.id, id, l.pack_size * l.pack_count, r.doc);
330            created.push(id);
331          }
332        }
333      }
334      return { doc: r.doc, items: created };
335    });
336  }
337
338  // ---------- видача ----------
339
340  private activeContainers(pid: number): Item[] {
341    const r = this.q("SELECT * FROM inventory_item WHERE product_id = ? AND is_container = 1 AND status = 'ACTIVE'").all(pid) as Item[];
342    this.scannedRows += r.length;
343    return r.sort(fefo);
344  }
345
346  private freeLeaves(pid: number): Item[] {
347    const r = this.q(`SELECT * FROM inventory_item WHERE product_id = ? AND is_container = 0 AND status = 'ACTIVE'
348                    AND contained_in_id IS NULL`).all(pid) as Item[];
349    this.scannedRows += r.length;
350    return r.sort(fefo);
351  }
352
353  private minActiveExpiry(pid: number): number | null {
354    const r = this.q(`SELECT MIN(expiry_day) AS m FROM inventory_item WHERE product_id = ? AND is_container = 0 AND status = 'ACTIVE'`).get(pid) as { m: number | null };
355    return r.m;
356  }
357
358  /**
359   * Порядок відбору (гіпотеза для перевірки симуляцією):
360   * A. цілі спайки/палети, що вміщуються в залишок рядка;
361   * B. цілі пакування з вільних груп, від більшого до меншого;
362   * C. розсип;
363   * D. якщо не вистачило — розкрити найменше вільне пакування, інакше розрізати контейнер, і повторити.
364   * Усередині кожного кроку — FEFO, далі FIFO. У режимі fefo для товарів зі строком кроки A–D
365   * бачать лише запас із найближчим строком, доки він не вичерпається.
366   */
367  issue(line: IssueLineIn, day: number, inTx = false): IssueResult {
368    const p = this.product(line);
369    if (!Number.isInteger(line.qty) || line.qty < 1) throw new ApiError(400, `${line.order}: некоректна кількість`);
370    const scanned0 = this.scannedRows;
371    const body = (): IssueResult => {
372      const res: IssueResult = {
373        order: line.order, product_id: p.id, requested: line.qty, issued: 0, short: 0,
374        picks: [], opened_packs: 0, opened_containers: 0, fefo_violation: false, scanned: 0,
375      };
376      if (this.opts.fastIssue) return this.issueFast(p, line, day, res);
377      let remaining = line.qty;
378      // FEFO для будь-якого запасу з датою: строк може прийти з картки або з партії («вжити до»).
379      const strict = (line.policy ?? 'fefo') === 'fefo';
380      const tier = (list: Item[]): Item[] => {
381        if (!strict) return list;
382        const min = this.minActiveExpiry(p.id);
383        return min == null ? list : list.filter((i) => i.expiry_day == null || i.expiry_day <= min);
384      };
385      let maxPickedExpiry: number | null = null;
386      const note = (it: Item) => {
387        if (it.expiry_day != null && (maxPickedExpiry == null || it.expiry_day > maxPickedExpiry)) maxPickedExpiry = it.expiry_day;
388      };
389
390      for (let guard = 0; remaining > 0 && guard < 10_000; guard++) {
391        const minStart = strict ? this.minActiveExpiry(p.id) : null;
392        let progressed = false;
393        // A
394        const conts = tier(this.activeContainers(p.id)).sort((a, b) => b.quantity - a.quantity);
395        for (const c of conts) {
396          if (c.quantity > remaining) continue;
397          const kids = this.children(c.id);
398          this.log(day, 'ISSUE', p.id, c.id, 0, line.order, null, 'whole container');
399          for (const k of kids) {
400            this.log(day, 'ISSUE', p.id, k.id, -k.quantity, line.order, c.id);
401            this.q('UPDATE inventory_item SET pack_count = 0, quantity = 0 WHERE id = ?').run(k.id);
402            this.archive(k.id, day, 'ISSUED', k.quantity);
403          }
404          this.archive(c.id, day, 'ISSUED', c.quantity); // quantity контейнера в архіві = заявлений вміст
405          note(c);
406          res.picks.push(pickOf(c, 'container', 1, c.quantity));
407          remaining -= c.quantity;
408          progressed = true;
409          if (remaining === 0) break;
410        }
411        if (remaining === 0) break;
412        if (progressed) continue;
413
414        // B, C
415        const leaves = tier(this.freeLeaves(p.id));
416        const packs = leaves.filter((l) => l.pack_type !== 'unit').sort((a, b) => b.pack_size - a.pack_size || fefo(a, b));
417        for (const it of packs) {
418          if (it.pack_size > remaining) continue;
419          const n = Math.min(it.pack_count, Math.floor(remaining / it.pack_size));
420          this.reduce(it, n, day, 'ISSUE', line.order);
421          note(it);
422          res.picks.push(pickOf(it, 'pack', n, n * it.pack_size));
423          remaining -= n * it.pack_size;
424          progressed = true;
425          if (remaining === 0) break;
426        }
427        for (const it of leaves) {
428          if (remaining === 0) break;
429          if (it.pack_type !== 'unit' || it.quantity === 0) continue;
430          const n = Math.min(it.quantity, remaining);
431          this.reduce(it, n, day, 'ISSUE', line.order);
432          note(it);
433          res.picks.push(pickOf(it, it.serial_number ? 'serial' : 'loose', n, n));
434          remaining -= n;
435          progressed = true;
436        }
437        if (remaining === 0) break;
438        if (progressed && strict && this.minActiveExpiry(p.id) !== minStart) continue; // найближчий строк вичерпано
439
440        // D
441        const closed = tier(this.freeLeaves(p.id)).filter((l) => l.pack_type !== 'unit').sort((a, b) => a.pack_size - b.pack_size || fefo(a, b));
442        if (closed.length) {
443          this.openPack(closed[0], day, line.order);
444          res.opened_packs++;
445          continue;
446        }
447        const cs = tier(this.activeContainers(p.id)).sort((a, b) => a.quantity - b.quantity || fefo(a, b));
448        if (cs.length) {
449          this.openContainer(cs[0], day, line.order);
450          res.opened_containers++;
451          continue;
452        }
453        break;
454      }
455      res.issued = line.qty - remaining;
456      res.short = remaining;
457      const left = this.minActiveExpiry(p.id);
458      res.fefo_violation = maxPickedExpiry != null && left != null && left < maxPickedExpiry;
459      return res;
460    };
461    const res = inTx ? body() : this.tx(body);
462    res.scanned = this.scannedRows - scanned0;
463    return res;
464  }
465
466  /**
467   * Той самий порядок A–D, але за ітерацію — лише 2 запити (спайки й вільні записи), а найближчий строк
468   * береться з уже прочитаних записів замість окремого MIN(expiry_day) на кожному кроці.
469   */
470  private issueFast(p: Product, line: IssueLineIn, day: number, res: IssueResult): IssueResult {
471    let remaining = line.qty;
472    const strict = (line.policy ?? 'fefo') === 'fefo';
473    let maxPicked: number | null = null;
474    const note = (it: Item) => {
475      if (it.expiry_day != null && (maxPicked == null || it.expiry_day > maxPicked)) maxPicked = it.expiry_day;
476    };
477    const minExpiry = (l: Item[]) => {
478      let m: number | null = null;
479      for (const i of l) if (i.expiry_day != null && (m == null || i.expiry_day < m)) m = i.expiry_day;
480      return m;
481    };
482    for (let guard = 0; remaining > 0 && guard < 10_000; guard++) {
483      const conts0 = this.activeContainers(p.id);
484      const leaves0 = this.freeLeaves(p.id);
485      const min = strict ? minExpiry([...conts0, ...leaves0]) : null;
486      const tier = (l: Item[]) => (min == null ? l : l.filter((i) => i.expiry_day == null || i.expiry_day <= min));
487      let progressed = false;
488
489      const conts = tier(conts0).sort((a, b) => b.quantity - a.quantity);
490      for (const c of conts) {
491        if (c.quantity > remaining) continue;
492        const kids = this.children(c.id);
493        this.log(day, 'ISSUE', p.id, c.id, 0, line.order, null, 'whole container');
494        for (const k of kids) {
495          this.log(day, 'ISSUE', p.id, k.id, -k.quantity, line.order, c.id);
496          this.q('UPDATE inventory_item SET pack_count = 0, quantity = 0 WHERE id = ?').run(k.id);
497          this.archive(k.id, day, 'ISSUED', k.quantity);
498        }
499        this.archive(c.id, day, 'ISSUED', c.quantity);
500        note(c);
501        res.picks.push(pickOf(c, 'container', 1, c.quantity));
502        remaining -= c.quantity;
503        progressed = true;
504        if (remaining === 0) break;
505      }
506      if (remaining === 0) break;
507      if (progressed) continue; // склад змінився — перечитати
508
509      const leaves = tier(leaves0);
510      const packs = leaves.filter((l) => l.pack_type !== 'unit').sort((a, b) => b.pack_size - a.pack_size || fefo(a, b));
511      for (const it of packs) {
512        if (it.pack_size > remaining) continue;
513        const n = Math.min(it.pack_count, Math.floor(remaining / it.pack_size));
514        this.reduce(it, n, day, 'ISSUE', line.order);
515        note(it);
516        res.picks.push(pickOf(it, 'pack', n, n * it.pack_size));
517        remaining -= n * it.pack_size;
518        progressed = true;
519        if (remaining === 0) break;
520      }
521      for (const it of leaves) {
522        if (remaining === 0) break;
523        if (it.pack_type !== 'unit' || it.quantity === 0) continue;
524        const n = Math.min(it.quantity, remaining);
525        this.reduce(it, n, day, 'ISSUE', line.order);
526        note(it);
527        res.picks.push(pickOf(it, it.serial_number ? 'serial' : 'loose', n, n));
528        remaining -= n;
529        progressed = true;
530      }
531      if (remaining === 0) break;
532
533      const closed = leaves.filter((l) => l.pack_type !== 'unit' && l.pack_count > 0).sort((a, b) => a.pack_size - b.pack_size || fefo(a, b));
534      if (closed.length) {
535        this.openPack(closed[0], day, line.order);
536        res.opened_packs++;
537        continue;
538      }
539      const cs = conts.sort((a, b) => a.quantity - b.quantity || fefo(a, b));
540      if (cs.length) {
541        this.openContainer(cs[0], day, line.order);
542        res.opened_containers++;
543        continue;
544      }
545      if (progressed) continue; // найближчий строк вичерпано — наступний рівень
546      break;
547    }
548    res.issued = line.qty - remaining;
549    res.short = remaining;
550    if (maxPicked != null) {
551      const left = minExpiry([...this.activeContainers(p.id), ...this.freeLeaves(p.id)]);
552      res.fefo_violation = left != null && left < maxPicked;
553    }
554    return res;
555  }
556
557  // ---------- етикетки, повернення, коригування, перепакування, строки ----------
558
559  // Складський серійник/етикетка на будь-який запис. Для групи — відділяє одне пакування.
560  label(itemId: number, label: string | null, day: number): { item_id: number; label: string } {
561    return this.tx(() => {
562      const it = this.item(itemId);
563      const code = label ?? `WS${String(++this.labelSeq).padStart(7, '0')}`;
564      if (this.q('SELECT 1 FROM inventory_item WHERE label_code = ?').get(code)) throw new ApiError(409, `етикетка ${code} вже використана`);
565      if (it.label_code) throw new ApiError(409, `запис ${it.id} вже має етикетку ${it.label_code}`);
566      if (it.is_container || it.pack_count === 1) {
567        this.q('UPDATE inventory_item SET label_code = ? WHERE id = ?').run(code, it.id);
568        this.log(day, 'LABEL', it.product_id, it.id, 0, null, null, code);
569        return { item_id: it.id, label: code };
570      }
571      this.reduce(it, 1, day, 'SPLIT', null);
572      const id = this.insertItem({ ...it, pack_count: 1, quantity: it.pack_size, source_inventory_id: it.id, origin_doc: null, label_code: code });
573      this.log(day, 'SPLIT', it.product_id, id, it.pack_size, null, it.id, code);
574      return { item_id: id, label: code };
575    });
576  }
577
578  returnItem(r: ReturnIn, day: number): { item_id: number } {
579    return this.tx(() => {
580      const src = this.anyItem(r.source_item_id);
581      if (!src) throw new ApiError(404, `джерело повернення ${r.source_item_id} не знайдено`);
582      if (src.serial_number && r.qty !== 1) throw new ApiError(400, 'серійна одиниця повертається поштучно');
583      const sealed = r.sealed_pack;
584      if (sealed && r.qty % sealed.pack_size !== 0) throw new ApiError(400, 'кількість не кратна пакуванню');
585      const id = this.insertItem({
586        product_id: src.product_id, is_container: 0, pack_type: sealed ? sealed.pack_type : 'unit',
587        pack_size: sealed ? sealed.pack_size : 1, pack_count: sealed ? r.qty / sealed.pack_size : r.qty, quantity: r.qty,
588        status: 'ACTIVE', contained_in_id: null, source_inventory_id: src.id, origin_doc: r.order,
589        serial_number: src.serial_number, label_code: null, mfg_day: src.mfg_day, expiry_day: src.expiry_day,
590        received_day: day, location: 'RETURNS',
591      });
592      this.log(day, 'RETURN', src.product_id, id, r.qty, r.order, src.id);
593      return { item_id: id };
594    });
595  }
596
597  // Інвентаризація: недостача в запечатаному пакуванні змушує його розкрити.
598  adjust(itemId: number, delta: number, day: number, reason: string, serials?: string[]): { item_id: number; opened: number } {
599    return this.tx(() => {
600      let it = this.item(itemId);
601      if (it.is_container) throw new ApiError(400, 'коригування виконується по рядку, не по контейнеру');
602      let opened = 0;
603      if (delta > 0 && it.serial_number) {
604        // Надлишок серійного товару — лише поштучно з серійниками (виявлено симуляцією).
605        if (serials?.length !== delta) throw new ApiError(400, 'надлишок серійного товару вводиться з серійником на кожну одиницю');
606        let id = 0;
607        for (const s of serials) {
608          id = this.insertItem({ ...it, pack_count: 1, quantity: 1, contained_in_id: null, source_inventory_id: null,
609            origin_doc: reason, serial_number: s, label_code: null, status: 'ACTIVE' });
610          this.log(day, 'ADJUSTMENT', it.product_id, id, 1, reason, it.id);
611        }
612        return { item_id: id, opened };
613      }
614      if (delta > 0) {
615        const id = this.insertItem({ ...it, pack_type: 'unit', pack_size: 1, pack_count: delta, quantity: delta, contained_in_id: null,
616          source_inventory_id: null, origin_doc: reason, serial_number: null, label_code: null, status: 'ACTIVE' });
617        this.log(day, 'ADJUSTMENT', it.product_id, id, delta, reason, it.id);
618        return { item_id: id, opened };
619      }
620      let need = -delta;
621      if (need > it.quantity) throw new ApiError(400, 'недостача більша за запис');
622      if (it.contained_in_id != null) {
623        this.openContainer(this.item(it.contained_in_id), day, reason);
624        opened++;
625        it = this.item(itemId);
626      }
627      const full = Math.floor(need / it.pack_size);
628      if (full > 0) {
629        this.reduce(it, full, day, 'ADJUSTMENT', reason);
630        need -= full * it.pack_size;
631      }
632      if (need > 0) {
633        const loose = this.openPack(it, day, reason);
634        opened++;
635        this.reduce(loose, need, day, 'ADJUSTMENT', reason);
636      }
637      return { item_id: itemId, opened };
638    });
639  }
640
641  // Сформувати стандартні пакування з великого розсипу (зворотне до розкриття). Без злиття різних записів.
642  repack(day: number, minPacks = 2): { repacked_items: number; packs_created: number } {
643    const rows = this.q(`SELECT i.*, p.std_pack_type AS std_type, p.std_pack_size AS std_size
644                         FROM inventory_item i JOIN product p ON p.id = i.product_id
645                         WHERE i.is_container = 0 AND i.status = 'ACTIVE' AND i.pack_type = 'unit' AND i.serial_number IS NULL
646                           AND i.contained_in_id IS NULL AND p.std_pack_size > 1 AND i.quantity >= p.std_pack_size * ?`)
647      .all(minPacks) as unknown as (Item & { std_type: string; std_size: number })[];
648    let packs = 0;
649    for (const r of rows) {
650      this.tx(() => {
651        const n = Math.floor(r.quantity / r.std_size);
652        this.reduce(r, n * r.std_size, day, 'REPACK', 'repack');
653        const id = this.insertItem({ ...r, pack_type: r.std_type, pack_size: r.std_size, pack_count: n, quantity: n * r.std_size,
654          source_inventory_id: r.id, origin_doc: null, label_code: null });
655        this.log(day, 'REPACK', r.product_id, id, n * r.std_size, 'repack', r.id);
656        packs += n;
657      });
658    }
659    return { repacked_items: rows.length, packs_created: packs };
660  }
661
662  // Строк придатності минув — запас фізично є, але недоступний. Автосписання не погоджене (WMS-02).
663  expire(day: number): { expired_items: number } {
664    return this.tx(() => {
665      const rows = this.q("SELECT id, product_id FROM inventory_item WHERE status = 'ACTIVE' AND expiry_day IS NOT NULL AND expiry_day < ?")
666        .all(day) as unknown as { id: number; product_id: number }[];
667      for (const r of rows) {
668        this.q("UPDATE inventory_item SET status = 'EXPIRED' WHERE id = ?").run(r.id);
669        this.log(day, 'STATUS', r.product_id, r.id, 0, null, null, 'EXPIRED');
670      }
671      return { expired_items: rows.length };
672    });
673  }
674
675  // Списання простроченого рішенням супервайзера.
676  writeOffExpired(day: number, doc: string): { items: number; qty: number } {
677    return this.tx(() => {
678      const leaves = this.q("SELECT * FROM inventory_item WHERE status = 'EXPIRED' AND is_container = 0").all() as unknown as Item[];
679      let qty = 0;
680      for (const it of leaves) {
681        this.log(day, 'WRITE_OFF', it.product_id, it.id, -it.quantity, doc);
682        qty += it.quantity;
683        this.q('UPDATE inventory_item SET pack_count = 0, quantity = 0 WHERE id = ?').run(it.id);
684        this.archive(it.id, day, 'WRITTEN_OFF', it.quantity);
685      }
686      const conts = this.q("SELECT * FROM inventory_item WHERE status = 'EXPIRED' AND is_container = 1").all() as unknown as Item[];
687      for (const c of conts) {
688        this.log(day, 'WRITE_OFF', c.product_id, c.id, 0, doc);
689        this.archive(c.id, day, 'WRITTEN_OFF', c.quantity);
690      }
691      return { items: leaves.length, qty };
692    });
693  }
694
695  // ---------- читання ----------
696
697  stockSummary(): { product_id: number; total: number; available: number }[] {
698    if (this.opts.fastSummary) {
699      return this.q(`SELECT ps.product_id, ps.quantity AS total, COALESCE(a.av, 0) AS available
700                     FROM product_stock ps
701                     LEFT JOIN (SELECT product_id, SUM(quantity) AS av FROM inventory_item
702                                WHERE is_container = 0 AND status = 'ACTIVE' GROUP BY product_id) a
703                       ON a.product_id = ps.product_id`).all() as { product_id: number; total: number; available: number }[];
704    }
705    return this.q(`SELECT ps.product_id, ps.quantity AS total,
706                     COALESCE((SELECT SUM(quantity) FROM inventory_item i
707                               WHERE i.product_id = ps.product_id AND i.is_container = 0 AND i.status = 'ACTIVE'), 0) AS available
708                   FROM product_stock ps`).all() as unknown as { product_id: number; total: number; available: number }[];
709  }
710
711  stock(key: ProductKey): { product: Product; total: number; items: Item[] } {
712    const p = this.product(key);
713    const total = (this.q('SELECT quantity FROM product_stock WHERE product_id = ?').get(p.id) as { quantity: number }).quantity;
714    const items = this.q('SELECT * FROM inventory_item WHERE product_id = ? ORDER BY contained_in_id, id').all(p.id) as unknown as Item[];
715    return { product: p, total, items };
716  }
717
718  items(productId: number): Item[] {
719    return this.q('SELECT * FROM inventory_item WHERE product_id = ?').all(productId) as unknown as Item[];
720  }
721
722  genealogy(id: number): { chain: Item[]; transactions: unknown[] } {
723    const chain: Item[] = [];
724    let cur = this.anyItem(id);
725    while (cur && chain.length < 100) {
726      chain.push(cur);
727      cur = cur.source_inventory_id != null ? this.anyItem(cur.source_inventory_id) : undefined;
728    }
729    const transactions = this.q('SELECT * FROM inventory_transaction WHERE item_id = ? OR related_item_id = ? ORDER BY id').all(id, id);
730    return { chain, transactions };
731  }
732
733  // R-01.12 + інваріанти пакування.
734  reconcile(): { ok: boolean; violations: Violation[] } {
735    const v: Violation[] = [];
736    const add = (check: string, rows: unknown[]) => {
737      for (const r of rows.slice(0, 20)) v.push({ check, detail: JSON.stringify(r) });
738      if (rows.length > 20) v.push({ check, detail: `… ще ${rows.length - 20}` });
739    };
740    add('кеш ≠ сума поточних записів', this.q(`
741      SELECT ps.product_id, ps.quantity AS cache, COALESCE(s.q, 0) AS items FROM product_stock ps
742      LEFT JOIN (SELECT product_id, SUM(quantity) q FROM inventory_item WHERE is_container = 0 GROUP BY product_id) s
743        ON s.product_id = ps.product_id WHERE ps.quantity <> COALESCE(s.q, 0)`).all());
744    const inc = this.opts.incrementalReconcile;
745    const cp = inc ? (this.q("SELECT COALESCE(MAX(CASE WHEN k = 'tx' THEN v END), 0) AS tx, COALESCE(MAX(CASE WHEN k = 'archive' THEN v END), 0) AS ar FROM reconcile_meta").get() as { tx: number; ar: number }) : { tx: 0, ar: 0 };
746    // Інкрементально: залишок на контрольну точку + рухи після неї (діапазон за первинним ключем журналу).
747    const ledger = inc
748      ? this.q(`
749      SELECT ps.product_id, ps.quantity AS cache, COALESCE(c.quantity, 0) + COALESCE(t.q, 0) AS ledger FROM product_stock ps
750      LEFT JOIN reconcile_checkpoint c ON c.product_id = ps.product_id
751      LEFT JOIN (SELECT product_id, SUM(qty_delta) q FROM inventory_transaction WHERE id > ? GROUP BY product_id) t
752        ON t.product_id = ps.product_id WHERE ps.quantity <> COALESCE(c.quantity, 0) + COALESCE(t.q, 0)`).all(cp.tx)
753      : this.q(`
754      SELECT ps.product_id, ps.quantity AS cache, COALESCE(t.q, 0) AS ledger FROM product_stock ps
755      LEFT JOIN (SELECT product_id, SUM(qty_delta) q FROM inventory_transaction GROUP BY product_id) t
756        ON t.product_id = ps.product_id WHERE ps.quantity <> COALESCE(t.q, 0)`).all();
757    add('кеш ≠ сума журналу', ledger);
758    add('від\'ємний або нульовий запис у поточній таблиці', this.q(`
759      SELECT id, quantity, pack_count FROM inventory_item WHERE quantity <= 0 OR pack_count <= 0`).all());
760    add('quantity ≠ pack_size × pack_count', this.q(`
761      SELECT id, quantity, pack_size, pack_count FROM inventory_item WHERE is_container = 0 AND quantity <> pack_size * pack_count`).all());
762    add('розсип з pack_size ≠ 1', this.q(`SELECT id, pack_size FROM inventory_item WHERE pack_type = 'unit' AND pack_size <> 1`).all());
763    add('серійна одиниця з quantity ≠ 1', this.q(`SELECT id, quantity FROM inventory_item WHERE serial_number IS NOT NULL AND quantity <> 1`).all());
764    add('серійна одиниця без серійника', this.q(`
765      SELECT i.id FROM inventory_item i JOIN product p ON p.id = i.product_id
766      WHERE p.is_serial = 1 AND i.is_container = 0 AND i.serial_number IS NULL`).all());
767    add('вміст контейнера ≠ заявленому', this.q(`
768      SELECT c.id, c.quantity, COALESCE(SUM(k.quantity), 0) AS content FROM inventory_item c
769      LEFT JOIN inventory_item k ON k.contained_in_id = c.id
770      WHERE c.is_container = 1 GROUP BY c.id HAVING c.quantity <> COALESCE(SUM(k.quantity), 0)`).all());
771    add('вкладення в неіснуючий/не-контейнер', this.q(`
772      SELECT k.id, k.contained_in_id FROM inventory_item k LEFT JOIN inventory_item c ON c.id = k.contained_in_id
773      WHERE k.contained_in_id IS NOT NULL AND (c.id IS NULL OR c.is_container = 0)`).all());
774    add('стан вкладеного ≠ стану контейнера', this.q(`
775      SELECT k.id, k.status, c.status AS container_status FROM inventory_item k JOIN inventory_item c ON c.id = k.contained_in_id
776      WHERE k.status <> c.status`).all());
777    add('розкритий запис у поточній таблиці', this.q(`SELECT id FROM inventory_item WHERE status = 'OPENED'`).all());
778    add('архівний запис без фінального стану', this.q(`
779      SELECT id, status FROM inventory_item_archive WHERE rowid > ? AND status IN ('ACTIVE', 'EXPIRED') LIMIT 50`).all(cp.ar));
780    add('обірване походження', this.q(`
781      SELECT i.id, i.source_inventory_id FROM inventory_item i
782      WHERE (i.source_inventory_id IS NULL AND i.origin_doc IS NULL)
783         OR (i.source_inventory_id IS NOT NULL
784             AND NOT EXISTS (SELECT 1 FROM inventory_item a WHERE a.id = i.source_inventory_id)
785             AND NOT EXISTS (SELECT 1 FROM inventory_item_archive a WHERE a.id = i.source_inventory_id))`).all());
786    if (inc && v.length === 0) {
787      // Контрольна точка зсувається лише після повністю чистої звірки.
788      this.q('DELETE FROM reconcile_checkpoint').run();
789      this.q('INSERT INTO reconcile_checkpoint (product_id, quantity) SELECT product_id, quantity FROM product_stock').run();
790      this.q("INSERT OR REPLACE INTO reconcile_meta (k, v) SELECT 'tx', COALESCE(MAX(id), 0) FROM inventory_transaction").run();
791      this.q("INSERT OR REPLACE INTO reconcile_meta (k, v) SELECT 'archive', COALESCE(MAX(rowid), 0) FROM inventory_item_archive").run();
792    }
793    return { ok: v.length === 0, violations: v };
794  }
795
796  // Аналіз строків: залишок за часткою строку, що лишилась, і списане за категоріями.
797  expiryReport(day: number): Record<string, unknown> {
798    const rows = this.q(`SELECT p.category, i.status, i.quantity, i.mfg_day, i.expiry_day FROM inventory_item i
799                         JOIN product p ON p.id = i.product_id WHERE i.is_container = 0`).all() as
800      { category: string; status: string; quantity: number; mfg_day: number | null; expiry_day: number | null }[];
801    const BUCKETS = ['прострочено', '< 10%', '10–25%', '25–50%', '≥ 50%', 'лише «вжити до»'];
802    const DAYS = ['прострочено', '< 30 дн', '30–90 дн', '90–180 дн', '180–365 дн', '> 365 дн'];
803    const byCat: Record<string, Record<string, number>> = {};
804    const byDays: Record<string, number> = Object.fromEntries(DAYS.map((d) => [d, 0]));
805    for (const r of rows) {
806      if (r.expiry_day == null) continue;
807      const left = r.expiry_day - day;
808      let b: string;
809      if (r.status === 'EXPIRED' || left < 0) b = BUCKETS[0];
810      else if (r.mfg_day == null) b = BUCKETS[5];
811      else {
812        const f = left / (r.expiry_day - r.mfg_day);
813        b = f < 0.1 ? BUCKETS[1] : f < 0.25 ? BUCKETS[2] : f < 0.5 ? BUCKETS[3] : BUCKETS[4];
814      }
815      (byCat[r.category] ??= Object.fromEntries(BUCKETS.map((x) => [x, 0])))[b] += r.quantity;
816      const d = left < 0 ? DAYS[0] : left < 30 ? DAYS[1] : left < 90 ? DAYS[2] : left < 180 ? DAYS[3] : left <= 365 ? DAYS[4] : DAYS[5];
817      byDays[d] += r.quantity;
818    }
819    const writtenOff = this.q(`SELECT p.category, -SUM(t.qty_delta) AS qty, COUNT(*) AS records FROM inventory_transaction t
820                               JOIN product p ON p.id = t.product_id WHERE t.type = 'WRITE_OFF' GROUP BY p.category`).all();
821    return { buckets: BUCKETS, byCategory: byCat, byDaysLeft: byDays, writtenOff };
822  }
823
824  profileReport(): { sql: string; calls: number; ms: number; rows: number }[] {
825    return [...this.profile.entries()].map(([sql, r]) => ({ sql, ...r })).sort((a, b) => b.ms - a.ms);
826  }
827
828  recordsPerProduct(): { p50: number; p95: number; p99: number; max: number } {
829    const n = (this.q('SELECT COUNT(*) AS n FROM inventory_item GROUP BY product_id ORDER BY n').all() as { n: number }[]).map((r) => r.n);
830    const at = (p: number) => n[Math.min(n.length - 1, Math.floor(p * n.length))] ?? 0;
831    return { p50: at(0.5), p95: at(0.95), p99: at(0.99), max: n.at(-1) ?? 0 };
832  }
833
834  stats(): Record<string, unknown> {
835    const one = (sql: string) => Object.values(this.q(sql).get() as object)[0];
836    const loose = this.q(`SELECT COUNT(*) AS n FROM inventory_item WHERE is_container = 0 AND pack_type = 'unit' AND serial_number IS NULL
837                          GROUP BY product_id`).all() as { n: number }[];
838    return {
839      products: one('SELECT COUNT(*) FROM product'),
840      items_current: one('SELECT COUNT(*) FROM inventory_item'),
841      containers_current: one('SELECT COUNT(*) FROM inventory_item WHERE is_container = 1'),
842      items_archive: one('SELECT COUNT(*) FROM inventory_item_archive'),
843      transactions: one('SELECT COUNT(*) FROM inventory_transaction'),
844      tx_by_type: Object.fromEntries((this.q('SELECT type, COUNT(*) n FROM inventory_transaction GROUP BY type ORDER BY n DESC').all() as { type: string; n: number }[]).map((r) => [r.type, r.n])),
845      stock_units: one('SELECT SUM(quantity) FROM product_stock'),
846      labeled_items: one('SELECT COUNT(*) FROM inventory_item WHERE label_code IS NOT NULL'),
847      serial_units: one('SELECT COUNT(*) FROM inventory_item WHERE serial_number IS NOT NULL'),
848      expired_items: one("SELECT COUNT(*) FROM inventory_item WHERE status = 'EXPIRED'"),
849      loose_records_per_product_avg: loose.length ? +(loose.reduce((s, r) => s + r.n, 0) / loose.length).toFixed(2) : 0,
850      loose_records_per_product_max: loose.reduce((m, r) => Math.max(m, r.n), 0),
851      products_with_multiple_loose: loose.filter((r) => r.n > 1).length,
852      items_per_product_max: one('SELECT MAX(n) FROM (SELECT COUNT(*) n FROM inventory_item GROUP BY product_id)'),
853    };
854  }
855}
856