schema.ts
TypeScript · 202 рядків
1// Схема R-03 у двох варіантах на тих самих полях:
2// v1 — «як R-02 + warehouse_id»: одна таблиця на всі склади, журнал і архів — суцільні таблиці;
3// v2 — розділення: запас за складом (LIST), журнал і архів за місяцем (RANGE), fillfactor під HOT-оновлення.
4// Коди замість тексту: pack_type, status, type — smallint (вужчий рядок, менші індекси).
5
6export type Variant = 'v1' | 'v2';
7export const WAREHOUSES = 5;
8
9// pack_type: 0 unit, 1 bag, 2 box, 3 carton, 4 bundle (спайка), 5 pallet
10// status поточний: 1 ACTIVE, 2 EXPIRED; фінальний в архіві: 10 ISSUED, 11 OPENED, 12 ADJUSTED, 13 REPACKED, 14 WRITTEN_OFF
11// type журналу: 1 RECEIVE, 2 ISSUE, 3 OPEN, 4 SPLIT, 5 RETURN, 6 ADJUSTMENT, 7 WRITE_OFF, 8 TRANSFER_OUT
12export const PT = { unit: 0, bag: 1, box: 2, carton: 3, bundle: 4, pallet: 5 } as const;
13export const ST = { ACTIVE: 1, EXPIRED: 2, ISSUED: 10, OPENED: 11 } as const;
14export const TX = { RECEIVE: 1, ISSUE: 2, OPEN: 3 } as const;
15
16const months = (from: string, n: number) =>
17 Array.from({ length: n }, (_, i) => {
18 const d = new Date(`${from}-01T00:00:00Z`);
19 d.setUTCMonth(d.getUTCMonth() + i);
20 const e = new Date(d);
21 e.setUTCMonth(e.getUTCMonth() + 1);
22 return { tag: d.toISOString().slice(0, 7).replace('-', '_'), from: d.toISOString().slice(0, 10), to: e.toISOString().slice(0, 10) };
23 });
24
25const ITEM_COLS = `
26 warehouse_id smallint NOT NULL,
27 product_id int NOT NULL,
28 is_container boolean NOT NULL DEFAULT false,
29 pack_type smallint NOT NULL,
30 status smallint NOT NULL,
31 pack_size int NOT NULL,
32 pack_count int NOT NULL,
33 quantity int NOT NULL,
34 contained_in_id bigint,
35 source_id bigint,
36 receipt_id bigint,
37 mfg_date date,
38 expiry_date date,
39 received_at timestamptz NOT NULL,
40 location_id int NOT NULL,
41 label_code text,
42 serial_number text`;
43
44export function ddl(v: Variant): string {
45 const common = `
46DROP SCHEMA IF EXISTS wms CASCADE;
47CREATE SCHEMA wms;
48SET search_path = wms;
49
50CREATE TABLE category (
51 id smallint PRIMARY KEY, name text NOT NULL,
52 pack1 int NOT NULL, pack1_type smallint NOT NULL, -- менше пакування (пакет/коробка)
53 pack2 int, pack2_type smallint, -- більше пакування
54 life_min int NOT NULL, life_max int NOT NULL, serial boolean NOT NULL DEFAULT false
55);
56INSERT INTO category VALUES
57 (1,'Кріплення',10,1,100,2,1825,3650,false),
58 (2,'Свічки',4,2,40,3,1825,3650,false),
59 (3,'Фільтри',1,0,12,3,1095,1825,false),
60 (4,'Гальмівні колодки',1,0,10,3,1095,1825,false),
61 (5,'Лампи',10,2,100,3,1825,3650,false),
62 (6,'Герметики',12,2,NULL,NULL,365,720,false),
63 (7,'Масла',4,2,NULL,NULL,1095,1825,false),
64 (8,'Підшипники і ремені',10,2,NULL,NULL,1095,2555,false),
65 (9,'Дорогі вузли',1,0,NULL,NULL,1825,3650,true);
66
67CREATE TABLE product (
68 id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
69 brand_id smallint NOT NULL,
70 sku text NOT NULL,
71 category_id smallint NOT NULL REFERENCES category,
72 shelf_life_days int,
73 UNIQUE (brand_id, sku) -- бізнес-ключ бренд + SKU
74);
75
76-- Кеш: фізичний і доступний залишок товару на складі; змінюється в тій самій транзакції, що й записи.
77CREATE TABLE product_stock (
78 warehouse_id smallint NOT NULL,
79 product_id int NOT NULL,
80 quantity int NOT NULL,
81 available int NOT NULL,
82 PRIMARY KEY (warehouse_id, product_id)
83) ${v === 'v2' ? 'WITH (fillfactor = 70)' : ''};
84
85-- Контрольна точка інкрементальної звірки.
86CREATE TABLE reconcile_checkpoint (
87 warehouse_id smallint NOT NULL, product_id int NOT NULL, quantity int NOT NULL,
88 PRIMARY KEY (warehouse_id, product_id)
89);
90CREATE TABLE reconcile_meta (k text PRIMARY KEY, v bigint NOT NULL);
91`;
92
93 if (v === 'v1') {
94 return common + `
95CREATE TABLE inventory_item (id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, ${ITEM_COLS});
96CREATE INDEX ix_item_wh_product ON inventory_item (warehouse_id, product_id);
97CREATE INDEX ix_item_container ON inventory_item (contained_in_id) WHERE contained_in_id IS NOT NULL;
98CREATE INDEX ix_item_expiry ON inventory_item (status, expiry_date);
99
100CREATE TABLE inventory_item_archive (id bigint PRIMARY KEY, ${ITEM_COLS},
101 archived_at timestamptz NOT NULL, quantity_final int NOT NULL);
102
103CREATE TABLE inventory_transaction (
104 id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
105 created_at timestamptz NOT NULL DEFAULT now(),
106 warehouse_id smallint NOT NULL, type smallint NOT NULL, product_id int NOT NULL, item_id bigint NOT NULL,
107 qty_delta int NOT NULL, doc_id bigint, related_item_id bigint, user_id int
108);
109CREATE INDEX ix_tx_product ON inventory_transaction (warehouse_id, product_id, id);
110CREATE INDEX ix_tx_item ON inventory_transaction (item_id);
111`;
112 }
113
114 const m = months('2026-01', 24);
115 return common + `
116CREATE TABLE inventory_item (id bigint GENERATED BY DEFAULT AS IDENTITY, ${ITEM_COLS},
117 PRIMARY KEY (warehouse_id, id)) PARTITION BY LIST (warehouse_id);
118${Array.from({ length: WAREHOUSES }, (_, i) => `CREATE TABLE inventory_item_w${i + 1} PARTITION OF inventory_item FOR VALUES IN (${i + 1}) WITH (fillfactor = 80);`).join('\n')}
119CREATE INDEX ix_item_wh_product ON inventory_item (warehouse_id, product_id);
120CREATE INDEX ix_item_container ON inventory_item (contained_in_id) WHERE contained_in_id IS NOT NULL;
121CREATE INDEX ix_item_expiry ON inventory_item (status, expiry_date);
122
123CREATE TABLE inventory_item_archive (id bigint NOT NULL, ${ITEM_COLS},
124 archived_at timestamptz NOT NULL, quantity_final int NOT NULL,
125 PRIMARY KEY (id, archived_at)) PARTITION BY RANGE (archived_at);
126${m.map((x) => `CREATE TABLE inventory_item_archive_${x.tag} PARTITION OF inventory_item_archive FOR VALUES FROM ('${x.from}') TO ('${x.to}');`).join('\n')}
127
128CREATE TABLE inventory_transaction (
129 id bigint GENERATED ALWAYS AS IDENTITY,
130 created_at timestamptz NOT NULL DEFAULT now(),
131 warehouse_id smallint NOT NULL, type smallint NOT NULL, product_id int NOT NULL, item_id bigint NOT NULL,
132 qty_delta int NOT NULL, doc_id bigint, related_item_id bigint, user_id int,
133 PRIMARY KEY (id, created_at)
134) PARTITION BY RANGE (created_at);
135${m.map((x) => `CREATE TABLE inventory_transaction_${x.tag} PARTITION OF inventory_transaction FOR VALUES FROM ('${x.from}') TO ('${x.to}');`).join('\n')}
136CREATE INDEX ix_tx_product ON inventory_transaction (warehouse_id, product_id, id);
137CREATE INDEX ix_tx_item ON inventory_transaction (item_id);
138`;
139}
140
141// Повний обсяг: 300 тис. SKU × до 150 брендів ≈ 2 млн товарів; на кожному з 5 складів ~85% товарів по 5–100 шт.,
142// 1–3 поставки на товар (простежуваність до поставки, R-02.11), пакування за категорією + розсип.
143export const SEED = `
144SET search_path = wms;
145SELECT setseed(0.42);
146
147INSERT INTO product (brand_id, sku, category_id, shelf_life_days)
148SELECT b.brand_id, s.sku, s.cat, CASE WHEN random() < 0.3 THEN NULL ELSE c.life_min + floor(random() * (c.life_max - c.life_min))::int END
149FROM (
150 SELECT lpad(g::text, 7, '0') AS sku, (1 + floor(random() * 9))::smallint AS cat,
151 CASE WHEN random() < 0.04 THEN 40 + floor(random() * 110) ELSE 1 + floor(random() * 7) END::int AS nb
152 FROM generate_series(1, 300000) g
153) s
154JOIN category c ON c.id = s.cat
155CROSS JOIN LATERAL (
156 SELECT DISTINCT (1 + floor(random() * 150))::smallint AS brand_id FROM generate_series(1, s.nb) k WHERE s.sku IS NOT NULL
157) b;
158
159-- Позиції складу: товар × склад, 1–3 поставки.
160CREATE TEMP TABLE pos AS
161SELECT w AS warehouse_id, p.id AS product_id, p.category_id, p.shelf_life_days,
162 g AS lot_no,
163 (5 + floor(random() * 96))::int / n.k AS qty
164FROM product p
165CROSS JOIN generate_series(1, ${WAREHOUSES}) w
166CROSS JOIN LATERAL (SELECT CASE WHEN r < 0.65 THEN 1 WHEN r < 0.9 THEN 2 ELSE 3 END AS k FROM (SELECT random() + p.id * 0 AS r) z) n
167CROSS JOIN LATERAL generate_series(1, n.k) g
168WHERE random() < 0.85;
169
170-- Групи цілих пакувань (менше пакування категорії) і розсип-залишок.
171INSERT INTO inventory_item (warehouse_id, product_id, pack_type, status, pack_size, pack_count, quantity,
172 receipt_id, mfg_date, expiry_date, received_at, location_id)
173SELECT x.warehouse_id, x.product_id, x.pt, 1, x.sz, x.cnt, x.sz * x.cnt,
174 (x.product_id::bigint * 10 + x.lot_no), x.mfg, x.mfg + coalesce(x.shelf_life_days, 1825),
175 now() - (random() * interval '180 days'), (random() * 200000)::int
176FROM (
177 SELECT q.*, c.pack1 AS sz, c.pack1_type AS pt, q.qty / c.pack1 AS cnt,
178 current_date - (random() * 400)::int AS mfg
179 FROM pos q JOIN category c ON c.id = q.category_id
180 WHERE c.pack1 > 1 AND q.qty >= c.pack1
181 UNION ALL
182 SELECT q.*, 1, 0, CASE WHEN c.pack1 > 1 THEN q.qty % c.pack1 ELSE q.qty END,
183 current_date - (random() * 400)::int
184 FROM pos q JOIN category c ON c.id = q.category_id
185 WHERE (c.pack1 = 1 OR q.qty % c.pack1 > 0) AND q.qty > 0
186) x
187WHERE x.cnt > 0;
188
189INSERT INTO product_stock (warehouse_id, product_id, quantity, available)
190SELECT warehouse_id, product_id, sum(quantity), sum(quantity) FROM inventory_item WHERE is_container = false
191GROUP BY warehouse_id, product_id;
192
193-- Журнал: прихід кожного запису (база для звірки «кеш = сума журналу»).
194INSERT INTO inventory_transaction (created_at, warehouse_id, type, product_id, item_id, qty_delta, doc_id)
195SELECT received_at, warehouse_id, 1, product_id, id, quantity, receipt_id FROM inventory_item;
196
197INSERT INTO reconcile_checkpoint SELECT warehouse_id, product_id, quantity FROM product_stock;
198INSERT INTO reconcile_meta VALUES ('tx', (SELECT max(id) FROM inventory_transaction));
199
200ANALYZE;
201`;
202