faker.ts
TypeScript · 259 рядків
1import type { LotIn, ProductIn } from './inventory.ts';
2
3// Детермінований генератор: однаковий seed — однаковий рік.
4export class Rng {
5 private s: number;
6 constructor(seed: number) {
7 this.s = seed >>> 0;
8 }
9 next(): number {
10 let t = (this.s += 0x6d2b79f5);
11 t = Math.imul(t ^ (t >>> 15), t | 1);
12 t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
13 return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
14 }
15 int(min: number, max: number): number {
16 return min + Math.floor(this.next() * (max - min + 1));
17 }
18 pick<T>(a: readonly T[]): T {
19 return a[Math.floor(this.next() * a.length)];
20 }
21 chance(p: number): boolean {
22 return this.next() < p;
23 }
24 poisson(lambda: number): number {
25 const l = Math.exp(-lambda);
26 let k = 0;
27 let p = 1;
28 do {
29 k++;
30 p *= this.next();
31 } while (p > l);
32 return k - 1;
33 }
34}
35
36export interface PackLevel { type: string; size: number }
37
38export interface Profile {
39 category: string;
40 share: number;
41 brands: string[];
42 names: string[];
43 serial?: boolean;
44 shelfLife?: [number, number];
45 levels: PackLevel[]; // від меншого до більшого; [] — лише поштучно
46 container?: { type: 'bundle' | 'pallet'; of: number }; // скільки верхніх пакувань у спайці/палеті
47 smallMax: number;
48}
49
50export const PROFILES: Profile[] = [
51 { category: 'Кріплення', share: 0.18, brands: ['Febi Bilstein', 'SWAG', 'Würth', 'Bossard', 'Topran'],
52 names: ['Болт М8×25', 'Гайка М10', 'Кліпса обшивки', 'Шайба ущільнювальна', 'Хомут 12-22'],
53 levels: [{ type: 'bag', size: 10 }, { type: 'box', size: 100 }], container: { type: 'bundle', of: 10 }, smallMax: 20 },
54 { category: 'Свічки', share: 0.08, brands: ['NGK', 'Bosch', 'Denso', 'Champion', 'Brisk'],
55 names: ['Свічка запалювання', 'Свічка розжарювання'],
56 levels: [{ type: 'box', size: 4 }, { type: 'carton', size: 40 }], container: { type: 'bundle', of: 10 }, smallMax: 8 },
57 { category: 'Фільтри', share: 0.18, brands: ['Mann-Filter', 'Mahle', 'Bosch', 'Filtron', 'Knecht'],
58 names: ['Фільтр масляний', 'Фільтр повітряний', 'Фільтр салону', 'Фільтр паливний'],
59 levels: [{ type: 'carton', size: 12 }], container: { type: 'pallet', of: 20 }, smallMax: 4 },
60 { category: 'Гальмівні колодки', share: 0.1, brands: ['Brembo', 'TRW', 'ATE', 'Ferodo', 'Textar'],
61 names: ['Колодки гальмівні передні', 'Колодки гальмівні задні'],
62 levels: [{ type: 'carton', size: 10 }], container: { type: 'pallet', of: 24 }, smallMax: 3 },
63 { category: 'Лампи', share: 0.07, brands: ['Philips', 'Osram', 'Narva', 'Bosch'],
64 names: ['Лампа H7', 'Лампа H4', 'Лампа W5W'],
65 levels: [{ type: 'box', size: 10 }, { type: 'carton', size: 100 }], container: { type: 'bundle', of: 5 }, smallMax: 10 },
66 { category: 'Герметики', share: 0.07, brands: ['Loctite', 'Elring', 'Victor Reinz', 'Permatex'], shelfLife: [365, 720],
67 names: ['Герметик силіконовий', 'Фіксатор різьби', 'Клей-герметик прокладок'],
68 levels: [{ type: 'box', size: 12 }], container: { type: 'bundle', of: 10 }, smallMax: 6 },
69 { category: 'Масла', share: 0.1, brands: ['Castrol', 'Mobil', 'Shell', 'Liqui Moly', 'Motul'], shelfLife: [1095, 1825],
70 names: ['Олива моторна 5W-30 4л', 'Олива трансмісійна 1л', 'Антифриз 5л'],
71 levels: [{ type: 'box', size: 4 }], container: { type: 'pallet', of: 40 }, smallMax: 4 },
72 { category: 'Підшипники і ремені', share: 0.12, brands: ['SKF', 'INA', 'FAG', 'Gates', 'Dayco', 'Contitech'],
73 names: ['Підшипник маточини', 'Ремінь ГРМ', 'Ролик натяжний', 'Ремінь поліклиновий'],
74 levels: [{ type: 'box', size: 10 }], smallMax: 3 },
75 { category: 'Дорогі вузли (серійні)', share: 0.05, brands: ['Bosch', 'Denso', 'Delphi', 'Garrett', 'BorgWarner', 'Valeo', 'Continental'],
76 names: ['Форсунка паливна', 'Турбокомпресор', 'Блок керування ЕБУ', 'Генератор', 'ТНВД'], serial: true,
77 levels: [], container: { type: 'bundle', of: 4 }, smallMax: 2 },
78];
79
80export interface SimProduct {
81 input: ProductIn;
82 profile: Profile;
83 cls: 'A' | 'B' | 'C';
84 lambda: number; // рядків замовлень на день
85 lead: number; // днів поставки
86 rop: number; // поріг дозамовлення (доступний залишок)
87 orderQty: number;
88 id?: number;
89}
90
91function containerTotal(p: Profile): number {
92 if (!p.container) return 0;
93 const top = p.levels.at(-1);
94 return (top ? top.size : 1) * p.container.of;
95}
96
97export function drawQty(p: SimProduct, rng: Rng): number {
98 const pr = p.profile;
99 const r = rng.next();
100 if (r < 0.6 || !pr.levels.length) return rng.int(1, pr.smallMax);
101 if (r < 0.9 || p.cls === 'C') return rng.pick(pr.levels).size * rng.int(1, 5);
102 const ct = containerTotal(pr);
103 return ct ? ct * rng.int(1, 2) : pr.levels.at(-1)!.size * rng.int(2, 10);
104}
105
106export function generateCatalog(n: number, rng: Rng): SimProduct[] {
107 const total = PROFILES.reduce((s, p) => s + p.share, 0);
108 const used = new Set<string>();
109 const skus: string[] = [];
110 const out: SimProduct[] = [];
111 for (let i = 0; i < n; i++) {
112 let x = rng.next() * total;
113 const prof = PROFILES.find((p) => (x -= p.share) < 0) ?? PROFILES[0];
114 let brand = rng.pick(prof.brands);
115 // ~4% SKU повторюються в іншого бренду: ключ — бренд + SKU.
116 let sku = skus.length && rng.chance(0.04) ? rng.pick(skus) : `${rng.int(10, 99)}${rng.pick(['', '-', '.'])}${rng.int(1000, 99999)}`;
117 for (let tries = 0; used.has(`${brand}|${sku}`) && tries < 10; tries++) brand = rng.pick(prof.brands);
118 if (used.has(`${brand}|${sku}`)) sku = `${sku}-${i}`;
119 used.add(`${brand}|${sku}`);
120 skus.push(sku);
121
122 const rank = i / n;
123 const cls = rank < 0.2 ? 'A' : rank < 0.5 ? 'B' : 'C';
124 const lambda = (cls === 'A' ? 0.8 : cls === 'B' ? 0.2 : 0.04) * (prof.serial ? 0.3 : 1);
125 const shelf = prof.shelfLife ? rng.int(prof.shelfLife[0], prof.shelfLife[1]) : null;
126 const top = prof.levels.at(-1);
127 const sp: SimProduct = {
128 input: {
129 brand, sku, name: `${rng.pick(prof.names)} ${brand}`, category: prof.category, is_serial: !!prof.serial,
130 shelf_life_days: shelf, std_pack_type: top?.type ?? null, std_pack_size: top?.size ?? null,
131 },
132 profile: prof, cls, lambda, lead: rng.int(3, 14), rop: 0, orderQty: 0,
133 };
134 // Оцінка денного попиту для порогу дозамовлення.
135 const est = new Rng(i + 7);
136 let s = 0;
137 for (let k = 0; k < 300; k++) s += drawQty(sp, est);
138 const daily = lambda * (s / 300);
139 sp.rop = Math.max(1, Math.ceil(daily * (sp.lead + 7)));
140 const unit = prof.serial ? 1 : top?.size ?? 1;
141 sp.orderQty = Math.max(unit, Math.ceil((daily * 30) / unit) * unit, prof.serial ? 2 : 0);
142 out.push(sp);
143 }
144 return out;
145}
146
147export interface Counters {
148 containers: number;
149 mixed_pack_container: number;
150 mixed_loose_container: number;
151 nonstandard_pack: number;
152 mixed_date_disassembled: number;
153 serial_in_container: number;
154 container_labels: number;
155 box_labels_at_receipt: number;
156}
157
158export function newCounters(): Counters {
159 return { containers: 0, mixed_pack_container: 0, mixed_loose_container: 0, nonstandard_pack: 0, mixed_date_disassembled: 0,
160 serial_in_container: 0, container_labels: 0, box_labels_at_receipt: 0 };
161}
162
163let labelSeq = 0;
164let serialSeq = 0;
165const nextLabel = () => `WL${String(++labelSeq).padStart(7, '0')}`;
166const location = (rng: Rng) => `${rng.pick(['A', 'B', 'C', 'D'])}${rng.int(1, 40)}-${rng.int(1, 30)}-${rng.int(1, 6)}-${rng.int(1, 4)}`;
167
168export type Dating = () => { mfg_day?: number; expiry_day?: number };
169
170/**
171 * Що приймальник вводить для поставки Q одиниць: партії, пакування партії і рядки.
172 * dating — дати однієї партії (виготовлення та/або «вжити до»); без нього дати лише для товарів зі строком.
173 */
174export function composeReceipt(sp: SimProduct, q: number, day: number, rng: Rng, c: Counters, dating?: Dating): LotIn[] {
175 const pr = sp.profile;
176 const key = { brand: sp.input.brand, sku: sp.input.sku, product_id: sp.id };
177 const dated = !!dating || !!pr.shelfLife;
178 const mfg = dating ?? (() => (pr.shelfLife ? { mfg_day: day - rng.int(5, 150) } : {}));
179 const lots: LotIn[] = [];
180 let rest = q;
181
182 if (pr.serial) {
183 const serials = (n: number) => Array.from({ length: n }, () => `${sp.input.brand.slice(0, 3).toUpperCase()}26${String(++serialSeq).padStart(8, '0')}`);
184 while (rest > 0) {
185 const of = pr.container!.of;
186 if (rest >= of && rng.chance(0.3)) {
187 c.serial_in_container++;
188 lots.push({ ...key, ...mfg(), location: location(rng), container: { type: pr.container!.type, total: of }, lines: [{ pack_type: 'unit', pack_size: 1, pack_count: of, serials: serials(of) }] });
189 rest -= of;
190 } else {
191 lots.push({ ...key, ...mfg(), location: location(rng), lines: [{ pack_type: 'unit', pack_size: 1, pack_count: rest, serials: serials(rest) }] });
192 rest = 0;
193 }
194 }
195 return lots;
196 }
197
198 const top = pr.levels.at(-1);
199 const lower = pr.levels.at(-2);
200 const ct = containerTotal(pr);
201 if (pr.container && top && q >= ct && rng.chance(0.75)) {
202 const n = Math.floor(q / ct);
203 const of = pr.container.of;
204 for (let i = 0; i < n; i++) {
205 rest -= ct;
206 const loc = location(rng);
207 if (dated && rng.chance(0.1)) {
208 // Різні дати на коробках: спайку розбирають і вводять кожне пакування окремою партією.
209 c.mixed_date_disassembled++;
210 for (let j = 0; j < of; j++) lots.push({ ...key, ...mfg(), location: loc, lines: [{ pack_type: top.type, pack_size: top.size, pack_count: 1 }] });
211 continue;
212 }
213 const r = rng.next();
214 let lines;
215 if (r < 0.7) {
216 lines = [{ pack_type: top.type, pack_size: top.size, pack_count: of }];
217 } else if (r < 0.88 && lower) {
218 c.mixed_pack_container++; // 9 коробок по 100 + 10 пакетів по 10
219 lines = [{ pack_type: top.type, pack_size: top.size, pack_count: of - 1 }, { pack_type: lower.type, pack_size: lower.size, pack_count: top.size / lower.size }];
220 } else if (r < 0.95) {
221 c.mixed_loose_container++;
222 lines = [{ pack_type: top.type, pack_size: top.size, pack_count: of - 1 }, { pack_type: 'unit', pack_size: 1, pack_count: top.size }];
223 } else {
224 c.nonstandard_pack++; // одна коробка неповна — приймальник вводить фактичну кількість
225 const d = rng.int(1, Math.max(1, Math.floor(top.size / 10)));
226 lines = top.size > 1
227 ? [{ pack_type: top.type, pack_size: top.size, pack_count: of - 1 }, { pack_type: top.type, pack_size: top.size - d, pack_count: 1 }]
228 : [{ pack_type: top.type, pack_size: top.size, pack_count: of }];
229 }
230 const total = lines.reduce((s, l) => s + l.pack_size * l.pack_count, 0);
231 const label = rng.chance(0.3) ? nextLabel() : undefined;
232 if (label) c.container_labels++;
233 c.containers++;
234 lots.push({ ...key, ...mfg(), location: loc, container: { type: pr.container.type, total, label }, lines });
235 }
236 }
237
238 const lines: LotIn['lines'] = [];
239 if (top && rest >= top.size) {
240 const k = Math.floor(rest / top.size);
241 if (k > 1 && rng.chance(0.03)) {
242 c.box_labels_at_receipt++; // одну коробку маркують складською етикеткою вже при прийманні
243 lines.push({ pack_type: top.type, pack_size: top.size, pack_count: 1, label: nextLabel() });
244 lines.push({ pack_type: top.type, pack_size: top.size, pack_count: k - 1 });
245 } else {
246 lines.push({ pack_type: top.type, pack_size: top.size, pack_count: k });
247 }
248 rest -= k * top.size;
249 }
250 if (lower && rest >= lower.size) {
251 const k = Math.floor(rest / lower.size);
252 lines.push({ pack_type: lower.type, pack_size: lower.size, pack_count: k });
253 rest -= k * lower.size;
254 }
255 if (rest > 0) lines.push({ pack_type: 'unit', pack_size: 1, pack_count: rest });
256 if (lines.length) lots.push({ ...key, ...mfg(), location: location(rng), lines });
257 return lots;
258}
259