techtools
Головна / research / lab / stock-db / src / stock.service.ts

stock.service.ts

TypeScript · 818 рядків

1/**
2 * Облік запасу — production-варіант доступу до бази (приклад для R-05).
3 *
4 * Шари (залежності спрямовані лише вниз; верхні шари знають тільки інтерфейси нижніх):
5 *   StockModule (корінь композиції)
6 *     ├─ сервіси сценаріїв: ReceivingService, IssuingService, ReconciliationService, JournalArchiver
7 *     ├─ репозиторії: CatalogRepository, StockStatsRepository, MigrationRunner
8 *     ├─ політики: AllocationPolicy (відбір), ArchiveIndexStrategy (індекс архіву), RetryPolicy (повтори)
9 *     └─ інфраструктура: Db (PgDb), Logger
10 *
11 * Інваріанти, які забезпечує цей шар:
12 *   • будь-яка зміна залишку — одна транзакція БД (R-01.10);
13 *   • порядок блокувань: спершу рядки product_stock (у порядку product_id), потім записи запасу — однаково
14 *     для приймання й видачі (R-05: інакше взаємні блокування через постійний розсип);
15 *   • блокування й читання — окремі оператори (R-03 §3.4, READ COMMITTED);
16 *   • зміни наявних записів — приростами, щоб паралельне доливання розсипу не губилося;
17 *   • взаємні блокування й конфлікти серіалізації — повтор з експоненційною затримкою; решта помилок — нагору.
18 *
19 * Текст кожного запиту — у методі, що його виконує; параметри іменовані (:name → див. named()).
20 * Схема — migrations/001_stock_v4.sql. Чинний stock.ts лишається для прогонів; цей файл — еталон стилю.
21 */
22import { readdirSync, readFileSync } from 'node:fs';
23import { join } from 'node:path';
24import { fileURLToPath } from 'node:url';
25import pg from 'pg';
26import { allocate, newAllocResult, type AllocResult, type AllocRow } from './alloc.ts';
27import {
28  PackType, Status, TxType,
29  type ArchiveResult, type Brand, type Category, type ConsolidationResult, type IssueDocument, type IssueResult,
30  type ItemStats, type LowStockRow, type NewProduct, type ReceiveLot, type ReceiveResult, type TableSize, type Warehouse, type WarehouseStock,
31} from './models.ts';
32
33// =====================================================================================================================
34// Інфраструктура
35// =====================================================================================================================
36
37export interface TxOptions {
38  isolation?: 'read committed' | 'repeatable read' | 'serializable';
39  readOnly?: boolean;
40  lockTimeoutMs?: number;       // скільки чекати на блокування рядка, перш ніж відмовити
41  statementTimeoutMs?: number;  // межа тривалості одного оператора
42}
43
44/** Мінімальний контракт доступу до бази, від якого залежать сервіси (DIP, ISP). */
45export interface Db {
46  query<R = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<R[]>;
47  execute(sql: string, params?: readonly unknown[]): Promise<number>;
48  transaction<T>(fn: (tx: Db) => Promise<T>, opts?: TxOptions): Promise<T>;
49}
50
51export interface Logger {
52  debug(msg: string, ctx?: Record<string, unknown>): void;
53  info(msg: string, ctx?: Record<string, unknown>): void;
54  warn(msg: string, ctx?: Record<string, unknown>): void;
55  error(msg: string, ctx?: Record<string, unknown>): void;
56}
57
58export const silentLogger: Logger = { debug() {}, info() {}, warn() {}, error() {} };
59
60pg.types.setTypeParser(20, (v) => Number(v));     // bigint → number (id < 2^53)
61pg.types.setTypeParser(1082, (v) => v);           // date — рядком YYYY-MM-DD
62pg.types.setTypeParser(1184, (v) => v);           // timestamptz — рядком ISO
63
64/** Реалізація Db на node-postgres. Транзакція отримує власне з'єднання з пулу. */
65export class PgDb implements Db {
66  private readonly pool: pg.Pool;
67  private readonly client: pg.PoolClient | null;
68  private readonly defaults: TxOptions;
69
70  constructor(pool: pg.Pool, defaults: TxOptions = {}, client: pg.PoolClient | null = null) {
71    this.pool = pool;
72    this.defaults = defaults;
73    this.client = client;
74  }
75
76  async query<R>(sql: string, params: readonly unknown[] = []): Promise<R[]> {
77    const r = await (this.client ?? this.pool).query(sql, params as unknown[]);
78    return r.rows as R[];
79  }
80
81  async execute(sql: string, params: readonly unknown[] = []): Promise<number> {
82    const r = await (this.client ?? this.pool).query(sql, params as unknown[]);
83    return r.rowCount ?? 0;
84  }
85
86  async transaction<T>(fn: (tx: Db) => Promise<T>, opts: TxOptions = {}): Promise<T> {
87    if (this.client) return fn(this);            // вкладений виклик — у межах уже відкритої транзакції
88    const o = { ...this.defaults, ...opts };
89    const c = await this.pool.connect();
90    try {
91      await c.query(`BEGIN ISOLATION LEVEL ${(o.isolation ?? 'read committed').toUpperCase()}${o.readOnly ? ' READ ONLY' : ''}`);
92      if (o.lockTimeoutMs) await c.query(`SET LOCAL lock_timeout = ${Math.trunc(o.lockTimeoutMs)}`);
93      if (o.statementTimeoutMs) await c.query(`SET LOCAL statement_timeout = ${Math.trunc(o.statementTimeoutMs)}`);
94      const result = await fn(new PgDb(this.pool, this.defaults, c));
95      await c.query('COMMIT');
96      return result;
97    } catch (e) {
98      await c.query('ROLLBACK').catch(() => {});
99      throw e;
100    } finally {
101      c.release();
102    }
103  }
104
105  async close(): Promise<void> {
106    await this.pool.end();
107  }
108}
109
110const ident = (name: string) => pg.Client.prototype.escapeIdentifier(name);
111const literal = (value: string) => pg.Client.prototype.escapeLiteral(value);
112
113/**
114 * Іменовані параметри для читабельності запитів: `:warehouse_id` → `$1`.
115 * Приведення типів PostgreSQL (`::int`) не чіпає; той самий параметр можна вживати кілька разів.
116 */
117export function named(text: string, values: Record<string, unknown>): [string, unknown[]] {
118  const order: string[] = [];
119  const sql = text.replace(/(?<!:):([a-z_][a-z0-9_]*)/gi, (_, name: string) => {
120    if (!(name in values)) throw new Error(`Немає значення параметра :${name}`);
121    let i = order.indexOf(name);
122    if (i < 0) i = order.push(name) - 1;
123    return `$${i + 1}`;
124  });
125  return [sql, order.map((n) => values[n])];
126}
127
128// =====================================================================================================================
129// Помилки й повтори
130// =====================================================================================================================
131
132export class StockError extends Error {
133  readonly code: string;
134  constructor(code: string, message: string, options?: { cause?: unknown }) {
135    super(message, options);
136    this.name = new.target.name;
137    this.code = code;
138  }
139}
140export class ValidationError extends StockError {
141  constructor(message: string) { super('VALIDATION', message); }
142}
143/** Тимчасовий конфлікт конкурентності — операцію можна повторити. */
144export class ConcurrencyError extends StockError {
145  constructor(message: string, cause: unknown) { super('CONCURRENCY', message, { cause }); }
146}
147export class NotFoundError extends StockError {
148  constructor(message: string) { super('NOT_FOUND', message); }
149}
150/** Немає розділу журналу на дату операції — не запущено обслуговування розділів (PartitionMaintenance). */
151export class PartitionMissingError extends StockError {
152  constructor(message: string, cause: unknown) { super('PARTITION_MISSING', message, { cause }); }
153}
154
155const RETRYABLE_PG = new Set(['40P01', '40001', '55P03']);   // deadlock, serialization failure, lock_timeout
156
157/** Перекласти помилку драйвера в доменну. */
158export function translateError(e: unknown): unknown {
159  const err = e as { code?: string; message?: string; detail?: string };
160  if (err?.code && RETRYABLE_PG.has(err.code)) return new ConcurrencyError(`Конфлікт конкурентності (${err.code})`, e);
161  if (err?.code === '23514' && err.message?.startsWith('no partition')) return new PartitionMissingError(`Немає розділу для операції: ${err.detail ?? ''}`, e);
162  return e;
163}
164
165export interface RetryPolicy {
166  run<T>(op: () => Promise<T>, label: string): Promise<T>;
167}
168
169/** Повтор лише для ConcurrencyError, з експоненційною затримкою і випадковим розкидом. */
170export class ExponentialRetry implements RetryPolicy {
171  private readonly attempts: number;
172  private readonly baseMs: number;
173  private readonly logger: Logger;
174
175  constructor(attempts = 5, baseMs = 5, logger: Logger = silentLogger) {
176    this.attempts = attempts;
177    this.baseMs = baseMs;
178    this.logger = logger;
179  }
180
181  async run<T>(op: () => Promise<T>, label: string): Promise<T> {
182    for (let attempt = 1; ; attempt++) {
183      try {
184        return await op();
185      } catch (raw) {
186        const e = translateError(raw);
187        if (!(e instanceof ConcurrencyError) || attempt >= this.attempts) throw e;   // інші помилки — одразу, вже доменні
188        const delay = this.baseMs * 2 ** (attempt - 1) * (0.5 + Math.random());
189        this.logger.warn('повтор після конфлікту', { label, attempt, delayMs: Math.round(delay) });
190        await new Promise((r) => setTimeout(r, delay));
191      }
192    }
193  }
194}
195
196// =====================================================================================================================
197// Перевірка вхідних даних
198// =====================================================================================================================
199
200const isPosInt = (x: unknown): x is number => Number.isInteger(x) && (x as number) > 0;
201const isIsoTime = (x: unknown) => typeof x === 'string' && !Number.isNaN(Date.parse(x));
202
203function validateLot(lot: ReceiveLot): void {
204  if (!isPosInt(lot.warehouseId) || !isPosInt(lot.productId)) throw new ValidationError('Потрібні склад і товар');
205  if (!lot.lines.length) throw new ValidationError('Партія без рядків');
206  for (const l of lot.lines) {
207    if (!isPosInt(l.pack_size) || !isPosInt(l.pack_count)) throw new ValidationError(`Некоректний рядок партії: ${JSON.stringify(l)}`);
208    if (l.pack_type === PackType.unit && l.pack_size !== 1) throw new ValidationError('Розсип має розмір пакування 1');
209    if (l.pack_type === PackType.bundle || l.pack_type === PackType.pallet) throw new ValidationError('Спайка/палета не може бути рядком партії');
210  }
211  if (!isIsoTime(lot.at)) throw new ValidationError('Некоректний час операції');
212  if (lot.expiryDate && lot.mfgDate && lot.expiryDate < lot.mfgDate) throw new ValidationError('Строк придатності раніше за виготовлення');
213}
214
215function validateDocument(doc: IssueDocument): void {
216  if (!isPosInt(doc.warehouseId)) throw new ValidationError('Потрібен склад');
217  if (!doc.lines.length) throw new ValidationError('Документ без рядків');
218  for (const l of doc.lines) if (!isPosInt(l.productId) || !isPosInt(l.qty)) throw new ValidationError(`Некоректний рядок документа: ${JSON.stringify(l)}`);
219  if (!isIsoTime(doc.at)) throw new ValidationError('Некоректний час операції');
220}
221
222// =====================================================================================================================
223// Політики
224// =====================================================================================================================
225
226/** Правило відбору: як розподілити кількість рядка між записами товару (у пам'яті, без бази). */
227export interface AllocationPolicy {
228  allocate(rows: AllocRow[], productId: number, qty: number, out: AllocResult, issueType: number): void;
229}
230
231/** R-02.7 + R-05: спайки → цілі пакування → розсип → розкриття; строгий FEFO; постійний розсип. */
232export const fefoPackFirstPolicy: AllocationPolicy = { allocate };
233
234/** Як організувати тиждень, що переходить в архів журналу (R-06). */
235export interface ArchiveIndexStrategy {
236  readonly name: 'none' | 'btree' | 'brin';
237  organize(db: Db, table: string): Promise<void>;
238}
239
240export class NoArchiveIndex implements ArchiveIndexStrategy {
241  readonly name = 'none' as const;
242  async organize(): Promise<void> {}
243}
244
245export class BTreeArchiveIndex implements ArchiveIndexStrategy {
246  readonly name = 'btree' as const;
247  async organize(db: Db, table: string): Promise<void> {
248    await db.execute(`CREATE INDEX ON stock.${ident(table)} (warehouse_id, product_id, created_at)`);
249  }
250}
251
252/** Впорядкувати тиждень за товаром (розділ більше не змінюється) і дати мініатюрний BRIN-індекс. */
253export class ClusteredBrinArchiveIndex implements ArchiveIndexStrategy {
254  readonly name = 'brin' as const;
255  private readonly pagesPerRange: number;
256  constructor(pagesPerRange = 8) { this.pagesPerRange = pagesPerRange; }
257  async organize(db: Db, table: string): Promise<void> {
258    const tmp = ident(`${table}_cluster_tmp`);
259    await db.execute(`CREATE INDEX ${tmp} ON stock.${ident(table)} (warehouse_id, product_id, created_at)`);
260    await db.execute(`CLUSTER stock.${ident(table)} USING ${tmp}`);
261    await db.execute(`DROP INDEX stock.${tmp}`);
262    await db.execute(`CREATE INDEX ON stock.${ident(table)} USING brin (warehouse_id, product_id) WITH (pages_per_range = ${Math.trunc(this.pagesPerRange)})`);
263  }
264}
265
266// =====================================================================================================================
267// Репозиторії
268// =====================================================================================================================
269
270/** Довідники: склади, бренди, категорії, товари. */
271export class CatalogRepository {
272  private readonly db: Db;
273  constructor(db: Db) { this.db = db; }
274
275  async saveWarehouses(list: readonly Warehouse[]): Promise<void> {
276    await this.db.execute(`INSERT INTO stock.warehouse (id, name) SELECT * FROM unnest($1::smallint[], $2::text[])
277                           ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name`, [list.map((w) => w.id), list.map((w) => w.name)]);
278  }
279
280  async saveBrands(list: readonly Brand[]): Promise<void> {
281    await this.db.execute(`INSERT INTO stock.brand (id, name) SELECT * FROM unnest($1::smallint[], $2::text[])
282                           ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name`, [list.map((b) => b.id), list.map((b) => b.name)]);
283  }
284
285  async saveCategories(list: readonly Category[]): Promise<void> {
286    await this.db.execute(`
287      INSERT INTO stock.category (id, name, kind, pack1_type, pack1_size, pack2_type, pack2_size, shelf_life_days, is_serial)
288      SELECT * FROM unnest($1::smallint[], $2::text[], $3::text[], $4::smallint[], $5::int[], $6::smallint[], $7::int[], $8::int[], $9::boolean[])
289      ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, kind = EXCLUDED.kind, pack1_type = EXCLUDED.pack1_type, pack1_size = EXCLUDED.pack1_size,
290        pack2_type = EXCLUDED.pack2_type, pack2_size = EXCLUDED.pack2_size, shelf_life_days = EXCLUDED.shelf_life_days, is_serial = EXCLUDED.is_serial`,
291    [list.map((c) => c.id), list.map((c) => c.name), list.map((c) => c.kind), list.map((c) => c.pack1_type), list.map((c) => c.pack1_size),
292      list.map((c) => c.pack2_type), list.map((c) => c.pack2_size), list.map((c) => c.shelf_life_days), list.map((c) => c.is_serial)]);
293  }
294
295  /** Додати товари пакетами; кожен пакет — окрема транзакція. Повертає id у порядку вхідного списку. */
296  async insertProducts(list: readonly NewProduct[], batchSize = 1000): Promise<number[]> {
297    const ids: number[] = [];
298    for (let i = 0; i < list.length; i += batchSize) {
299      const p = list.slice(i, i + batchSize);
300      const rows = await this.db.query<{ id: number }>(`
301        INSERT INTO stock.product (brand_id, sku, name, category_id, shelf_life_days)
302        SELECT b, s, n, c, l FROM unnest($1::smallint[], $2::text[], $3::text[], $4::smallint[], $5::int[]) WITH ORDINALITY AS x(b, s, n, c, l, ord)
303        ORDER BY ord RETURNING id`,
304      [p.map((x) => x.brand_id), p.map((x) => x.sku), p.map((x) => x.name), p.map((x) => x.category_id), p.map((x) => x.shelf_life_days)]);
305      ids.push(...rows.map((r) => r.id));
306    }
307    return ids;
308  }
309}
310
311/** Читання стану й статистики (без змін даних). */
312export class StockStatsRepository {
313  private readonly db: Db;
314  constructor(db: Db) { this.db = db; }
315
316  async lowStock(warehouseId: number, reorderPoints: ReadonlyMap<number, number> | number): Promise<LowStockRow[]> {
317    const rows = typeof reorderPoints === 'number'
318      ? await this.db.query<{ product_id: number; available: number }>(
319        'SELECT product_id, available FROM stock.product_stock WHERE warehouse_id = $1 AND available <= $2', [warehouseId, reorderPoints])
320      : await this.db.query<{ product_id: number; available: number }>(`
321        SELECT s.product_id, s.available FROM stock.product_stock s
322        JOIN unnest($2::int[], $3::int[]) AS t(pid, rop) ON t.pid = s.product_id
323        WHERE s.warehouse_id = $1 AND s.available <= t.rop`, [warehouseId, [...reorderPoints.keys()], [...reorderPoints.values()]]);
324    return rows.map((r) => ({ productId: r.product_id, available: r.available }));
325  }
326
327  async warehouseStock(): Promise<WarehouseStock[]> {
328    const rows = await this.db.query<{ warehouse_id: number; products: number; units: number; avg: number }>(`
329      SELECT warehouse_id, count(*) FILTER (WHERE quantity > 0)::int AS products, sum(quantity)::bigint AS units,
330             round(avg(quantity) FILTER (WHERE quantity > 0), 1)::float8 AS avg
331      FROM stock.product_stock GROUP BY 1 ORDER BY 1`);
332    return rows.map((r) => ({ warehouseId: r.warehouse_id, products: r.products, units: Number(r.units), avgPerProduct: r.avg }));
333  }
334
335  async tableSizes(): Promise<TableSize[]> {
336    const rows = await this.db.query<{ tbl: string; parts: number; rows: number; bytes: number; idx: number }>(`
337      SELECT coalesce(p.relname, c.relname) AS tbl, count(*)::int AS parts, sum(coalesce(st.n_live_tup, 0))::bigint AS rows,
338             sum(pg_total_relation_size(c.oid))::bigint AS bytes, sum(pg_indexes_size(c.oid))::bigint AS idx
339      FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace AND n.nspname = 'stock'
340      LEFT JOIN pg_inherits i ON i.inhrelid = c.oid LEFT JOIN pg_class p ON p.oid = i.inhparent
341      LEFT JOIN pg_stat_user_tables st ON st.relid = c.oid
342      WHERE c.relkind = 'r' AND c.relname <> 'schema_migrations' GROUP BY 1 ORDER BY 4 DESC`);
343    return rows.map((r) => ({ table: r.tbl, partitions: r.parts, rows: Number(r.rows), totalMB: Number(r.bytes) / 2 ** 20, indexMB: Number(r.idx) / 2 ** 20 }));
344  }
345
346  async itemStats(): Promise<ItemStats> {
347    const [a] = await this.db.query<{ records: number; loose: number; loose_zero: number; positions: number }>(`
348      SELECT count(*)::int AS records,
349             count(*) FILTER (WHERE pack_type = 0 AND NOT is_container AND contained_in_id IS NULL)::int AS loose,
350             count(*) FILTER (WHERE pack_type = 0 AND NOT is_container AND contained_in_id IS NULL AND quantity = 0)::int AS loose_zero,
351             count(DISTINCT (warehouse_id, product_id))::int AS positions
352      FROM stock.inventory_item`);
353    const b = await this.db.query<{ bucket: string; positions: number }>(`
354      SELECT CASE WHEN n <= 3 THEN n::text WHEN n <= 6 THEN '4–6' WHEN n <= 10 THEN '7–10' ELSE '>10' END AS bucket, count(*)::int AS positions
355      FROM (SELECT count(*) n FROM stock.inventory_item GROUP BY warehouse_id, product_id) x GROUP BY 1 ORDER BY min(n)`);
356    return { records: a.records, looseRecords: a.loose, looseZero: a.loose_zero, positions: a.positions, recordsPerPosition: b };
357  }
358}
359
360/** Обслуговування розділів: завчасно створити тижневі розділи журналу й місячні розділи архіву (запуск за розкладом). */
361export class PartitionMaintenance {
362  private readonly db: Db;
363  private readonly logger: Logger;
364  constructor(db: Db, logger: Logger = silentLogger) {
365    this.db = db;
366    this.logger = logger;
367  }
368
369  /** Гарантувати розділи від сьогодні на aheadWeeks тижнів уперед. Ідемпотентно. */
370  async ensureAhead(today: string, aheadWeeks = 8): Promise<number> {
371    return this.ensure(addDays(today, -7), addDays(today, aheadWeeks * 7));
372  }
373
374  async ensure(from: string, to: string): Promise<number> {
375    const [{ n }] = await this.db.query<{ n: number }>('SELECT stock.ensure_partitions($1::date, $2::date) AS n', [from, to]);
376    if (n) this.logger.info('створено розділи', { from, to, count: n });
377    return n;
378  }
379}
380
381/** Міграції: файли *.sql по порядку, кожен — одна транзакція; версія фіксується самим файлом. */
382export class MigrationRunner {
383  private readonly db: Db;
384  private readonly dir: string;
385  private readonly logger: Logger;
386  constructor(db: Db, dir: string, logger: Logger = silentLogger) {
387    this.db = db;
388    this.dir = dir;
389    this.logger = logger;
390  }
391
392  async migrate(): Promise<string[]> {
393    const [{ ok }] = await this.db.query<{ ok: boolean }>(`SELECT to_regclass('stock.schema_migrations') IS NOT NULL AS ok`);
394    const done = new Set(ok ? (await this.db.query<{ version: string }>('SELECT version FROM stock.schema_migrations')).map((r) => r.version) : []);
395    const applied: string[] = [];
396    for (const file of readdirSync(this.dir).filter((f) => f.endsWith('.sql')).sort()) {
397      const version = file.replace(/\.sql$/, '');
398      if (done.has(version)) continue;
399      await this.db.transaction((tx) => tx.execute(readFileSync(join(this.dir, file), 'utf8')));
400      this.logger.info('міграцію застосовано', { version });
401      applied.push(version);
402    }
403    return applied;
404  }
405}
406
407// =====================================================================================================================
408// Сервіси сценаріїв
409// =====================================================================================================================
410
411/** Приймання: одна партія товару — один оператор, одна транзакція (потоварне розвантаження). */
412export class ReceivingService {
413  private readonly db: Db;
414  private readonly retry: RetryPolicy;
415  constructor(db: Db, retry: RetryPolicy) {
416    this.db = db;
417    this.retry = retry;
418  }
419
420  async receive(lot: ReceiveLot): Promise<ReceiveResult> {
421    validateLot(lot);
422    const total = lot.lines.reduce((s, l) => s + l.pack_size * l.pack_count, 0);
423    const looseUnits = lot.lines.filter((l) => l.pack_type === PackType.unit).reduce((s, l) => s + l.pack_count, 0);
424    const [sql, params] = named(`
425      -- 1. Спершу блокуємо рядок залишку товару (той самий порядок блокувань, що й у видачі) і додаємо кількість.
426      WITH stock_row AS (
427        INSERT INTO stock.product_stock (warehouse_id, product_id, quantity, available)
428        VALUES (:warehouse_id, :product_id, :total, :total)
429        ON CONFLICT (warehouse_id, product_id) DO UPDATE
430          SET quantity  = stock.product_stock.quantity  + EXCLUDED.quantity,
431              available = stock.product_stock.available + EXCLUDED.available
432        RETURNING 1
433      ),
434      -- 2. Цілі пакування — нові записи цієї поставки (простежуваність до поставки, R-02.11).
435      packs AS (
436        INSERT INTO stock.inventory_item (warehouse_id, product_id, pack_type, status, pack_size, pack_count, quantity,
437                                          receipt_id, mfg_date, expiry_date, received_at, location_id)
438        SELECT :warehouse_id, :product_id, line.pack_type, ${Status.ACTIVE}, line.pack_size, line.pack_count,
439               line.pack_size * line.pack_count, :doc_id, :mfg_date, :expiry_date, :at, :location_id
440        FROM unnest(:pack_types::smallint[], :pack_sizes::int[], :pack_counts::int[]) AS line(pack_type, pack_size, pack_count),
441             stock_row
442        WHERE line.pack_type <> ${PackType.unit}
443        RETURNING id, quantity
444      ),
445      -- 3. Розсип доливається в постійний запис розсипу (склад + товар + адреса + стан + строк).
446      loose AS (
447        INSERT INTO stock.inventory_item (warehouse_id, product_id, pack_type, status, pack_size, pack_count, quantity,
448                                          receipt_id, mfg_date, expiry_date, received_at, location_id)
449        SELECT :warehouse_id, :product_id, ${PackType.unit}, ${Status.ACTIVE}, 1, :loose_units, :loose_units,
450               :doc_id, :mfg_date, :expiry_date, :at, :location_id
451        FROM stock_row
452        WHERE :loose_units::int > 0
453        -- ключ постійного розсипу = унікальний індекс ux_item_loose
454        ON CONFLICT (warehouse_id, product_id, location_id, status, (coalesce(expiry_date, 'infinity'::date)))
455          WHERE pack_type = 0 AND NOT is_container AND contained_in_id IS NULL AND serial_number IS NULL
456        DO UPDATE SET quantity   = stock.inventory_item.quantity   + EXCLUDED.quantity,
457                      pack_count = stock.inventory_item.pack_count + EXCLUDED.pack_count
458        RETURNING id
459      ),
460      -- 4. Журнал: по рядку на кожен запис, що отримав кількість.
461      journal AS (
462        INSERT INTO stock.inventory_transaction (created_at, warehouse_id, type, product_id, item_id, qty_delta, doc_id, user_id)
463        SELECT :at::timestamptz, :warehouse_id::smallint, :type::smallint, :product_id::int, id, quantity, :doc_id::bigint, :user_id::int
464        FROM packs
465        UNION ALL
466        SELECT :at::timestamptz, :warehouse_id::smallint, :type::smallint, :product_id::int, id, :loose_units::int, :doc_id::bigint, :user_id::int
467        FROM loose
468        RETURNING 1
469      )
470      SELECT (SELECT count(*) FROM packs)::int AS packs, (SELECT count(*) FROM journal)::int AS journal`, {
471      warehouse_id: lot.warehouseId, product_id: lot.productId, total, type: lot.type ?? TxType.RECEIVE,
472      doc_id: lot.docId, user_id: lot.userId, at: lot.at, location_id: lot.locationId, mfg_date: lot.mfgDate, expiry_date: lot.expiryDate,
473      pack_types: lot.lines.map((l) => l.pack_type), pack_sizes: lot.lines.map((l) => l.pack_size), pack_counts: lot.lines.map((l) => l.pack_count),
474      loose_units: looseUnits,
475    });
476    const [r] = await this.retry.run(() => this.db.query<{ packs: number; journal: number }>(sql, params), 'receive');
477    return { units: total, packRows: r.packs, looseUnits, journalRows: r.journal };
478  }
479}
480
481/** Видача документа (продаж, переміщення): блокування → читання → розподіл (політика) → один оператор змін. */
482export class IssuingService {
483  private readonly db: Db;
484  private readonly policy: AllocationPolicy;
485  private readonly retry: RetryPolicy;
486  private readonly tx: TxOptions;
487  constructor(db: Db, policy: AllocationPolicy, retry: RetryPolicy, tx: TxOptions = { lockTimeoutMs: 5_000, statementTimeoutMs: 30_000 }) {
488    this.db = db;
489    this.policy = policy;
490    this.retry = retry;
491    this.tx = tx;
492  }
493
494  async issue(doc: IssueDocument): Promise<IssueResult> {
495    validateDocument(doc);
496    const type = doc.type ?? TxType.ISSUE;
497    const demand = new Map<number, number>();
498    for (const l of doc.lines) demand.set(l.productId, (demand.get(l.productId) ?? 0) + l.qty);
499    const productIds = [...demand.keys()].sort((a, b) => a - b);
500    return this.retry.run(() => this.db.transaction(async (tx) => {
501      const locked = await this.lockProducts(tx, doc.warehouseId, productIds);
502      const byProduct = await this.readActiveItems(tx, doc.warehouseId, locked);
503      const out = newAllocResult();
504      for (const [productId, qty] of demand) this.policy.allocate(byProduct.get(productId) ?? [], productId, qty, out, type);
505      const journal = out.journal.length ? await this.persist(tx, doc, out) : 0;
506      return toIssueResult(demand, out, journal);
507    }, this.tx), 'issue');
508  }
509
510  /** Блокування рядків залишку в сталому порядку product_id — без взаємних блокувань між документами. */
511  private async lockProducts(tx: Db, warehouseId: number, productIds: number[]): Promise<number[]> {
512    const [sql, params] = named(`
513      SELECT product_id
514      FROM stock.product_stock
515      WHERE warehouse_id = :warehouse_id
516        AND product_id = ANY(:product_ids::int[])
517      ORDER BY product_id
518      FOR UPDATE`, { warehouse_id: warehouseId, product_ids: productIds });
519    return (await tx.query<{ product_id: number }>(sql, params)).map((r) => r.product_id);
520  }
521
522  /** Окремий оператор після блокування: у READ COMMITTED бачить усе, що зафіксували попередні документи (R-03 §3.4). */
523  private async readActiveItems(tx: Db, warehouseId: number, productIds: number[]): Promise<Map<number, AllocRow[]>> {
524    const [sql, params] = named(`
525      SELECT id, product_id, is_container, pack_type, pack_size, pack_count, quantity, contained_in_id, location_id,
526             mfg_date, expiry_date, received_at, serial_number IS NOT NULL AS serial
527      FROM stock.inventory_item
528      WHERE warehouse_id = :warehouse_id
529        AND product_id = ANY(:product_ids::int[])
530        AND status = ${Status.ACTIVE}`, { warehouse_id: warehouseId, product_ids: productIds });
531    return groupRows(await tx.query<Record<string, any>>(sql, params));
532  }
533
534  /** Усі зміни документа одним оператором: одне звертання до бази незалежно від кількості рядків. */
535  private async persist(tx: Db, doc: IssueDocument, out: AllocResult): Promise<number> {
536    const rows = [...out.rows];
537    const created = rows.filter((r) => r.isNew);
538    const changed = rows.filter((r) => !r.isNew && !r.archived && (r.packCount !== r.origCount || r.quantity !== r.origQuantity || r.freed));
539    const finished = rows.filter((r) => !r.isNew && r.archived);
540    const [sql, params] = named(`
541      -- 1. Новий розсип із розкритих пакувань — upsert у постійний запис розсипу; тимчасовий id → справжній.
542      WITH new_loose AS (
543        SELECT *
544        FROM unnest(:created_temp_ids::bigint[], :created_product_ids::int[], :created_quantities::int[], :created_locations::int[],
545                    :created_mfg::date[], :created_expiry::date[], :created_received::timestamptz[], :created_sources::bigint[])
546          AS n(temp_id, product_id, quantity, location_id, mfg_date, expiry_date, received_at, source_id)
547      ),
548      upserted AS (
549        INSERT INTO stock.inventory_item (warehouse_id, product_id, pack_type, status, pack_size, pack_count, quantity,
550                                          source_id, mfg_date, expiry_date, received_at, location_id)
551        SELECT :warehouse_id, n.product_id, ${PackType.unit}, ${Status.ACTIVE}, 1, n.quantity, n.quantity,
552               n.source_id, n.mfg_date, n.expiry_date, n.received_at, n.location_id
553        FROM new_loose n
554        -- ключ постійного розсипу = унікальний індекс ux_item_loose
555        ON CONFLICT (warehouse_id, product_id, location_id, status, (coalesce(expiry_date, 'infinity'::date)))
556          WHERE pack_type = 0 AND NOT is_container AND contained_in_id IS NULL AND serial_number IS NULL
557        DO UPDATE SET quantity   = stock.inventory_item.quantity   + EXCLUDED.quantity,
558                      pack_count = stock.inventory_item.pack_count + EXCLUDED.pack_count
559        RETURNING id, product_id, location_id, expiry_date
560      ),
561      id_map AS (
562        SELECT n.temp_id, u.id
563        FROM new_loose n
564        JOIN upserted u ON u.product_id = n.product_id
565                       AND u.location_id = n.location_id
566                       AND u.expiry_date IS NOT DISTINCT FROM n.expiry_date
567      ),
568      -- 2. Наявні записи — приростами (паралельне доливання розсипу не губиться); звільнені зі спайки — без вкладеності.
569      changed AS (
570        UPDATE stock.inventory_item i
571           SET pack_count      = i.pack_count + c.pack_count_delta,
572               quantity        = i.quantity   + c.quantity_delta,
573               contained_in_id = CASE WHEN c.freed THEN NULL ELSE i.contained_in_id END
574        FROM unnest(:changed_ids::bigint[], :changed_pack_count_deltas::int[], :changed_quantity_deltas::int[], :changed_freed::boolean[])
575          AS c(id, pack_count_delta, quantity_delta, freed)
576        WHERE i.id = c.id
577        RETURNING 1
578      ),
579      -- 3. Закінчені записи — з поточної таблиці в архів із фінальним станом і quantity_final.
580      finished AS (
581        SELECT *
582        FROM unnest(:finished_ids::bigint[], :finished_statuses::smallint[], :finished_quantities::int[]) AS f(id, status, quantity_final)
583      ),
584      removed AS (
585        DELETE FROM stock.inventory_item i
586        USING finished f
587        WHERE i.id = f.id
588        RETURNING i.*, f.status AS final_status, f.quantity_final
589      ),
590      archived AS (
591        INSERT INTO stock.inventory_item_archive (id, warehouse_id, product_id, is_container, pack_type, status, pack_size, pack_count, quantity,
592                                                  contained_in_id, source_id, receipt_id, mfg_date, expiry_date, received_at, location_id,
593                                                  label_code, serial_number, archived_at, quantity_final)
594        SELECT id, warehouse_id, product_id, is_container, pack_type, final_status, pack_size,
595               CASE WHEN is_container THEN pack_count ELSE 0 END,
596               CASE WHEN is_container THEN quantity   ELSE 0 END,
597               contained_in_id, source_id, receipt_id, mfg_date, expiry_date, received_at, location_id, label_code, serial_number,
598               :at, quantity_final
599        FROM removed
600        RETURNING 1
601      ),
602      -- 4. Журнал рухів; посилання на новий розсип — через id_map.
603      journal AS (
604        INSERT INTO stock.inventory_transaction (created_at, warehouse_id, type, product_id, item_id, qty_delta, doc_id, related_item_id, user_id)
605        SELECT :at, :warehouse_id, j.type, j.product_id, coalesce(item.id, j.item_id), j.qty_delta, :doc_id, coalesce(related.id, j.related_id), :user_id
606        FROM unnest(:journal_types::smallint[], :journal_product_ids::int[], :journal_item_ids::bigint[], :journal_deltas::int[], :journal_related_ids::bigint[])
607          AS j(type, product_id, item_id, qty_delta, related_id)
608        LEFT JOIN id_map item    ON item.temp_id    = j.item_id
609        LEFT JOIN id_map related ON related.temp_id = j.related_id
610        RETURNING 1
611      ),
612      -- 5. Кеш залишку — в тій самій транзакції (R-01.9).
613      stock_rows AS (
614        UPDATE stock.product_stock s
615           SET quantity  = s.quantity  + d.delta,
616               available = s.available + d.delta
617        FROM unnest(:stock_product_ids::int[], :stock_deltas::int[]) AS d(product_id, delta)
618        WHERE s.warehouse_id = :warehouse_id AND s.product_id = d.product_id
619        RETURNING 1
620      )
621      SELECT (SELECT count(*) FROM journal)::int AS journal`, {
622      warehouse_id: doc.warehouseId, doc_id: doc.docId, user_id: doc.userId, at: doc.at,
623      created_temp_ids: created.map((r) => r.id), created_product_ids: created.map((r) => r.productId),
624      created_quantities: created.map((r) => r.quantity), created_locations: created.map((r) => r.locationId),
625      created_mfg: created.map((r) => r.mfgDate), created_expiry: created.map((r) => r.expiryDate),
626      created_received: created.map((r) => r.receivedAt), created_sources: created.map((r) => r.sourceId ?? null),
627      changed_ids: changed.map((r) => r.id), changed_pack_count_deltas: changed.map((r) => r.packCount - r.origCount),
628      changed_quantity_deltas: changed.map((r) => r.quantity - r.origQuantity), changed_freed: changed.map((r) => !!r.freed),
629      finished_ids: finished.map((r) => r.id), finished_statuses: finished.map((r) => r.archived!.status),
630      finished_quantities: finished.map((r) => r.archived!.final),
631      journal_types: out.journal.map((j) => j.type), journal_product_ids: out.journal.map((j) => j.productId),
632      journal_item_ids: out.journal.map((j) => j.itemId), journal_deltas: out.journal.map((j) => j.delta),
633      journal_related_ids: out.journal.map((j) => j.relatedId),
634      stock_product_ids: [...out.stockDelta.keys()], stock_deltas: [...out.stockDelta.values()],
635    });
636    return (await tx.query<{ journal: number }>(sql, params))[0].journal;
637  }
638}
639
640function groupRows(rows: Record<string, any>[]): Map<number, AllocRow[]> {
641  const m = new Map<number, AllocRow[]>();
642  for (const r of rows) {
643    const row: AllocRow = {
644      id: r.id, productId: r.product_id, isContainer: r.is_container, packType: r.pack_type, packSize: r.pack_size,
645      packCount: r.pack_count, quantity: r.quantity, containedInId: r.contained_in_id, locationId: r.location_id,
646      expiryDate: r.expiry_date, mfgDate: r.mfg_date, receivedAt: r.received_at, serial: r.serial,
647      origCount: r.pack_count, origQuantity: r.quantity,
648    };
649    (m.get(row.productId) ?? m.set(row.productId, []).get(row.productId)!).push(row);
650  }
651  return m;
652}
653
654function toIssueResult(demand: Map<number, number>, out: AllocResult, journalRows: number): IssueResult {
655  return {
656    requested: [...demand.values()].reduce((s, q) => s + q, 0), issued: out.issued, short: out.short,
657    openedPacks: out.openedPacks, cutContainers: out.cutContainers, journalRows,
658    products: [...out.issuedByProduct].map(([productId, v]) => ({ productId, qty: v.qty, mfgDate: v.mfgDate, expiryDate: v.expiryDate })),
659  };
660}
661
662/** Тижнева консолідація: перевірити всі позиції, зсунути контрольну точку позиціям із рухами (без рядків RECONCILE). */
663export class ReconciliationService {
664  private readonly db: Db;
665  private readonly logger: Logger;
666  constructor(db: Db, logger: Logger = silentLogger) {
667    this.db = db;
668    this.logger = logger;
669  }
670
671  async consolidateWeek(weekStart: string): Promise<ConsolidationResult> {
672    const t = performance.now();
673    const end = addDays(weekStart, 7);
674    // перевірка в одному знімку: залишок і журнал узгоджені навіть під час роботи складу
675    const v = await this.verify();
676    if (v.bad) this.logger.error('розбіжність контрольної точки', { weekStart, positions: v.bad });
677    const advanced = await this.advance(`${end}T00:00:00Z`);
678    return { weekStart, positionsChecked: v.positions, mismatches: v.bad, advanced, ms: performance.now() - t };
679  }
680
681  /** Для кожної позиції: контрольна точка + рухи після неї = залишок. Один знімок — коректно й під час роботи складу. */
682  private async verify(): Promise<{ positions: number; bad: number }> {
683    const [v] = await this.db.transaction((tx) => tx.query<{ positions: number; bad: number }>(`
684      WITH moves_since_checkpoint AS (
685        SELECT j.warehouse_id, j.product_id, sum(j.qty_delta) AS delta
686        FROM stock.inventory_transaction j
687        JOIN stock.product_stock s USING (warehouse_id, product_id)
688        WHERE j.created_at >= s.checked_at
689        GROUP BY j.warehouse_id, j.product_id
690      )
691      SELECT count(*)::int AS positions,
692             count(*) FILTER (WHERE s.quantity <> s.checked_quantity + coalesce(m.delta, 0))::int AS bad
693      FROM stock.product_stock s
694      LEFT JOIN moves_since_checkpoint m USING (warehouse_id, product_id)`),
695    { isolation: 'repeatable read', readOnly: true });
696    return v;
697  }
698
699  /** Зсунути контрольну точку на межу тижня сумою рухів до неї — не залежить від поточного залишку, безпечно паралельно з видачею. */
700  private async advance(boundary: string): Promise<number> {
701    const [sql, params] = named(`
702      UPDATE stock.product_stock s
703         SET checked_quantity = s.checked_quantity + m.delta,
704             checked_at       = :boundary
705      FROM (
706        SELECT j.warehouse_id, j.product_id, sum(j.qty_delta) AS delta
707        FROM stock.inventory_transaction j
708        JOIN stock.product_stock s2 USING (warehouse_id, product_id)
709        WHERE j.created_at >= s2.checked_at
710          AND j.created_at <  :boundary
711        GROUP BY j.warehouse_id, j.product_id
712      ) m
713      WHERE s.warehouse_id = m.warehouse_id
714        AND s.product_id   = m.product_id`, { boundary });
715    return this.db.execute(sql, params);
716  }
717}
718
719/** Перенесення звіреного тижня з робочого журналу в архів без копіювання рядків; індекс — за стратегією. */
720export class JournalArchiver {
721  private readonly db: Db;
722  private readonly strategy: ArchiveIndexStrategy;
723  private readonly logger: Logger;
724  constructor(db: Db, strategy: ArchiveIndexStrategy, logger: Logger = silentLogger) {
725    this.db = db;
726    this.strategy = strategy;
727    this.logger = logger;
728  }
729
730  async archiveWeek(weekStart: string): Promise<ArchiveResult | null> {
731    const [{ name }] = await this.db.query<{ name: string }>(`SELECT 'inventory_transaction_' || to_char($1::date, 'IYYY"w"IW') AS name`, [weekStart]);
732    const attached = await this.db.query(`SELECT 1 FROM pg_inherits WHERE inhrelid = to_regclass($1) AND inhparent = 'stock.inventory_transaction'::regclass`, [`stock.${name}`]);
733    if (!attached.length) return null;
734    const table = `stock.${ident(name)}`;
735    let t = performance.now();
736    // CONCURRENTLY не блокує запис у поточний тиждень; виконується поза транзакцією
737    await this.db.execute(`ALTER TABLE stock.inventory_transaction DETACH PARTITION ${table} CONCURRENTLY`);
738    const detachMs = performance.now() - t;
739    t = performance.now();
740    for (const { indexname } of await this.db.query<{ indexname: string }>(`SELECT indexname FROM pg_indexes WHERE schemaname = 'stock' AND tablename = $1`, [name])) {
741      await this.db.execute(`DROP INDEX stock.${ident(indexname)}`);
742    }
743    await this.strategy.organize(this.db, name);
744    const organizeMs = performance.now() - t;
745    t = performance.now();
746    // обмеження за датами заздалегідь — ATTACH не перечитує розділ для перевірки меж
747    const from = literal(weekStart);
748    const to = literal(addDays(weekStart, 7));
749    await this.db.execute(`ALTER TABLE ${table} ADD CONSTRAINT ${ident(`${name}_range`)} CHECK (created_at >= ${from} AND created_at < ${to})`);
750    await this.db.execute(`ALTER TABLE stock.inventory_transaction_archive ATTACH PARTITION ${table} FOR VALUES FROM (${from}) TO (${to})`);
751    await this.db.execute(`ANALYZE ${table}`);
752    const attachMs = performance.now() - t;
753    const [s] = await this.db.query<{ rows: number; bytes: number }>(`SELECT coalesce(st.n_live_tup, 0)::bigint AS rows, pg_total_relation_size(c.oid)::bigint AS bytes
754      FROM pg_class c LEFT JOIN pg_stat_user_tables st ON st.relid = c.oid WHERE c.oid = to_regclass($1)`, [`stock.${name}`]);
755    this.logger.info('тиждень перенесено в архів', { partition: name, index: this.strategy.name });
756    return { partition: name, rows: Number(s.rows), index: this.strategy.name, detachMs, organizeMs, attachMs, sizeMB: Number(s.bytes) / 2 ** 20 };
757  }
758}
759
760const addDays = (ymd: string, days: number) => new Date(Date.parse(`${ymd}T00:00:00Z`) + days * 86_400_000).toISOString().slice(0, 10);
761
762// =====================================================================================================================
763// Корінь композиції
764// =====================================================================================================================
765
766export interface StockModuleOptions {
767  maxConnections?: number;
768  archiveIndex?: ArchiveIndexStrategy;
769  allocationPolicy?: AllocationPolicy;
770  retry?: RetryPolicy;
771  logger?: Logger;
772  migrationsDir?: string;
773}
774
775/** Збирає сервіси з однією базою. Замінні частини передаються через options (тести, інші стратегії). */
776export class StockModule {
777  readonly catalog: CatalogRepository;
778  readonly stats: StockStatsRepository;
779  readonly receiving: ReceivingService;
780  readonly issuing: IssuingService;
781  readonly reconciliation: ReconciliationService;
782  readonly archiver: JournalArchiver;
783  readonly migrations: MigrationRunner;
784  readonly partitions: PartitionMaintenance;
785  private readonly db: PgDb;
786
787  private constructor(db: PgDb, o: Required<StockModuleOptions>) {
788    this.db = db;
789    this.catalog = new CatalogRepository(db);
790    this.stats = new StockStatsRepository(db);
791    this.receiving = new ReceivingService(db, o.retry);
792    this.issuing = new IssuingService(db, o.allocationPolicy, o.retry);
793    this.reconciliation = new ReconciliationService(db, o.logger);
794    this.archiver = new JournalArchiver(db, o.archiveIndex, o.logger);
795    this.migrations = new MigrationRunner(db, o.migrationsDir, o.logger);
796    this.partitions = new PartitionMaintenance(db, o.logger);
797  }
798
799  static async connect(url: string, options: StockModuleOptions = {}): Promise<StockModule> {
800    const logger = options.logger ?? silentLogger;
801    const pool = new pg.Pool({ connectionString: url, max: options.maxConnections ?? 20 });
802    pool.on('error', (e) => logger.error('помилка неактивного з\'єднання', { message: e.message }));
803    await pool.query('SELECT 1');
804    return new StockModule(new PgDb(pool), {
805      maxConnections: options.maxConnections ?? 20,
806      archiveIndex: options.archiveIndex ?? new ClusteredBrinArchiveIndex(),
807      allocationPolicy: options.allocationPolicy ?? fefoPackFirstPolicy,
808      retry: options.retry ?? new ExponentialRetry(5, 5, logger),
809      logger,
810      migrationsDir: options.migrationsDir ?? fileURLToPath(new URL('../migrations', import.meta.url)),
811    });
812  }
813
814  async close(): Promise<void> {
815    await this.db.close();
816  }
817}
818