wms.ts
TypeScript · 576 рядків
1// ЕМУЛЯТОР WMS СКЛАДУ для приймання (R-31). Усе в цьому файлі — те, що має бути у WMS складу, але ще немає
2// (або є на старій моделі в заглушках). Кожен виклик пише прогалину в gaps.ts.
3//
4// Роль WMS за R-23.6 / TSD-04: зберігає ВЕСЬ стан (прихід, місця, тара, план, залишки, задачі) і виконує команди;
5// НІЧОГО НЕ ВИРІШУЄ — куди класти, коли створити задачу, що показати на ТСД вирішує процес WorkFlow (борд board.ts).
6// Тому відповіді тут — факти й розрахунки (план, рекомендації полиць, заповненість), а не екрани.
7// Простір — справжня Topology (topology.ts): WMS передає їй стан адрес і отримує напрямки, маршрути, полиці.
8//
9// Спрощення, яких у справжній WMS не має бути (їх видно в реєстрі прогалин):
10// - стан у пам'яті процесу, без бази й без транзакції на прохід WorkFlow (W2, TSD-04);
11// - задачі живуть у flow-old, а не у WMS (W1, R-23.6);
12// - ідемпотентність — кеш відповіді за Idempotency-Key, без збереження.
13import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
14import type { Arrival, Card, OpenOrder } from './erp.ts'
15import { gap } from './gaps.ts'
16import * as topo from './topology.ts'
17import { barcodeOf, unitOf } from './world.ts'
18
19type Json = any
20
21export interface Container {
22 code: string
23 kind: 'box' | 'basket' | 'crossdock'
24 /** Напрямок: ключ «поверх» або «поверх·зона»; для крос-доку — пакування. */
25 direction: string
26 label: string
27 status: 'bound' | 'closed' | 'moving' | 'delivered' | 'empty'
28 contents: Map<number, number>
29 weightKg: number
30 volumeM3: number
31 location: string
32 orders: Map<number, number>
33}
34
35interface Direction { key: string; label: string; floorId: string; zoneId: string | null; intakeId: string; intake: string; mode: string; minutes: number; basketTarget: string; basketConveyor: string; byConveyor: boolean; volumeM3: number; weightKg: number; boxes: number }
36
37/** Межі тари — з Topology (короб і кошик рівня складу, R-26 T4), заповнення короба до 85% об'єму. */
38const FILL = 0.85
39
40export class WmsEmulator {
41 arrival!: Arrival & { status: string; places: string[]; expectedPlaces: number | null }
42 cards = new Map<number, Card>()
43 barcodes = new Map<string, number>()
44 measured = new Set<number>()
45 places = new Map<string, { code: string; status: 'gate' | 'waiting' | 'sorting' | 'empty'; slot: string; contents: Map<number, number> }>()
46 containers = new Map<string, Container>()
47 directions = new Map<string, Direction>()
48 /** Тара на станції: напрямок → поточний код (ліміт місць станції). */
49 station = new Map<string, string>()
50 stationCode = ''
51 pending: { direction: string; kind: Container['kind']; label: string }[] = []
52 /** Залишок на адресах: адреса → товар → к-сть; і вага / об'єм для Topology. */
53 stock = new Map<string, Map<number, number>>()
54 addrLoad = new Map<string, { weight: number; volume: number }>()
55 reserves = new Map<string, number>()
56 orders: (OpenOrder & { left: number })[] = []
57 sorted = new Map<number, number>()
58 placed = new Map<number, number>()
59 crossdocked = new Map<number, number>()
60 outbox: { type: string; data: Json; at: string }[] = []
61 log: string[] = []
62 private idem = new Map<string, Json>()
63 private server: Server | null = null
64 private waitingCount = 0
65 private free: { boxes: string[]; baskets: string[]; crossdock: string[] }
66
67 private world: { measure: (itemId: number) => { lengthM: number; widthM: number; heightM: number; weightKg: number } }
68
69 constructor(free: { boxes: string[]; baskets: string[]; crossdock: string[] }, world: { measure: (itemId: number) => { lengthM: number; widthM: number; heightM: number; weightKg: number } }) {
70 this.free = { boxes: [...free.boxes], baskets: [...free.baskets], crossdock: [...free.crossdock] }
71 this.world = world
72 }
73
74 // ───────────────────────── документ ERP (фаза 1) ─────────────────────────
75
76 /** Прихід дійшов до складу (R-29 1.15): зберегти «очікується», картки — з майстра. */
77 receiveDocument(arrival: Arrival, cards: Map<number, Card>, orders: OpenOrder[]) {
78 this.arrival = { ...arrival, status: 'expected', places: [], expectedPlaces: null }
79 this.cards = new Map([...cards].map(([k, v]) => [k, { ...v }]))
80 this.orders = orders.map((o) => ({ ...o, left: o.qty }))
81 this.fact('DOCUMENT_ACCEPTED', { messageId: arrival.messageId })
82 gap('1.15', 'simplified', 'WMS складу', 'Прихід «очікується» в базі складу (рядки, картки)', 'прихід у пам\'яті емулятора', 'R-29 1.15')
83 gap('1.16', 'missing', 'WMS складу → WorkFlow', 'Подія DOCUMENT_RECEIVED запускає процес «Прихід ERP» (без задач, R-26)', 'прогін сам знає, що прихід є; задач не створює', 'R-29 1.16–1.18')
84 }
85
86 // ───────────────────────── HTTP для блоків API_REQUEST борду ─────────────────────────
87
88 async listen(port = 0): Promise<string> {
89 this.server = createServer((req, res) => this.handle(req, res))
90 await new Promise<void>((resolve) => this.server!.listen(port, '127.0.0.1', resolve))
91 const address = this.server.address() as { port: number }
92 return `http://127.0.0.1:${address.port}`
93 }
94
95 async close() {
96 await new Promise<void>((resolve) => this.server?.close(() => resolve()))
97 }
98
99 private async handle(req: IncomingMessage, res: ServerResponse) {
100 const chunks: Buffer[] = []
101 for await (const chunk of req) chunks.push(chunk as Buffer)
102 const body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}
103 const key = String(req.headers['idempotency-key'] || '')
104 const send = (status: number, value: Json) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(value)) }
105 if (key && this.idem.has(key)) return send(200, this.idem.get(key))
106 try {
107 const url = new URL(req.url || '/', 'http://wms')
108 const result = this.route(req.method || 'GET', url.pathname, body)
109 if (key) this.idem.set(key, result)
110 send(200, result)
111 } catch (error: any) {
112 this.log.push(`ERROR ${req.method} ${req.url}: ${error.message}`)
113 send(error.status || 409, { error: error.message })
114 }
115 }
116
117 route(method: string, path: string, b: Json): Json {
118 const code = path.match(/^\/wms\/codes\/(.+)$/)
119 if (method === 'GET' && code) return this.recognize(decodeURIComponent(code[1]))
120 switch (`${method} ${path}`) {
121 case 'POST /wms/codes/bind': return this.bindBarcode(b.code, Number(b.itemId))
122 case 'POST /wms/arrivals/arrive': return this.arrive(String(b.docNum))
123 case 'POST /wms/places': return this.newPlace(String(b.placeType || 'pallet'))
124 case 'POST /wms/places/park': return this.park(b.place, b.slot)
125 case 'POST /wms/arrivals/unloaded': return this.unloaded()
126 case 'POST /wms/sorting/start': return this.startSorting(b.station)
127 case 'POST /wms/sorting/bind': return this.bindContainer(b.code)
128 case 'POST /wms/sorting/open-place': return this.openPlace(b.place)
129 case 'POST /wms/sorting/item': return this.sortItem(Number(b.itemId))
130 case 'POST /wms/sorting/put': return this.put(b.place, Number(b.itemId), Number(b.qty), b.container)
131 case 'POST /wms/sorting/swap': return this.swap(b.closed, b.code)
132 case 'POST /wms/sorting/place-empty': return this.placeEmpty(b.place)
133 case 'POST /wms/sorting/close': return this.closeSorting()
134 case 'POST /wms/containers/route': return this.containerRoute(b.code)
135 case 'POST /wms/containers/deliver': return this.deliver(b.code, b.at)
136 case 'POST /wms/putaway/open': return this.putawayOpen(b.code)
137 case 'POST /wms/putaway/suggest': return this.suggest(b.code, Number(b.itemId))
138 case 'POST /wms/putaway/place': return this.place(b.code, Number(b.itemId), Number(b.qty), b.address, b.planned)
139 }
140 throw Object.assign(new Error(`no route ${method} ${path}`), { status: 404 })
141 }
142
143 // ───────────────────────── розпізнавання коду (фаза 0, крок 0.5) ─────────────────────────
144
145 /** Довідник кодів WMS: що це за код (R-26.1). Штрихкоди товару спершу невідомі — ERP їх не дає (R-28). */
146 recognize(code: string) {
147 gap('0.5', 'simplified', 'WMS складу', 'Довідник кодів: товар / пакування / стікер місця / тара / адреса / станція', 'розпізнавання за префіксами й пам\'яттю емулятора', 'R-29 0.5, R-26.1')
148 const none = { kind: 'unknown', itemId: 0, name: '' }
149 if (this.barcodes.has(code)) {
150 const itemId = this.barcodes.get(code)!
151 return { kind: 'item', itemId, name: this.cards.get(itemId)?.name.slice(0, 60) ?? '' }
152 }
153 if (this.places.has(code)) return { ...none, kind: 'place' }
154 if (this.containers.has(code)) return { ...none, kind: this.containers.get(code)!.kind }
155 if (/^BX-/.test(code)) return { ...none, kind: 'box' }
156 if (/^KS-/.test(code)) return { ...none, kind: 'basket' }
157 if (/^XD-/.test(code)) return { ...none, kind: 'crossdock' }
158 if (code === this.stationCode || code === topo.directions().station.code) return { ...none, kind: 'station' }
159 if (code.startsWith(`${topo.waitingZone().code}-`)) return { ...none, kind: 'waiting' }
160 if (topo.addressInfo(code)) return { ...none, kind: 'address' }
161 if (/^Z-\d+$/.test(code)) return { ...none, kind: 'zone' }
162 return none
163 }
164
165 /** Невідомий штрихкод → товар з рядків приходу (R-29 5.5–5.7). Прив'язка лишається в довіднику кодів. */
166 bindBarcode(code: string, itemId: number) {
167 if (!this.arrival.lines.some((l) => l.itemId === itemId)) throw new Error(`item ${itemId} is not in the arrival`)
168 this.barcodes.set(code, itemId)
169 gap('5.7', 'missing', 'WMS складу', 'Прив\'язка невідомого штрихкоду до товару з рядків приходу (+ у картку майстра, на інші склади)', 'код прив\'язано в пам\'яті емулятора; майстру не передано', 'R-29 5.5–5.8')
170 return { name: this.cards.get(itemId)!.name.slice(0, 60) }
171 }
172
173 // ───────────────────────── фура й розвантаження (фази 2–3) ─────────────────────────
174
175 arrive(docNum: string) {
176 if (String(this.arrival.docNum) !== docNum) throw new Error(`no expected arrival №${docNum}`)
177 this.arrival.status = 'unloading'
178 gap('2.2', 'missing', 'WMS складу', 'Пошук приходу «очікується» за номером (у «Пр» немає постачальника)', 'прихід знайдено за номером документа', 'R-29 2.2')
179 gap('2.3', 'missing', 'WMS складу → Topology', 'Вільні ворота й місткість зони очікування', 'ворота не обираються; зона очікування — з плану Topology', 'R-29 2.3–2.4')
180 this.fact('TRUCK_ARRIVED', { messageId: this.arrival.messageId })
181 gap('2.6', 'missing', 'WMS складу → ERP', 'Факт «фура прибула / розвантаження почато» для ERP', 'факт лише в outbox емулятора', 'R-29 2.6, П20')
182 const units = this.arrival.lines.reduce((s, l) => s + l.qty, 0)
183 return { arrivalId: String(this.arrival.erpDocId), docNum, lines: this.arrival.lines.length, units }
184 }
185
186 newPlace(placeType: string) {
187 const n = this.arrival.places.length + 1
188 const code = `P-${this.arrival.docNum}-${String(n).padStart(2, '0')}`
189 const zone = topo.waitingZone()
190 const perLine = Math.ceil(zone.slots / zone.lines)
191 const line = Math.floor(this.waitingCount / perLine) + 1
192 const slot = `${zone.code}-${line}-${String((this.waitingCount % perLine) + 1).padStart(2, '0')}`
193 this.waitingCount += 1
194 this.places.set(code, { code, status: 'gate', slot, contents: new Map() })
195 this.arrival.places.push(code)
196 gap('3.7', 'simplified', 'WMS складу', `Місце приходу: код, № M, тип (${placeType}), вага й габарити за типом`, 'місце в пам\'яті; вага й габарити типу не задаються', 'R-29 3.6–3.7')
197 gap('3.8', 'missing', 'WorkFlow → шлюз → принтер', 'Друк стікера місця на портативний принтер і підтвердження друку', 'стікер «надруковано» без принтера; комірник клеїть код з екрана', 'R-29 3.8–3.11, П10')
198 gap('3.13', 'missing', 'WMS складу → Topology', 'Куди поставити місце в зоні очікування (лінія, позиція)', `емулятор роздає позиції по черзі: ${perLine} на лінію`, 'R-29 3.13–3.15, R-26 T2')
199 return { code, slot, count: n }
200 }
201
202 park(place: string, slot: string) {
203 const p = this.places.get(place)
204 if (!p) throw new Error(`no place ${place}`)
205 if (slot !== p.slot) return { ok: false, count: this.arrival.places.length, expected: p.slot }
206 p.status = 'waiting'
207 this.move(`місце ${place}`, 'ворота', slot)
208 return { ok: true, count: this.arrival.places.filter((c) => this.places.get(c)!.status !== 'gate').length, expected: p.slot }
209 }
210
211 unloaded() {
212 this.arrival.expectedPlaces = this.arrival.places.length
213 this.arrival.status = 'waiting-sorting'
214 this.fact('PLACES_COUNTED', { places: this.arrival.places.length })
215 gap('3.20', 'missing', 'WMS складу → ERP', 'Факт PLACES_COUNTED і звірка «M місць із N» (ERP кількості місць не дає)', 'кількість місць записано без звірки', 'R-29 3.19–3.20, R-28')
216 return { places: this.arrival.places.length }
217 }
218
219 // ───────────────────────── розкладка: старт і план тари (фаза 4) ─────────────────────────
220
221 /**
222 * План розкладки (R-26.5–R-26.7): рядок → напрямок → обсяг і маса → набір тари в ліміті місць станції.
223 * Напрямок рядка — поверх і зона першої полиці, яку Topology пропонує для цього товару зі станції.
224 * Правила (TSD-06): крос-док першим; один короб — один поверх; не більше ліміту станції; малий обсяг зон поверху —
225 * один короб поверху. План незмінний (R-26.6): тут — лише стартовий набір тари.
226 */
227 startSorting(station: string) {
228 const d = topo.directions()
229 if (station !== d.station.code) throw new Error(`station ${station} is not a sorting station (${d.station.code})`)
230 this.stationCode = station
231 this.arrival.status = 'sorting'
232 gap('4.4', 'missing', 'WMS складу', 'Скан станції розкладки: на якій станції план (ліміт, маршрути)', 'станцію сканує комірник; WMS перевіряє код за Topology', 'R-29 4.4')
233 gap('4.11', 'missing', 'WMS складу (операція «план розкладки»)', 'План розкладки: напрямок рядка, обсяг і маса, баланс у ліміті станції, «ідеальна розкладка»', 'емулятор: напрямок — поверх × зона першої полиці Topology; короби — за об\'ємом і масою оцінки картки', 'R-29 4.11–4.12, R-26.5, П58')
234 const boxVolume = d.box.length * d.box.width * d.box.height * FILL
235 const byKey = new Map<string, Direction>()
236 for (const line of this.arrival.lines) {
237 const card = this.cards.get(line.itemId)!
238 const best = topo.candidates(card, line.qty, d.station.id, this.addressState())[0]
239 const info = best ? topo.addressInfo(best.address) : null
240 const floor = d.floors.find((f) => f.floorId === info?.floorId) ?? d.floors[0]
241 const zone = floor.zones.find((z) => z.zoneId === info?.zoneId)
242 const key = zone ? `${floor.floor}·${zone.zone}` : floor.floor
243 const target = zone?.box ?? floor.box!
244 const dir = byKey.get(key) ?? {
245 key, label: zone ? `${floor.floorName}, зона ${zone.zone}` : floor.floorName, floorId: floor.floorId, zoneId: zone?.zoneId ?? null,
246 intakeId: target.intakeId, intake: target.intake, mode: target.leg.mode, minutes: Math.round(target.leg.time / 6) / 10,
247 basketTarget: (zone?.basket ?? floor.basket)?.target ?? '', basketConveyor: (zone?.basket ?? floor.basket)?.conveyor ?? '',
248 byConveyor: (zone?.basket ?? floor.basket)?.byConveyor ?? false, volumeM3: 0, weightKg: 0, boxes: 0,
249 }
250 dir.volumeM3 += card.lengthM * card.widthM * card.heightM * line.qty
251 dir.weightKg += card.weightKg * line.qty
252 byKey.set(key, dir)
253 ;(line as Json).direction = key
254 }
255 for (const dir of byKey.values()) dir.boxes = Math.max(1, Math.ceil(dir.volumeM3 / boxVolume), Math.ceil(dir.weightKg / d.box.weight))
256 this.directions = byKey
257 const crossdock = this.orders.some((o) => this.arrival.lines.some((l) => l.itemId === o.itemId))
258 const slots = (d.station.slots ?? 5) - (crossdock ? 1 : 0)
259 if (byKey.size > slots) {
260 gap('4.11b', 'missing', 'WMS складу', 'Злиття напрямків у ліміті станції (малий обсяг зон — один короб поверху)', 'напрямків більше за ліміт — зайві чекають, поки звільниться місце на станції', 'TSD-06 правила 2–3')
261 }
262 // стартовий набір: крос-док коробка, по коробу на напрямок у межах ліміту, кошики — на вимогу (без ліміту, біля конвеєра)
263 this.pending = []
264 if (crossdock) this.pending.push({ direction: 'crossdock', kind: 'crossdock', label: `крос-док → ${d.crossdock?.packing ?? 'пакування'}` })
265 for (const dir of [...byKey.values()].slice(0, slots)) this.pending.push({ direction: dir.key, kind: 'box', label: `короб → ${dir.label} (${dir.intake})` })
266 const plan = [...byKey.values()].map((x) => `${x.label}: ${x.boxes} кор., ${Math.round(x.weightKg)} кг`).join('; ')
267 this.log.push(`ПЛАН ${plan}${crossdock ? '; крос-док коробка' : ''}`)
268 this.fact('SORTING_PLAN', { directions: [...byKey.values()].map((x) => ({ key: x.key, boxes: x.boxes, weightKg: Math.round(x.weightKg) })) })
269 const next = this.pending[0]
270 return { text: plan + (crossdock ? '; + крос-док коробка' : ''), toBind: this.pending.length, nextLabel: next?.label ?? '' }
271 }
272
273 /** Прив'язати порожній короб / кошик / крос-док коробку до напрямку плану (R-29 4.14–4.16). */
274 bindContainer(code: string) {
275 const next = this.pending[0]
276 if (!next) throw new Error('nothing to bind')
277 const kind = code.startsWith('XD-') ? 'crossdock' : code.startsWith('KS-') ? 'basket' : 'box'
278 if (kind !== next.kind) return { ok: false, left: this.pending.length, nextLabel: next.label, label: '' }
279 this.newContainer(code, kind, next.direction, next.label)
280 this.pending.shift()
281 gap('4.14', 'missing', 'WMS складу', 'Прив\'язка фізичного короба / кошика / крос-док коробки до напрямку плану', 'тару прив\'язано в пам\'яті емулятора', 'R-29 4.14–4.16, 5.23')
282 return { ok: true, left: this.pending.length, nextLabel: this.pending[0]?.label ?? '', label: next.label }
283 }
284
285 private newContainer(code: string, kind: Container['kind'], direction: string, label: string) {
286 this.containers.set(code, { code, kind, direction, label, status: 'bound', contents: new Map(), weightKg: 0, volumeM3: 0, location: this.stationCode, orders: new Map() })
287 this.station.set(`${kind}:${direction}`, code)
288 this.free.boxes = this.free.boxes.filter((c) => c !== code)
289 this.free.baskets = this.free.baskets.filter((c) => c !== code)
290 this.free.crossdock = this.free.crossdock.filter((c) => c !== code)
291 }
292
293 // ───────────────────────── розкладка: деталь → тара (фаза 5) ─────────────────────────
294
295 openPlace(place: string) {
296 const p = this.places.get(place)
297 if (!p || p.status === 'gate') throw new Error(`place ${place} is not in the waiting zone`)
298 p.status = 'sorting'
299 this.move(`місце ${place}`, p.slot, this.stationCode)
300 return { ok: true }
301 }
302
303 /**
304 * Факти для правила «куди» (таблиця рішень у WorkFlow): чи є в приході, крос-док (замовлення, збір не почався),
305 * цінний товар, чи влазить у кошик, яка тара напрямку стоїть на станції. Першим сканом — замір (софт заміру).
306 */
307 sortItem(itemId: number) {
308 const card = this.cards.get(itemId)
309 const line = this.arrival.lines.find((l) => l.itemId === itemId) as Json
310 if (!card || !line) return { name: '', inArrival: false, left: 0, crossdockQty: 0, crossdockCode: '', expensive: false, fitsBasket: false, basketCode: '', boxCode: '', boxLabel: '', basketLabel: '' }
311 if (!this.measured.has(itemId)) {
312 Object.assign(card, this.world.measure(itemId), { source: 'measured' })
313 this.measured.add(itemId)
314 gap('5.17', 'missing', 'обладнання → WMS складу', 'Замір габаритів і ваги (софт заміру) → картка measured → майстер', '«замір» бере справжні розміри зі світу при першому скані', 'R-29 5.17–5.19, R-28.10')
315 }
316 const d = topo.directions()
317 const crossdockQty = this.orders.filter((o) => o.itemId === itemId).reduce((s, o) => s + o.left, 0)
318 gap('5.12', 'no-data', 'ERP → майстер → WMS', 'Цінність товару (ціна) — «дорогий товар у допоміжний кошик»', 'ERP ціни не дає; цінні — за списком у прогоні (REPAIR&RENEW, MOTIP)', 'запит користувача 23.11')
319 const expensive = /REPAIR&RENEW|MOTIP/i.test(card.name)
320 const fitsBasket = card.lengthM <= d.basket.length && card.widthM <= d.basket.width && card.heightM <= d.basket.height && card.weightKg <= d.basket.weight
321 const dir = this.directions.get(line.direction)
322 let boxCode = this.station.get(`box:${line.direction}`) ?? ''
323 if (!boxCode) {
324 // напрямок без короба на станції (ліміт) — короб напрямку чекає місця; кладемо в короб того самого поверху
325 const sameFloor = [...this.directions.values()].find((x) => x.floorId === dir?.floorId && this.station.get(`box:${x.key}`))
326 boxCode = sameFloor ? this.station.get(`box:${sameFloor.key}`)! : [...this.station.entries()].find(([k]) => k.startsWith('box:'))![1]
327 gap('4.11c', 'missing', 'WMS складу', 'Напрямок без короба на станції: чекати місця чи класти в короб поверху', 'кладемо в короб того самого поверху (або будь-який)', 'TSD-06 правило 2')
328 }
329 const basketKey = `basket:${dir?.floorId ?? ''}`
330 let basketCode = this.station.get(basketKey) ?? ''
331 if (!basketCode) basketCode = this.free.baskets[0]
332 return {
333 name: card.name.slice(0, 60), inArrival: true, left: line.qty - (this.sorted.get(itemId) ?? 0),
334 crossdockQty, crossdockCode: this.station.get('crossdock:crossdock') ?? '',
335 expensive, fitsBasket, basketCode, basketLabel: `кошик → ${dir?.label ?? ''} (${dir?.basketConveyor || 'вручну'})`,
336 boxCode, boxLabel: this.containers.get(boxCode)?.label ?? '',
337 }
338 }
339
340 /**
341 * Покласти n шт товару з місця в тару. Тара — та, що назвав процес. Кошик ще не прив'язаний (беруть біля конвеєра) —
342 * прив'язується тут. Крос-док: у коробку йде не більше, ніж треба замовленням; решту процес кладе далі (restQty).
343 * Не влазить — тару закрито («короб повний»), відповідь full + наступна тара; товар лишається в руках.
344 */
345 put(place: string, itemId: number, qty: number, container: string) {
346 const p = this.places.get(place)
347 const card = this.cards.get(itemId)!
348 if (!p) throw new Error(`no place ${place}`)
349 let c = this.containers.get(container)
350 if (!c && container.startsWith('KS-')) {
351 const line = this.arrival.lines.find((l) => l.itemId === itemId) as Json
352 const dir = this.directions.get(line.direction)!
353 this.newContainer(container, 'basket', `basket:${dir.floorId}`, `кошик → ${dir.label}`)
354 this.station.set(`basket:${dir.floorId}`, container)
355 c = this.containers.get(container)!
356 ;(c as Json).floorId = dir.floorId
357 gap('4.16', 'missing', 'WMS складу', 'Кошик біля конвеєра: прив\'язка до напрямку при першому покладанні', 'кошик прив\'язано при першому покладанні', 'R-29 4.16, 5.24')
358 }
359 if (!c || c.status !== 'bound') throw new Error(`container ${container} is not open at the station`)
360 let n = qty
361 let restQty = 0
362 if (c.kind === 'crossdock') {
363 const need = this.orders.filter((o) => o.itemId === itemId).reduce((s, o) => s + o.left, 0)
364 n = Math.min(qty, need)
365 restQty = qty - n
366 }
367 const d = topo.directions()
368 const limit = c.kind === 'basket' ? d.basket : d.box
369 const capacityM3 = limit.length * limit.width * limit.height * FILL
370 const addW = card.weightKg * n
371 const addV = card.lengthM * card.widthM * card.heightM * n
372 if (c.contents.size && (c.weightKg + addW > limit.weight || c.volumeM3 + addV > capacityM3)) {
373 c.status = 'closed'
374 const kind = c.kind
375 const next = kind === 'basket' ? this.free.baskets[0] : kind === 'crossdock' ? this.free.crossdock[0] : this.free.boxes[0]
376 gap('5.20', 'simplified', 'WMS складу', '«Короб повний»: заповненість тари за об\'ємом і масою (зараз — оцінка картки)', 'короб закривається, коли наступне пакування не влазить', 'R-29 5.20–5.23, TSD-06 правило 8')
377 return { full: true, closed: c.code, closedKind: kind, next, nextLabel: c.label, putQty: 0, restQty: qty, restContainer: '', left: 0 }
378 }
379 if (c.weightKg + addW > limit.weight) gap('5.20b', 'missing', 'WMS складу / WorkFlow', 'Одне пакування важче за межу тари', 'покладено понад межу — правило «розділи пакування» потрібне', 'TSD-06 правило 4')
380 c.contents.set(itemId, (c.contents.get(itemId) ?? 0) + n)
381 c.weightKg += addW
382 c.volumeM3 += addV
383 p.contents.set(itemId, (p.contents.get(itemId) ?? 0) - n)
384 this.sorted.set(itemId, (this.sorted.get(itemId) ?? 0) + n)
385 if (c.kind === 'crossdock') {
386 let left = n
387 for (const o of this.orders.filter((x) => x.itemId === itemId)) {
388 const take = Math.min(left, o.left)
389 o.left -= take
390 left -= take
391 if (take) c.orders.set(o.orderId, (c.orders.get(o.orderId) ?? 0) + take)
392 }
393 this.crossdocked.set(itemId, (this.crossdocked.get(itemId) ?? 0) + n)
394 gap('5.12x', 'missing', 'WMS складу', 'Резерв замовлення закривається з кошика крос-доку, резерв полиці знімається', 'замовлення в пам\'яті емулятора зменшено', 'R-30.9, R-30.16')
395 }
396 this.move(`${n} × ${itemId}`, place, c.code)
397 gap('5.15', 'simplified', 'WMS складу', 'Рух «місце → тара» в обліку (пакування, кількість), задача на пакування рівно раз', 'рух у журналі емулятора; задач на пакування немає — викладка йде по вмісту тари', 'R-29 5.10, 5.15')
398 let restContainer = ''
399 if (restQty) {
400 const line = this.arrival.lines.find((l) => l.itemId === itemId) as Json
401 restContainer = this.station.get(`box:${line.direction}`) ?? [...this.station.entries()].find(([k]) => k.startsWith('box:'))![1]
402 const rest = this.containers.get(restContainer)!
403 rest.contents.set(itemId, (rest.contents.get(itemId) ?? 0) + restQty)
404 rest.weightKg += card.weightKg * restQty
405 rest.volumeM3 += card.lengthM * card.widthM * card.heightM * restQty
406 p.contents.set(itemId, (p.contents.get(itemId) ?? 0) - restQty)
407 this.sorted.set(itemId, (this.sorted.get(itemId) ?? 0) + restQty)
408 this.move(`${restQty} × ${itemId}`, place, restContainer)
409 gap('5.16x', 'simplified', 'WorkFlow', 'Частковий крос-док: решта пакування — у короб напрямку з окремим підтвердженням сканом', 'решту записано в короб напрямку без скану', 'R-30.16')
410 }
411 const left = this.arrival.lines.reduce((s, l) => s + l.qty, 0) - [...this.sorted.values()].reduce((s, x) => s + x, 0)
412 return { full: false, closed: '', closedKind: '', next: '', nextLabel: '', putQty: n, restQty, restContainer, left }
413 }
414
415 /** Поставити нову тару на місце закритої (R-29 5.23): новий код, той самий напрямок. */
416 swap(closed: string, code: string) {
417 const old = this.containers.get(closed)
418 if (!old) throw new Error(`no container ${closed}`)
419 this.newContainer(code, old.kind, old.direction, old.label)
420 if (old.kind === 'basket') this.station.set(old.direction, code)
421 return { ok: true, label: old.label }
422 }
423
424 placeEmpty(place: string) {
425 const p = this.places.get(place)!
426 p.status = 'empty'
427 const leftInPlace = [...p.contents.values()].reduce((s, x) => s + x, 0)
428 const placesLeft = this.arrival.places.filter((c) => this.places.get(c)!.status !== 'empty').length
429 return { placesLeft, leftInPlace }
430 }
431
432 /** Усі місця порожні → закрити тару на станції, звірити рядки (R-29 6.1–6.4). */
433 closeSorting() {
434 const toDeliver: { code: string; kind: string }[] = []
435 for (const c of this.containers.values()) {
436 if (c.status === 'bound' && c.contents.size) { c.status = 'closed'; toDeliver.push({ code: c.code, kind: c.kind }) }
437 else if (c.status === 'bound') c.status = 'empty'
438 }
439 const diffs = this.arrival.lines.filter((l) => (this.sorted.get(l.itemId) ?? 0) !== l.qty)
440 this.arrival.status = 'sorted'
441 this.fact('DOCUMENT_DONE', { lines: this.arrival.lines.map((l) => ({ itemId: l.itemId, expected: l.qty, actual: this.sorted.get(l.itemId) ?? 0 })) })
442 gap('6.2', 'simplified', 'WMS складу', 'Звірка рядків «факт ↔ ERP», розбіжність → інвентаризація полиць, факт DOCUMENT_DONE', `звірено в емуляторі: розбіжностей ${diffs.length}; задач інвентаризації не створено`, 'R-29 6.1–6.6')
443 return { containers: toDeliver, discrepancies: diffs.length, text: `тари до доставки: ${toDeliver.length}, розбіжностей: ${diffs.length}` }
444 }
445
446 // ───────────────────────── доставка тари (фаза 7) ─────────────────────────
447
448 containerRoute(code: string) {
449 const c = this.containers.get(code)
450 if (!c) throw new Error(`no container ${code}`)
451 const d = topo.directions()
452 if (c.kind === 'crossdock') {
453 return { kind: c.kind, target: d.crossdock!.packing, targetName: 'пакування', mode: d.crossdock!.leg.mode, minutes: Math.round(d.crossdock!.leg.time / 6) / 10, via: d.crossdock!.leg.via.join(' → ') || '—' }
454 }
455 if (c.kind === 'basket') {
456 const dir = [...this.directions.values()].find((x) => x.floorId === (c as Json).floorId)!
457 return { kind: c.kind, target: dir.basketTarget, targetName: `кінець конвеєра ${dir.basketConveyor}`, mode: dir.byConveyor ? 'conveyor' : 'hand', minutes: 0, via: dir.basketConveyor }
458 }
459 const dir = this.directions.get(c.direction)!
460 gap('7.2', 'simplified', 'WMS складу → Topology', 'Маршрут вилочного / рокли до місця прийому зони (route/options)', 'маршрут узято з напрямків станції (Topology), без варіантів засобів', 'R-29 7.2–7.4')
461 return { kind: c.kind, target: dir.intake, targetName: `місце прийому ${dir.label}`, mode: dir.mode, minutes: dir.minutes, via: dir.intake }
462 }
463
464 deliver(code: string, at: string) {
465 const c = this.containers.get(code)!
466 const route = this.containerRoute(code)
467 if (at !== route.target) return { ok: false, kind: c.kind, expected: route.target }
468 c.status = 'delivered'
469 this.move(`тара ${code}`, c.location, at)
470 c.location = at
471 if (c.kind === 'crossdock') {
472 gap('5.28', 'missing', 'WorkFlow', 'Крос-док коробка на пакуванні → процес замовлення (збір / пакування)', 'прогін закінчується на «передано на пакування»', 'R-29 5.28, R-30.9')
473 }
474 return { ok: true, kind: c.kind, expected: route.target }
475 }
476
477 // ───────────────────────── викладка (фази 8–9) ─────────────────────────
478
479 putawayOpen(code: string) {
480 const c = this.containers.get(code)!
481 const units = [...c.contents.values()].reduce((s, x) => s + x, 0)
482 return { lines: c.contents.size, units }
483 }
484
485 /**
486 * Полиця для товару з тари (R-22, WMS-07): кандидати — Topology від точки, де стоїть тара; фільтр WMS —
487 * адреси того самого напрямку (поверх × зона тари), спершу адреси цього товару, далі — найближчі.
488 */
489 suggest(code: string, itemId: number) {
490 const c = this.containers.get(code)!
491 const qty = c.contents.get(itemId) ?? 0
492 const card = this.cards.get(itemId)!
493 if (!qty) return { inContainer: false, qty: 0, address: '', alt: '', fits: false, name: card?.name.slice(0, 60) ?? '' }
494 const from = c.kind === 'basket' ? topo.warehouse.items.find((i: Json) => topo.codeOf(i.id) === c.location)?.id ?? c.location : topo.warehouse.items.find((i: Json) => topo.codeOf(i.id) === c.location)?.id ?? c.location
495 const dir = c.kind === 'box' ? this.directions.get(c.direction) : [...this.directions.values()].find((x) => x.floorId === (c as Json).floorId)
496 const all = topo.candidates(card, qty, from, this.addressState(itemId))
497 const same = all.filter((x) => {
498 const info = topo.addressInfo(x.address)
499 return info && info.floorId === dir?.floorId && (c.kind !== 'box' || !dir?.zoneId || info.zoneId === dir.zoneId)
500 })
501 // заповненість після покладання (R-22): більша з часток за вагою полиці й об'ємом комірки
502 const fill = (x: Json) => Math.max(x.load.limit ? x.load.after / x.load.limit : 0, x.volume.limit ? x.volume.after / x.volume.limit : 0)
503 const pool = (same.length ? same : all).filter((x) => fill(x) <= 0.98 && (!this.reserves.has(x.address) || x.sameSku > 0))
504 // порядок WMS: адреса, де цей товар уже лежить → вільні до 0,7 → 0,7–0,98; усередині — порядок Topology
505 const rank = (x: Json) => (x.sameSku > 0 ? 0 : fill(x) < 0.7 ? 1 : 2)
506 const ranked = pool.map((x, i) => ({ x, i })).sort((a, b) => rank(a.x) - rank(b.x) || a.i - b.i).map((r) => r.x)
507 gap('8.8', 'simplified', 'WMS складу', 'Фільтр полиць WMS: свої адреси товару, потім бренду; заповненість 0,7 / 0,98; вага; резерви задач', 'адреси цього товару → заповненість < 0,7 → до 0,98, у межах напрямку тари; бренду й «одна пробна полиця 0,7–0,98» немає', 'R-29 8.5–8.10, R-22')
508 if (!same.length) gap('8.8b', 'missing', 'WMS складу', 'У зоні тари немає місця — куди везти (інша зона, підлога / стіна)', 'взято полицю поза зоною тари', 'R-22.27, R-29 9.5')
509 const best = ranked[0]
510 if (!best) {
511 gap('9.5', 'missing', 'WMS складу → Topology', 'Немає допустимої полиці: місце поза схемою (підлога / стіна біля стелажа)', 'товар лишився в тарі', 'R-29 9.5')
512 return { inContainer: true, qty, address: '', alt: '', fits: false, name: card.name.slice(0, 60) }
513 }
514 this.reserves.set(best.address, (this.reserves.get(best.address) ?? 0) + qty)
515 return { inContainer: true, qty, address: best.address, alt: ranked[1]?.address ?? '', fits: best.fits, name: card.name.slice(0, 60) }
516 }
517
518 place(code: string, itemId: number, qty: number, address: string, planned: string) {
519 const c = this.containers.get(code)!
520 const card = this.cards.get(itemId)!
521 if (!topo.addressInfo(address)) throw new Error(`unknown address ${address}`)
522 const have = c.contents.get(itemId) ?? 0
523 const n = Math.min(qty, have)
524 c.contents.set(itemId, have - n)
525 if (!c.contents.get(itemId)) c.contents.delete(itemId)
526 const shelf = this.stock.get(address) ?? new Map<number, number>()
527 shelf.set(itemId, (shelf.get(itemId) ?? 0) + n)
528 this.stock.set(address, shelf)
529 const load = this.addrLoad.get(address) ?? { weight: 0, volume: 0 }
530 load.weight += card.weightKg * n
531 load.volume += card.lengthM * card.widthM * card.heightM * n
532 this.addrLoad.set(address, load)
533 this.reserves.delete(planned)
534 this.placed.set(itemId, (this.placed.get(itemId) ?? 0) + n)
535 this.move(`${n} × ${itemId}`, code, address)
536 this.fact('STOCK_CHANGED', { itemId, address, qty: n })
537 const line = this.arrival.lines.find((l) => l.itemId === itemId)!
538 if ((this.placed.get(itemId) ?? 0) + (this.crossdocked.get(itemId) ?? 0) >= line.qty) this.fact('READY_FOR_SALE', { itemId })
539 gap('9.3', 'simplified', 'WMS складу', 'Рух «тара → адреса» однією транзакцією: залишок, коефіцієнт і вага полиці, зняти резерв, закрити задачу', 'рух у пам\'яті; коефіцієнт заповненості не рахується', 'R-29 9.3, WMS-07')
540 if (address !== planned) gap('9.6', 'missing', 'WMS складу → Topology', 'Поклав не на рекомендовану адресу — причина й відхилення', 'адресу прийнято без причини', 'R-29 9.6, R-17 §10')
541 const units = [...c.contents.values()].reduce((s, x) => s + x, 0)
542 if (!units) {
543 c.status = 'empty'
544 gap('9.11', 'missing', 'WorkFlow / WMS складу', 'Порожня тара → задача «повернути на станцію» (обіг коробів і кошиків)', 'тару позначено порожньою, нікуди не повертається', 'R-29 9.11')
545 }
546 return { left: c.contents.size, units, deviation: address !== planned }
547 }
548
549 // ───────────────────────── спільне ─────────────────────────
550
551 /** Стан адрес для Topology (R-17): вага й об'єм зайнятих адрес, скільки цього товару вже лежить. */
552 addressState(itemId?: number) {
553 return [...this.addrLoad].map(([address, load]) => ({ address, weight: load.weight, volume: load.volume, sameSku: itemId ? this.stock.get(address)?.get(itemId) ?? 0 : 0 }))
554 }
555
556 private move(what: string, from: string, to: string) {
557 this.log.push(`РУХ ${what}: ${from} → ${to}`)
558 }
559
560 private fact(type: string, data: Json) {
561 this.outbox.push({ type, data, at: new Date().toISOString() })
562 gap('9.8', 'not-wired', 'WMS складу → майстер → ERP', 'Факти з outbox → канал фактів майстра → стрічка ERP', 'факти лишились в outbox емулятора (у wms-master канал фактів є)', 'R-29 1.19–1.20, 9.7–9.9, R-24')
563 }
564}
565
566/** Справжні розміри зі світу — те, що поверне софт заміру. */
567export function measureFrom(arrival: Arrival) {
568 return (itemId: number) => {
569 const line = arrival.lines.find((l) => l.itemId === itemId)!
570 const u = unitOf(line)
571 return { lengthM: u.lengthM, widthM: u.widthM, heightM: u.heightM, weightKg: u.weightKg }
572 }
573}
574
575export { barcodeOf }
576