alloc.ts
TypeScript · 187 рядків
1// Відбір у пам'яті над записами одного товару на складі (рядок product_stock уже заблоковано).
2// Порядок R-02.7: A — цілі спайки; B — цілі пакування від більшого; C — розсип; D — розкрити найменше пакування /
3// розрізати спайку. Строгий FEFO: ітерація бачить лише найближчий строк.
4// Постійний розсип (R-05): розкриття й розрізання доливають у запис розсипу з тією самою адресою і строком.
5// Зміни повертаються приростами (delta), щоб паралельне приймання розсипу не губилося.
6import { PackType, Status, TxType } from './models.ts';
7
8export interface AllocRow {
9 id: number; // > 0 — існуючий запис; < 0 — новий (тимчасовий id)
10 productId: number;
11 isContainer: boolean;
12 packType: number;
13 packSize: number;
14 packCount: number;
15 quantity: number;
16 containedInId: number | null;
17 locationId: number;
18 expiryDate: string | null;
19 mfgDate: string | null;
20 receivedAt: string;
21 serial: boolean;
22 // стан до відбору — для приростів
23 origCount: number;
24 origQuantity: number;
25 // результат
26 freed?: boolean; // знято вкладеність (розрізали спайку)
27 archived?: { status: number; final: number };
28 isNew?: boolean;
29 sourceId?: number | null;
30}
31
32export interface AllocJournal { type: number; productId: number; itemId: number; delta: number; relatedId: number | null }
33
34export interface AllocResult {
35 rows: Set<AllocRow>; // змінені / нові / в архів
36 journal: AllocJournal[];
37 stockDelta: Map<number, number>;
38 issuedByProduct: Map<number, { qty: number; mfgDate: string | null; expiryDate: string | null }>;
39 issued: number;
40 short: number;
41 openedPacks: number;
42 cutContainers: number;
43}
44
45export const newAllocResult = (): AllocResult => ({
46 rows: new Set(), journal: [], stockDelta: new Map(), issuedByProduct: new Map(), issued: 0, short: 0, openedPacks: 0, cutContainers: 0,
47});
48
49let tempSeq = -1;
50const DAY = 86_400_000;
51const exp = (r: AllocRow) => (r.expiryDate ? Date.parse(r.expiryDate) / DAY : Infinity);
52const fefo = (a: AllocRow, b: AllocRow) => exp(a) - exp(b) || Date.parse(a.receivedAt) - Date.parse(b.receivedAt) || a.id - b.id;
53export const isPersistentLoose = (r: AllocRow) => r.packType === PackType.unit && !r.isContainer && r.containedInId == null && !r.serial;
54
55export function allocate(rows: AllocRow[], productId: number, qty: number, out: AllocResult, issueType: number = TxType.ISSUE): void {
56 let remaining = qty;
57 const live = () => rows.filter((r) => !r.archived);
58 const log = (type: number, it: AllocRow, delta: number, relatedId: number | null = null) => {
59 out.journal.push({ type, productId, itemId: it.id, delta, relatedId });
60 if (delta) out.stockDelta.set(productId, (out.stockDelta.get(productId) ?? 0) + delta);
61 };
62 const noteIssued = (it: AllocRow, q: number) => {
63 const cur = out.issuedByProduct.get(productId) ?? { qty: 0, mfgDate: it.mfgDate, expiryDate: it.expiryDate };
64 cur.qty += q;
65 out.issuedByProduct.set(productId, cur);
66 };
67 const archive = (r: AllocRow, status: number, final: number) => { r.archived = { status, final }; out.rows.add(r); };
68 // Постійний розсип для адреси й строку: наявний або новий (з кількістю 0).
69 const looseFor = (locationId: number, expiryDate: string | null, mfgDate: string | null, receivedAt: string, sourceId: number): AllocRow => {
70 let l = rows.find((r) => !r.archived && isPersistentLoose(r) && r.locationId === locationId && r.expiryDate === expiryDate);
71 if (!l) {
72 l = { id: tempSeq--, productId, isContainer: false, packType: PackType.unit, packSize: 1, packCount: 0, quantity: 0, containedInId: null,
73 locationId, expiryDate, mfgDate, receivedAt, serial: false, origCount: 0, origQuantity: 0, isNew: true, sourceId };
74 rows.push(l);
75 }
76 out.rows.add(l);
77 return l;
78 };
79 const take = (it: AllocRow, units: number, type: number) => {
80 // забрати units одиниць: для пакувань — цілими пакуваннями, для розсипу — штуками
81 const packs = units / it.packSize;
82 log(type, it, -units);
83 it.packCount -= packs;
84 it.quantity -= units;
85 out.rows.add(it);
86 // група пакувань, що закінчилась, — в архів; постійний розсип лишається навіть з нулем
87 if (it.quantity === 0 && !isPersistentLoose(it)) archive(it, type === TxType.OPEN ? Status.OPENED : Status.ISSUED, units);
88 };
89
90 for (let guard = 0; remaining > 0 && guard < 1000; guard++) {
91 const all = live();
92 const conts0 = all.filter((r) => r.isContainer);
93 const leaves0 = all.filter((r) => !r.isContainer && r.containedInId == null && r.quantity > 0);
94 let min = Infinity;
95 for (const r of [...conts0, ...leaves0]) if (exp(r) < min) min = exp(r);
96 const tier = (l: AllocRow[]) => l.filter((r) => exp(r) <= min).sort(fefo);
97 let progressed = false;
98
99 // A — ціла спайка, що вміщується в рядок
100 for (const c of tier(conts0).sort((a, b) => b.quantity - a.quantity)) {
101 if (c.quantity > remaining) continue;
102 log(issueType, c, 0);
103 for (const k of all.filter((r) => r.containedInId === c.id)) {
104 log(issueType, k, -k.quantity, c.id);
105 noteIssued(k, k.quantity);
106 const q = k.quantity;
107 k.quantity = 0;
108 k.packCount = 0;
109 archive(k, Status.ISSUED, q);
110 }
111 noteIssued(c, 0);
112 archive(c, Status.ISSUED, c.quantity);
113 remaining -= c.quantity;
114 progressed = true;
115 if (remaining === 0) break;
116 }
117 if (remaining === 0) break;
118 if (progressed) continue;
119
120 // B — цілі пакування, від більшого
121 const leaves = tier(leaves0);
122 for (const it of leaves.filter((l) => l.packType !== PackType.unit).sort((a, b) => b.packSize - a.packSize || fefo(a, b))) {
123 if (it.packSize > remaining) continue;
124 const n = Math.min(it.packCount, Math.floor(remaining / it.packSize));
125 take(it, n * it.packSize, issueType);
126 noteIssued(it, n * it.packSize);
127 remaining -= n * it.packSize;
128 progressed = true;
129 if (remaining === 0) break;
130 }
131 // C — розсип
132 for (const it of leaves) {
133 if (remaining === 0) break;
134 if (it.packType !== PackType.unit || it.quantity === 0 || it.archived) continue;
135 const n = Math.min(it.quantity, remaining);
136 take(it, n, issueType);
137 noteIssued(it, n);
138 remaining -= n;
139 progressed = true;
140 }
141 if (remaining === 0) break;
142
143 // D — розкрити найменше пакування (вміст — у постійний розсип тієї ж адреси й строку)
144 const closed = leaves.filter((l) => l.packType !== PackType.unit && !l.archived && l.packCount > 0).sort((a, b) => a.packSize - b.packSize || fefo(a, b));
145 if (closed.length) {
146 const it = closed[0];
147 const loose = looseFor(it.locationId, it.expiryDate, it.mfgDate, it.receivedAt, it.id);
148 take(it, it.packSize, TxType.OPEN);
149 loose.quantity += it.packSize;
150 loose.packCount += it.packSize;
151 log(TxType.OPEN, loose, it.packSize, it.id);
152 out.openedPacks++;
153 continue;
154 }
155 // D — розрізати спайку: вкладені пакування стають вільними, вкладений розсип доливається в постійний
156 const cs = tier(conts0).filter((c) => !c.archived).sort((a, b) => a.quantity - b.quantity || fefo(a, b));
157 if (cs.length) {
158 const c = cs[0];
159 log(TxType.OPEN, c, 0);
160 for (const k of all.filter((r) => r.containedInId === c.id)) {
161 if (k.packType === PackType.unit && !k.serial) {
162 const loose = looseFor(k.locationId, k.expiryDate, k.mfgDate, k.receivedAt, k.id);
163 log(TxType.OPEN, k, -k.quantity, c.id);
164 log(TxType.OPEN, loose, k.quantity, k.id);
165 loose.quantity += k.quantity;
166 loose.packCount += k.quantity;
167 const q = k.quantity;
168 k.quantity = 0;
169 k.packCount = 0;
170 archive(k, Status.OPENED, q);
171 } else {
172 k.containedInId = null;
173 k.freed = true;
174 out.rows.add(k);
175 }
176 }
177 archive(c, Status.OPENED, c.quantity);
178 out.cutContainers++;
179 continue;
180 }
181 if (progressed) continue;
182 break;
183 }
184 out.issued += qty - remaining;
185 out.short += remaining;
186}
187