stock.ts
TypeScript · 430 рядків
1// Репозиторій обліку запасу: усі звернення до бази (схема stock, міграція 001_stock_v4).
2// Прогони й інші інструменти працюють лише через цей клас і моделі з models.ts.
3import { readdirSync, readFileSync } from 'node:fs';
4import { dirname, join } from 'node:path';
5import { fileURLToPath } from 'node:url';
6import pg from 'pg';
7import { allocate, isPersistentLoose, newAllocResult, type AllocRow } from './alloc.ts';
8import {
9 PackType, Status, TxType,
10 type ArchiveIndex, type ArchiveResult, type Brand, type Category, type ConsolidationResult, type IssueDocument, type IssueResult,
11 type ItemStats, type LowStockRow, type NewProduct, type ReceiveLot, type ReceiveResult, type StatementStat, type TableSize,
12 type Warehouse, type WarehouseStock,
13} from './models.ts';
14
15pg.types.setTypeParser(20, (v) => Number(v)); // bigint → number (id < 2^53)
16pg.types.setTypeParser(1082, (v) => v); // date — рядком
17pg.types.setTypeParser(1184, (v) => v); // timestamptz — рядком
18
19const MIGRATIONS = join(dirname(fileURLToPath(import.meta.url)), '..', 'migrations');
20export class StockRepository {
21 readonly pool: pg.Pool;
22
23 private constructor(pool: pg.Pool) {
24 this.pool = pool;
25 }
26
27 /** Підключення до бази обліку. maxConnections — скільки одночасних операцій. */
28 static async open(url: string, maxConnections = 20): Promise<StockRepository> {
29 const pool = new pg.Pool({ connectionString: url, max: maxConnections });
30 await pool.query('SELECT 1');
31 return new StockRepository(pool);
32 }
33
34 /** Створити (за потреби перестворити) базу з розширенням pg_stat_statements. */
35 static async createDatabase(serverUrl: string, name: string, drop = false): Promise<void> {
36 const admin = new pg.Client({ connectionString: `${serverUrl}/postgres` });
37 await admin.connect();
38 try {
39 if (drop) await admin.query(`DROP DATABASE IF EXISTS ${pg.Client.prototype.escapeIdentifier(name)} WITH (FORCE)`);
40 const exists = await admin.query('SELECT 1 FROM pg_database WHERE datname = $1', [name]);
41 if (!exists.rowCount) await admin.query(`CREATE DATABASE ${pg.Client.prototype.escapeIdentifier(name)}`);
42 } finally {
43 await admin.end();
44 }
45 const c = new pg.Client({ connectionString: `${serverUrl}/${name}` });
46 await c.connect();
47 await c.query('CREATE EXTENSION IF NOT EXISTS pg_stat_statements');
48 await c.end();
49 }
50
51 async close(): Promise<void> {
52 await this.pool.end();
53 }
54
55 // ---------- схема ----------
56
57 /** Застосувати нові файли migrations/*.sql по порядку; кожен файл — одна транзакція. */
58 async migrate(): Promise<string[]> {
59 const has = await this.pool.query(`SELECT to_regclass('stock.schema_migrations') IS NOT NULL AS ok`);
60 const done = new Set<string>(has.rows[0].ok ? (await this.pool.query('SELECT version FROM stock.schema_migrations')).rows.map((r) => r.version) : []);
61 const applied: string[] = [];
62 for (const f of readdirSync(MIGRATIONS).filter((x) => x.endsWith('.sql')).sort()) {
63 const version = f.replace(/\.sql$/, '');
64 if (done.has(version)) continue;
65 const c = await this.pool.connect();
66 try {
67 await c.query('BEGIN');
68 await c.query(readFileSync(join(MIGRATIONS, f), 'utf8'));
69 await c.query('COMMIT');
70 applied.push(version);
71 } catch (e) {
72 await c.query('ROLLBACK');
73 throw e;
74 } finally {
75 c.release();
76 }
77 }
78 return applied;
79 }
80
81 /** Тижневі розділи журналу й місячні розділи архіву записів на проміжок дат. */
82 async ensurePartitions(from: string, to: string): Promise<number> {
83 return (await this.pool.query('SELECT stock.ensure_partitions($1::date, $2::date) AS n', [from, to])).rows[0].n;
84 }
85
86 // ---------- довідники ----------
87
88 async saveWarehouses(list: Warehouse[]): Promise<void> {
89 await this.pool.query(`INSERT INTO stock.warehouse (id, name) SELECT * FROM unnest($1::smallint[], $2::text[])
90 ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name`, [list.map((w) => w.id), list.map((w) => w.name)]);
91 }
92
93 async saveBrands(list: Brand[]): Promise<void> {
94 await this.pool.query(`INSERT INTO stock.brand (id, name) SELECT * FROM unnest($1::smallint[], $2::text[])
95 ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name`, [list.map((b) => b.id), list.map((b) => b.name)]);
96 }
97
98 async saveCategories(list: Category[]): Promise<void> {
99 await this.pool.query(`
100 INSERT INTO stock.category (id, name, kind, pack1_type, pack1_size, pack2_type, pack2_size, shelf_life_days, is_serial)
101 SELECT * FROM unnest($1::smallint[], $2::text[], $3::text[], $4::smallint[], $5::int[], $6::smallint[], $7::int[], $8::int[], $9::boolean[])
102 ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, kind = EXCLUDED.kind, pack1_type = EXCLUDED.pack1_type, pack1_size = EXCLUDED.pack1_size,
103 pack2_type = EXCLUDED.pack2_type, pack2_size = EXCLUDED.pack2_size, shelf_life_days = EXCLUDED.shelf_life_days, is_serial = EXCLUDED.is_serial`,
104 [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),
105 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)]);
106 }
107
108 /** Додати товари пакетами (одна транзакція на пакет); повертає id у тому самому порядку. */
109 async insertProducts(list: NewProduct[], batch = 1000): Promise<number[]> {
110 const ids: number[] = [];
111 for (let i = 0; i < list.length; i += batch) {
112 const p = list.slice(i, i + batch);
113 const r = await this.pool.query(`
114 INSERT INTO stock.product (brand_id, sku, name, category_id, shelf_life_days)
115 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)
116 ORDER BY ord
117 RETURNING id`, [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)]);
118 ids.push(...r.rows.map((x) => x.id));
119 }
120 return ids;
121 }
122
123 async categories(): Promise<Category[]> {
124 return (await this.pool.query('SELECT * FROM stock.category ORDER BY id')).rows;
125 }
126
127 // ---------- операції ----------
128
129 /** Приймання однієї партії товару — одна транзакція (потоварне розвантаження). */
130 async receive(lot: ReceiveLot): Promise<ReceiveResult> {
131 const total = lot.lines.reduce((s, l) => s + l.pack_size * l.pack_count, 0);
132 const looseUnits = lot.lines.filter((l) => l.pack_type === PackType.unit).reduce((s, l) => s + l.pack_count, 0);
133 // Порядок блокувань як у видачі: спершу рядок product_stock (крок s виконується першим — на нього посилаються packs і loose),
134 // потім записи запасу; інакше — взаємні блокування з видачею, бо приймання доливає в постійний розсип.
135 const r = await this.pool.query(`
136 WITH s AS (
137 INSERT INTO stock.product_stock (warehouse_id, product_id, quantity, available) VALUES ($1, $2, $14, $14)
138 ON CONFLICT (warehouse_id, product_id) DO UPDATE
139 SET quantity = stock.product_stock.quantity + EXCLUDED.quantity, available = stock.product_stock.available + EXCLUDED.available
140 RETURNING 1 AS locked
141 ), packs AS (
142 INSERT INTO stock.inventory_item (warehouse_id, product_id, pack_type, status, pack_size, pack_count, quantity,
143 receipt_id, mfg_date, expiry_date, received_at, location_id)
144 SELECT $1, $2, l.pt, ${Status.ACTIVE}, l.sz, l.cnt, l.sz * l.cnt, $3, $4, $5, $6, $7
145 FROM unnest($8::smallint[], $9::int[], $10::int[]) AS l(pt, sz, cnt), s
146 WHERE l.pt <> ${PackType.unit}
147 RETURNING id, quantity
148 ), loose AS (
149 INSERT INTO stock.inventory_item (warehouse_id, product_id, pack_type, status, pack_size, pack_count, quantity,
150 receipt_id, mfg_date, expiry_date, received_at, location_id)
151 SELECT $1, $2, ${PackType.unit}, ${Status.ACTIVE}, 1, $11, $11, $3, $4, $5, $6, $7 FROM s WHERE $11::int > 0
152 -- ключ постійного розсипу = унікальний індекс ux_item_loose
153 ON CONFLICT (warehouse_id, product_id, location_id, status, (coalesce(expiry_date, 'infinity'::date)))
154 WHERE pack_type = 0 AND NOT is_container AND contained_in_id IS NULL AND serial_number IS NULL
155 DO UPDATE SET quantity = stock.inventory_item.quantity + EXCLUDED.quantity,
156 pack_count = stock.inventory_item.pack_count + EXCLUDED.pack_count
157 RETURNING id
158 ), j AS (
159 INSERT INTO stock.inventory_transaction (created_at, warehouse_id, type, product_id, item_id, qty_delta, doc_id, user_id)
160 SELECT $6::timestamptz, $1::smallint, $12::smallint, $2::int, id, quantity, $3::bigint, $13::int FROM packs
161 UNION ALL SELECT $6::timestamptz, $1::smallint, $12::smallint, $2::int, id, $11::int, $3::bigint, $13::int FROM loose
162 RETURNING 1
163 )
164 SELECT (SELECT count(*) FROM packs) AS packs, (SELECT count(*) FROM j) AS journal`, [
165 lot.warehouseId, lot.productId, lot.docId, lot.mfgDate, lot.expiryDate, lot.at, lot.locationId,
166 lot.lines.map((l) => l.pack_type), lot.lines.map((l) => l.pack_size), lot.lines.map((l) => l.pack_count),
167 looseUnits, lot.type ?? TxType.RECEIVE, lot.userId, total,
168 ]);
169 return { units: total, packRows: Number(r.rows[0].packs), looseUnits, journalRows: Number(r.rows[0].journal) };
170 }
171
172 /** Видача документа (продаж або переміщення) — одна транзакція, 5 звертань до бази незалежно від кількості рядків. */
173 async issue(doc: IssueDocument): Promise<IssueResult> {
174 const type = doc.type ?? TxType.ISSUE;
175 const lines = new Map<number, number>();
176 for (const l of doc.lines) lines.set(l.productId, (lines.get(l.productId) ?? 0) + l.qty);
177 const pids = [...lines.keys()].sort((a, b) => a - b);
178 const c = await this.pool.connect();
179 try {
180 await c.query('BEGIN');
181 // Блокування й читання — окремими операторами (R-03 §3.4: в READ COMMITTED інакше читаються застарілі записи).
182 const locked = await c.query(` SELECT product_id FROM stock.product_stock WHERE warehouse_id = $1 AND product_id = ANY($2::int[]) ORDER BY product_id FOR UPDATE`, [doc.warehouseId, pids]);
183 const read = await c.query(`
184 SELECT id, product_id, is_container, pack_type, pack_size, pack_count, quantity, contained_in_id, location_id,
185 mfg_date, expiry_date, received_at, serial_number IS NOT NULL AS serial
186 FROM stock.inventory_item
187 WHERE warehouse_id = $1 AND product_id = ANY($2::int[]) AND status = ${Status.ACTIVE}`, [doc.warehouseId, locked.rows.map((r) => r.product_id)]);
188 const byProduct = new Map<number, AllocRow[]>();
189 for (const r of read.rows) {
190 const row: AllocRow = {
191 id: r.id, productId: r.product_id, isContainer: r.is_container, packType: r.pack_type, packSize: r.pack_size,
192 packCount: r.pack_count, quantity: r.quantity, containedInId: r.contained_in_id, locationId: r.location_id,
193 expiryDate: r.expiry_date, mfgDate: r.mfg_date, receivedAt: r.received_at, serial: r.serial,
194 origCount: r.pack_count, origQuantity: r.quantity,
195 };
196 (byProduct.get(r.product_id) ?? byProduct.set(r.product_id, []).get(r.product_id)!).push(row);
197 }
198 const out = newAllocResult();
199 for (const [pid, qty] of lines) allocate(byProduct.get(pid) ?? [], pid, qty, out, type);
200
201 const rows = [...out.rows];
202 const nw = rows.filter((r) => r.isNew);
203 const upd = rows.filter((r) => !r.isNew && !r.archived && (r.packCount !== r.origCount || r.quantity !== r.origQuantity || r.freed));
204 const arc = rows.filter((r) => !r.isNew && r.archived);
205 let journal = 0;
206 if (out.journal.length) {
207 // Усі зміни документа одним оператором. Новий розсип — upsert у постійний запис; оновлення — приростами.
208 const f = await c.query(`
209 WITH nw AS (
210 SELECT * FROM unnest($2::bigint[], $3::int[], $4::int[], $5::int[], $6::date[], $7::date[], $8::timestamptz[], $9::bigint[])
211 AS n(temp, pid, q, loc, mfg, exp, recv, src)
212 ), ins AS (
213 INSERT INTO stock.inventory_item (warehouse_id, product_id, pack_type, status, pack_size, pack_count, quantity,
214 source_id, mfg_date, expiry_date, received_at, location_id)
215 SELECT $1, n.pid, ${PackType.unit}, ${Status.ACTIVE}, 1, n.q, n.q, n.src, n.mfg, n.exp, n.recv, n.loc FROM nw n
216 -- ключ постійного розсипу = унікальний індекс ux_item_loose
217 ON CONFLICT (warehouse_id, product_id, location_id, status, (coalesce(expiry_date, 'infinity'::date)))
218 WHERE pack_type = 0 AND NOT is_container AND contained_in_id IS NULL AND serial_number IS NULL
219 DO UPDATE SET quantity = stock.inventory_item.quantity + EXCLUDED.quantity,
220 pack_count = stock.inventory_item.pack_count + EXCLUDED.pack_count
221 RETURNING id, product_id, location_id, expiry_date
222 ), map AS (
223 SELECT n.temp, i.id FROM nw n JOIN ins i ON i.product_id = n.pid AND i.location_id = n.loc AND i.expiry_date IS NOT DISTINCT FROM n.exp
224 ), upd AS (
225 UPDATE stock.inventory_item i
226 SET pack_count = i.pack_count + u.dpc, quantity = i.quantity + u.dq,
227 contained_in_id = CASE WHEN u.freed THEN NULL ELSE i.contained_in_id END
228 FROM unnest($10::bigint[], $11::int[], $12::int[], $13::boolean[]) AS u(id, dpc, dq, freed)
229 WHERE i.id = u.id
230 RETURNING 1
231 ), f AS (
232 SELECT * FROM unnest($14::bigint[], $15::smallint[], $16::int[]) AS f(id, st, fin)
233 ), del AS (
234 DELETE FROM stock.inventory_item i USING f WHERE i.id = f.id
235 RETURNING i.*, f.st, f.fin
236 ), arc AS (
237 INSERT INTO stock.inventory_item_archive (id, warehouse_id, product_id, is_container, pack_type, status, pack_size, pack_count, quantity,
238 contained_in_id, source_id, receipt_id, mfg_date, expiry_date, received_at, location_id,
239 label_code, serial_number, archived_at, quantity_final)
240 SELECT id, warehouse_id, product_id, is_container, pack_type, st, pack_size,
241 CASE WHEN is_container THEN pack_count ELSE 0 END, CASE WHEN is_container THEN quantity ELSE 0 END,
242 contained_in_id, source_id, receipt_id, mfg_date, expiry_date, received_at, location_id, label_code, serial_number, $24, fin
243 FROM del
244 RETURNING 1
245 ), jr AS (
246 INSERT INTO stock.inventory_transaction (created_at, warehouse_id, type, product_id, item_id, qty_delta, doc_id, related_item_id, user_id)
247 SELECT $24, $1, j.type, j.pid, coalesce(m1.id, j.item), j.d, $22, coalesce(m2.id, j.rel), $23
248 FROM unnest($17::smallint[], $18::int[], $19::bigint[], $20::int[], $21::bigint[]) AS j(type, pid, item, d, rel)
249 LEFT JOIN map m1 ON m1.temp = j.item LEFT JOIN map m2 ON m2.temp = j.rel
250 RETURNING 1
251 ), st AS (
252 UPDATE stock.product_stock s SET quantity = s.quantity + d.d, available = s.available + d.d
253 FROM unnest($25::int[], $26::int[]) AS d(pid, d)
254 WHERE s.warehouse_id = $1 AND s.product_id = d.pid
255 RETURNING 1
256 )
257 SELECT (SELECT count(*) FROM jr) AS journal, (SELECT count(*) FROM upd) AS updated, (SELECT count(*) FROM arc) AS archived`, [
258 doc.warehouseId,
259 nw.map((r) => r.id), nw.map((r) => r.productId), nw.map((r) => r.quantity), nw.map((r) => r.locationId),
260 nw.map((r) => r.mfgDate), nw.map((r) => r.expiryDate), nw.map((r) => r.receivedAt), nw.map((r) => r.sourceId ?? null),
261 upd.map((r) => r.id), upd.map((r) => r.packCount - r.origCount), upd.map((r) => r.quantity - r.origQuantity), upd.map((r) => !!r.freed),
262 arc.map((r) => r.id), arc.map((r) => r.archived!.status), arc.map((r) => r.archived!.final),
263 out.journal.map((j) => j.type), out.journal.map((j) => j.productId), out.journal.map((j) => j.itemId), out.journal.map((j) => j.delta), out.journal.map((j) => j.relatedId),
264 doc.docId, doc.userId, doc.at,
265 [...out.stockDelta.keys()], [...out.stockDelta.values()],
266 ]);
267 journal = Number(f.rows[0].journal);
268 }
269 await c.query('COMMIT');
270 return {
271 requested: [...lines.values()].reduce((s, q) => s + q, 0), issued: out.issued, short: out.short,
272 openedPacks: out.openedPacks, cutContainers: out.cutContainers, journalRows: journal,
273 products: [...out.issuedByProduct].map(([productId, v]) => ({ productId, qty: v.qty, mfgDate: v.mfgDate, expiryDate: v.expiryDate })),
274 };
275 } catch (e) {
276 await c.query('ROLLBACK').catch(() => {});
277 throw e;
278 } finally {
279 c.release();
280 }
281 }
282
283 /** Позиції складу, де доступний залишок не більший за поріг (порогу на товар). */
284 async lowStock(warehouseId: number, thresholds: Map<number, number> | number): Promise<LowStockRow[]> {
285 if (typeof thresholds === 'number') {
286 const r = await this.pool.query('SELECT product_id, available FROM stock.product_stock WHERE warehouse_id = $1 AND available <= $2', [warehouseId, thresholds]);
287 return r.rows.map((x) => ({ productId: x.product_id, available: x.available }));
288 }
289 const r = await this.pool.query(`
290 SELECT s.product_id, s.available FROM stock.product_stock s
291 JOIN unnest($2::int[], $3::int[]) AS t(pid, rop) ON t.pid = s.product_id
292 WHERE s.warehouse_id = $1 AND s.available <= t.rop`, [warehouseId, [...thresholds.keys()], [...thresholds.values()]]);
293 return r.rows.map((x) => ({ productId: x.product_id, available: x.available }));
294 }
295
296 /** Товари з позицією на складі. */
297 async stockedProducts(warehouseId: number): Promise<number[]> {
298 return (await this.pool.query('SELECT product_id FROM stock.product_stock WHERE warehouse_id = $1', [warehouseId])).rows.map((r) => r.product_id);
299 }
300
301 // ---------- консолідація й архів журналу ----------
302
303 /**
304 * Тижнева консолідація: перевірити «контрольна точка + рухи після неї = залишок» для всіх позицій,
305 * потім зсунути контрольну точку на кінець тижня для позицій із рухами (без рядків RECONCILE).
306 */
307 async consolidateWeek(weekStart: string): Promise<ConsolidationResult> {
308 const t = performance.now();
309 const end = new Date(Date.parse(`${weekStart}T00:00:00Z`) + 7 * 86_400_000).toISOString();
310 const c = await this.pool.connect();
311 try {
312 await c.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');
313 const v = (await c.query(`
314 WITH t AS (
315 SELECT j.warehouse_id, j.product_id, sum(j.qty_delta) AS q
316 FROM stock.inventory_transaction j JOIN stock.product_stock s USING (warehouse_id, product_id)
317 WHERE j.created_at >= s.checked_at GROUP BY 1, 2)
318 SELECT count(*) AS positions, count(*) FILTER (WHERE s.quantity <> s.checked_quantity + coalesce(t.q, 0)) AS bad
319 FROM stock.product_stock s LEFT JOIN t USING (warehouse_id, product_id)`)).rows[0];
320 await c.query('COMMIT');
321 const adv = await c.query(`
322 UPDATE stock.product_stock s SET checked_quantity = s.checked_quantity + t.q, checked_at = $1
323 FROM (SELECT j.warehouse_id, j.product_id, sum(j.qty_delta) AS q
324 FROM stock.inventory_transaction j JOIN stock.product_stock s2 USING (warehouse_id, product_id)
325 WHERE j.created_at >= s2.checked_at AND j.created_at < $1 GROUP BY 1, 2) t
326 WHERE s.warehouse_id = t.warehouse_id AND s.product_id = t.product_id`, [end]);
327 return { weekStart, positionsChecked: Number(v.positions), mismatches: Number(v.bad), advanced: adv.rowCount ?? 0, ms: performance.now() - t };
328 } finally {
329 c.release();
330 }
331 }
332
333 /**
334 * Перенести тиждень у архів журналу: відключити розділ (без копіювання), організувати за варіантом індексу (R-06),
335 * під'єднати до inventory_transaction_archive. Тиждень має бути вже консолідований.
336 */
337 async archiveWeek(weekStart: string, index: ArchiveIndex): Promise<ArchiveResult | null> {
338 const name = (await this.pool.query(`SELECT 'inventory_transaction_' || to_char($1::date, 'IYYY"w"IW') AS n`, [weekStart])).rows[0].n as string;
339 const attached = await this.pool.query(`SELECT 1 FROM pg_inherits WHERE inhrelid = to_regclass($1) AND inhparent = 'stock.inventory_transaction'::regclass`, [`stock.${name}`]);
340 if (!attached.rowCount) return null;
341 const id = pg.Client.prototype.escapeIdentifier(name);
342 const from = weekStart;
343 const to = new Date(Date.parse(`${weekStart}T00:00:00Z`) + 7 * 86_400_000).toISOString().slice(0, 10);
344 let t = performance.now();
345 await this.pool.query(`ALTER TABLE stock.inventory_transaction DETACH PARTITION stock.${id} CONCURRENTLY`);
346 const detachMs = performance.now() - t;
347 t = performance.now();
348 // індекс робочого журналу на розділі більше не потрібен
349 for (const r of (await this.pool.query(`SELECT indexname FROM pg_indexes WHERE schemaname = 'stock' AND tablename = $1`, [name])).rows) {
350 await this.pool.query(`DROP INDEX stock.${pg.Client.prototype.escapeIdentifier(r.indexname)}`);
351 }
352 if (index === 'btree') {
353 await this.pool.query(`CREATE INDEX ON stock.${id} (warehouse_id, product_id, created_at)`);
354 } else if (index === 'brin') {
355 // впорядкувати рядки за товаром один раз (розділ більше не змінюється) і дати мініатюрний BRIN-індекс
356 const tmp = pg.Client.prototype.escapeIdentifier(`${name}_cluster_tmp`);
357 await this.pool.query(`CREATE INDEX ${tmp} ON stock.${id} (warehouse_id, product_id, created_at)`);
358 await this.pool.query(`CLUSTER stock.${id} USING ${tmp}`);
359 await this.pool.query(`DROP INDEX stock.${tmp}`);
360 await this.pool.query(`CREATE INDEX ON stock.${id} USING brin (warehouse_id, product_id) WITH (pages_per_range = 8)`);
361 }
362 const organizeMs = performance.now() - t;
363 t = performance.now();
364 await this.pool.query(`ALTER TABLE stock.inventory_transaction_archive ATTACH PARTITION stock.${id} FOR VALUES FROM ('${from}') TO ('${to}')`);
365 await this.pool.query(`ANALYZE stock.${id}`);
366 const attachMs = performance.now() - t;
367 const s = (await this.pool.query(`SELECT reltuples::bigint AS rows, pg_total_relation_size(oid) AS bytes FROM pg_class WHERE oid = to_regclass($1)`, [`stock.${name}`])).rows[0];
368 return { partition: name, rows: Number(s.rows), index, detachMs, organizeMs, attachMs, sizeMB: Number(s.bytes) / 2 ** 20 };
369 }
370
371 /** Історія руху товару за період з робочого журналу або з архіву (для R-06). */
372 async productHistory(warehouseId: number, productId: number, from: string, to: string, source: 'hot' | 'archive'): Promise<{ rows: number; delta: number; ms: number }> {
373 const t = performance.now();
374 const table = source === 'hot' ? 'stock.inventory_transaction' : 'stock.inventory_transaction_archive';
375 const r = (await this.pool.query(`SELECT count(*) AS n, coalesce(sum(qty_delta), 0) AS d FROM ${table}
376 WHERE warehouse_id = $1 AND product_id = $2 AND created_at >= $3 AND created_at < $4`, [warehouseId, productId, from, to])).rows[0];
377 return { rows: Number(r.n), delta: Number(r.d), ms: performance.now() - t };
378 }
379
380 // ---------- статистика ----------
381
382 async warehouseStock(): Promise<WarehouseStock[]> {
383 return (await this.pool.query(`
384 SELECT warehouse_id, count(*) FILTER (WHERE quantity > 0) AS products, sum(quantity) AS units,
385 round(avg(quantity) FILTER (WHERE quantity > 0), 1) AS avg
386 FROM stock.product_stock GROUP BY 1 ORDER BY 1`)).rows
387 .map((r) => ({ warehouseId: r.warehouse_id, products: Number(r.products), units: Number(r.units), avgPerProduct: Number(r.avg) }));
388 }
389
390 async tableSizes(): Promise<TableSize[]> {
391 return (await this.pool.query(`
392 SELECT coalesce(p.relname, c.relname) AS tbl, count(*) AS parts, sum(coalesce(st.n_live_tup, 0))::bigint AS rows,
393 sum(pg_total_relation_size(c.oid)) AS bytes, sum(pg_indexes_size(c.oid)) AS idx
394 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace AND n.nspname = 'stock'
395 LEFT JOIN pg_inherits i ON i.inhrelid = c.oid LEFT JOIN pg_class p ON p.oid = i.inhparent
396 LEFT JOIN pg_stat_user_tables st ON st.relid = c.oid
397 WHERE c.relkind = 'r' AND c.relname <> 'schema_migrations' GROUP BY 1 ORDER BY 4 DESC`)).rows
398 .map((r) => ({ table: r.tbl, partitions: Number(r.parts), rows: Math.max(0, Number(r.rows)), totalMB: Number(r.bytes) / 2 ** 20, indexMB: Number(r.idx) / 2 ** 20 }));
399 }
400
401 async itemStats(): Promise<ItemStats> {
402 const a = (await this.pool.query(`
403 SELECT count(*) AS records,
404 count(*) FILTER (WHERE pack_type = 0 AND NOT is_container AND contained_in_id IS NULL) AS loose,
405 count(*) FILTER (WHERE pack_type = 0 AND NOT is_container AND contained_in_id IS NULL AND quantity = 0) AS loose_zero,
406 count(DISTINCT (warehouse_id, product_id)) AS positions
407 FROM stock.inventory_item`)).rows[0];
408 const b = (await this.pool.query(`
409 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(*) AS positions
410 FROM (SELECT count(*) n FROM stock.inventory_item GROUP BY warehouse_id, product_id) x GROUP BY 1 ORDER BY min(n)`)).rows;
411 return { records: Number(a.records), looseRecords: Number(a.loose), looseZero: Number(a.loose_zero), positions: Number(a.positions),
412 recordsPerPosition: b.map((r) => ({ bucket: r.bucket, positions: Number(r.positions) })) };
413 }
414
415 async resetStatementStats(): Promise<void> {
416 await this.pool.query('SELECT public.pg_stat_statements_reset()');
417 }
418
419 async topStatements(limit = 8): Promise<StatementStat[]> {
420 return (await this.pool.query(`
421 SELECT calls, total_exec_time AS total, mean_exec_time AS mean, 100 * total_exec_time / sum(total_exec_time) OVER () AS pct,
422 left(regexp_replace(query, '\\s+', ' ', 'g'), 100) AS q
423 FROM public.pg_stat_statements WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
424 ORDER BY total_exec_time DESC LIMIT $1`, [limit])).rows
425 .map((r) => ({ calls: Number(r.calls), totalMs: Number(r.total), meanMs: Number(r.mean), pct: Number(r.pct), query: r.q }));
426 }
427}
428
429export { isPersistentLoose };
430