techtools

faker.ts

TypeScript · 169 рядків

1// Фейкер автотоварів (з research/lab/stock-db): 100 категорій, ~4 000 назв, бренди, товари бренд + SKU, склад партії, дати.
2// Детермінований за seed. Формат — під вхід API (import-catalog, receive).
3import { PackType } from '../src/domain/codes.ts';
4import { APPLICATION, BRAND_NAMES, CATEGORIES, NAME_CAP, SERIES, SMALL, type CategoryKind } from './catalog-data.ts';
5
6export class Rng {
7  private s: number;
8  constructor(seed: number) {
9    this.s = seed >>> 0;
10  }
11  next(): number {
12    let t = (this.s += 0x6d2b79f5);
13    t = Math.imul(t ^ (t >>> 15), t | 1);
14    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
15    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
16  }
17  int(min: number, max: number): number {
18    return min + Math.floor(this.next() * (max - min + 1));
19  }
20  pick<T>(a: readonly T[]): T {
21    return a[Math.floor(this.next() * a.length)];
22  }
23  chance(p: number): boolean {
24    return this.next() < p;
25  }
26  shuffle<T>(a: T[]): T[] {
27    for (let i = a.length - 1; i > 0; i--) {
28      const j = Math.floor(this.next() * (i + 1));
29      [a[i], a[j]] = [a[j], a[i]];
30    }
31    return a;
32  }
33}
34
35export interface Category {
36  id: number; name: string; kind: CategoryKind; pack1_type: number; pack1_size: number; pack2_type: number | null; pack2_size: number | null;
37  shelf_life_days: number | null; is_serial: boolean;
38}
39export interface NewProduct { brand_id: number; sku: string; name: string; category_id: number; shelf_life_days: number | null }
40export interface LotLine { packType: number; packSize: number; packCount: number }
41export interface Lot {
42  lines: LotLine[];
43  container: { packType: number; count: number } | null;
44  serials: string[] | null;
45  mfgDate: string | null;
46  expiryDate: string | null;
47}
48
49const DAY = 86_400_000;
50const ymd = (ms: number) => new Date(ms).toISOString().slice(0, 10);
51const cartesian = (bases: string[], mods: string[][]) => mods.reduce((out, m) => out.flatMap((b) => m.map((x) => `${b} ${x}`)), bases.slice());
52
53export class Faker {
54  readonly rng: Rng;
55  private readonly cats: Category[];
56  private readonly namesCache = new Map<number, string[]>();
57  private serialSeq = 0;
58
59  constructor(seed = 42) {
60    this.rng = new Rng(seed);
61    this.cats = CATEGORIES.map((c, i) => ({
62      id: i + 1, name: c.name, kind: c.kind,
63      pack1_type: c.pack[0] as number, pack1_size: c.pack[1] as number,
64      pack2_type: (c.pack[2] as number | null) ?? null, pack2_size: (c.pack[3] as number | null) ?? null,
65      shelf_life_days: c.life, is_serial: !!c.serial,
66    }));
67  }
68
69  categories(): Category[] {
70    return this.cats;
71  }
72
73  category(id: number): Category {
74    return this.cats[id - 1];
75  }
76
77  names(categoryId: number): string[] {
78    let n = this.namesCache.get(categoryId);
79    if (!n) {
80      const spec = CATEGORIES[categoryId - 1];
81      let all = cartesian(spec.bases, spec.mods);
82      if (all.length < SMALL) all = cartesian(all, [spec.kind === 'consumable' ? SERIES : APPLICATION]);
83      const step = Math.max(1, all.length / NAME_CAP);
84      n = Array.from({ length: Math.min(NAME_CAP, all.length) }, (_, i) => all[Math.floor(i * step)]);
85      this.namesCache.set(categoryId, n);
86    }
87    return n;
88  }
89
90  brands(count: number): { id: number; name: string }[] {
91    return BRAND_NAMES.slice(0, Math.min(count, BRAND_NAMES.length)).map((name, i) => ({ id: i + 1, name }));
92  }
93
94  /** Товари: бренд працює в кількох категоріях; SKU у стилі бренду; частина SKU — коди інших брендів (кроси). */
95  products(o: { brands: { id: number }[]; skuMin: number; skuMax: number; categoriesPerBrand: [number, number]; sharedSkuShare: number }): NewProduct[] {
96    const out: NewProduct[] = [];
97    const codes: string[] = [];
98    const ids = this.cats.map((c) => c.id);
99    for (const b of o.brands) {
100      const mine = this.rng.shuffle(ids.slice()).slice(0, this.rng.int(o.categoriesPerBrand[0], o.categoriesPerBrand[1]));
101      const style = this.rng.int(0, 3);
102      const used = new Set<string>();
103      for (let i = this.rng.int(o.skuMin, o.skuMax); i > 0; i--) {
104        let sku = codes.length && this.rng.chance(o.sharedSkuShare) ? this.rng.pick(codes) : this.sku(style);
105        while (used.has(sku)) sku = this.sku(style);
106        used.add(sku);
107        codes.push(sku);
108        const c = this.category(this.rng.pick(mine));
109        out.push({
110          brand_id: b.id, sku, category_id: c.id, name: this.rng.pick(this.names(c.id)),
111          shelf_life_days: c.shelf_life_days ? Math.round(c.shelf_life_days * (0.8 + this.rng.next() * 0.4)) : null,
112        });
113      }
114    }
115    return out;
116  }
117
118  private sku(style: number): string {
119    const d = (k: number) => Array.from({ length: k }, () => this.rng.int(0, 9)).join('');
120    const L = () => String.fromCharCode(65 + this.rng.int(0, 25));
121    switch (style) {
122      case 0: return d(10);
123      case 1: return `${L()}${L()} ${d(3)} ${d(3)}`;
124      case 2: return `${d(3)}.${d(3)}.${d(2)}`;
125      default: return `${L()}${d(6)}`;
126    }
127  }
128
129  /**
130   * Склад партії qty одиниць за пакуванням категорії: цілі пакування + розсип-залишок; серійні — поштучно з номерами;
131   * bundleShare — частка партій, що приходять однією спайкою (вміст — та сама розкладка).
132   */
133  lot(categoryId: number, qty: number, at: number, o: { loose?: boolean; bundleShare?: number } = {}): Lot {
134    const c = this.category(categoryId);
135    const lines: LotLine[] = [];
136    if (c.is_serial) {
137      lines.push({ packType: PackType.unit, packSize: 1, packCount: qty });
138      const serials = Array.from({ length: qty }, () => `SN${(++this.serialSeq).toString(36).toUpperCase().padStart(7, '0')}`);
139      return { lines, container: null, serials, ...this.dates(categoryId, at) };
140    }
141    if (!o.loose && c.pack1_size > 1 && qty >= c.pack1_size) {
142      lines.push({ packType: c.pack1_type, packSize: c.pack1_size, packCount: Math.floor(qty / c.pack1_size) });
143      if (qty % c.pack1_size) lines.push({ packType: PackType.unit, packSize: 1, packCount: qty % c.pack1_size });
144    } else {
145      lines.push({ packType: PackType.unit, packSize: 1, packCount: qty });
146    }
147    const bundle = !o.loose && lines[0].packType !== PackType.unit && this.rng.chance(o.bundleShare ?? 0);
148    return { lines, container: bundle ? { packType: PackType.bundle, count: 1 } : null, serials: null, ...this.dates(categoryId, at) };
149  }
150
151  /** Дата виготовлення і «придатний до»: товар приходить із віком до 30% строку. */
152  dates(categoryId: number, at: number): { mfgDate: string | null; expiryDate: string | null } {
153    const life = this.category(categoryId).shelf_life_days;
154    if (!life) return { mfgDate: null, expiryDate: null };
155    const mfg = at - this.rng.int(0, Math.floor(life * 0.3)) * DAY;
156    return { mfgDate: ymd(mfg), expiryDate: ymd(mfg + life * DAY) };
157  }
158
159  /** Адреса A-01-01 … H-40-06 як location_id (domain/location.ts). */
160  location(): number {
161    return this.rng.int(1, 8) * 10_000 + this.rng.int(1, 40) * 100 + this.rng.int(1, 6);
162  }
163
164  roundToPack(categoryId: number, qty: number): number {
165    const c = this.category(categoryId);
166    return !c.is_serial && c.pack1_size > 1 ? Math.ceil(qty / c.pack1_size) * c.pack1_size : qty;
167  }
168}
169