techtools

faker.ts

TypeScript · 175 рядків

1// Фейкер автотоварів: 100 категорій (розхідники, запчастини, агрегати), ~4 000 назв, бренди, товари (бренд + SKU),
2// склад партії приймання й дати. Детермінований за seed.
3import { APPLICATION, BRAND_NAMES, CATEGORIES, NAME_CAP, SERIES, SMALL } from './catalog-data.ts';
4import { PackType, type Brand, type Category, type LotLine, type NewProduct } from './models.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 ProductOptions {
36  brands: Brand[];
37  skuMin: number;               // товарів на бренд, від
38  skuMax: number;               // товарів на бренд, до
39  categoriesPerBrand: [number, number];
40  sharedSkuShare: number;       // частка SKU, що повторює код іншого бренду (оригінальні номери, кроси)
41}
42
43export interface GeneratedLot { lines: LotLine[]; mfgDate: string | null; expiryDate: string | null; locationId: number }
44
45const DAY = 86_400_000;
46const ymd = (ms: number) => new Date(ms).toISOString().slice(0, 10);
47
48function cartesian(bases: string[], mods: string[][]): string[] {
49  let out = bases.slice();
50  for (const m of mods) out = out.flatMap((b) => m.map((x) => `${b} ${x}`));
51  return out;
52}
53
54export class Faker {
55  readonly rng: Rng;
56  private namesCache = new Map<number, string[]>();
57  private categoryList: Category[];
58
59  constructor(seed = 42) {
60    this.rng = new Rng(seed);
61    this.categoryList = 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  /** 100 категорій автотоварів із типовим пакуванням і строком. */
70  categories(): Category[] {
71    return this.categoryList;
72  }
73
74  category(id: number): Category {
75    return this.categoryList[id - 1];
76  }
77
78  /** Назви товарів категорії (детерміновано, не більше NAME_CAP). */
79  names(categoryId: number): string[] {
80    let n = this.namesCache.get(categoryId);
81    if (!n) {
82      const spec = CATEGORIES[categoryId - 1];
83      let all = cartesian(spec.bases, spec.mods);
84      if (all.length < SMALL) all = cartesian(all, [spec.kind === 'consumable' ? SERIES : APPLICATION]);
85      // рівномірна вибірка, щоб у межі потрапили всі основи
86      const step = Math.max(1, all.length / NAME_CAP);
87      n = Array.from({ length: Math.min(NAME_CAP, all.length) }, (_, i) => all[Math.floor(i * step)]);
88      this.namesCache.set(categoryId, n);
89    }
90    return n;
91  }
92
93  /** Усі назви каталогу (для перевірки обсягу). */
94  allNames(): string[] {
95    return this.categoryList.flatMap((c) => this.names(c.id));
96  }
97
98  /** count брендів із довідника (~150 назв). */
99  brands(count: number): Brand[] {
100    return BRAND_NAMES.slice(0, Math.min(count, BRAND_NAMES.length)).map((name, i) => ({ id: i + 1, name }));
101  }
102
103  /** Товари: кожен бренд працює в кількох категоріях; SKU у стилі бренду; частина SKU — коди інших брендів. */
104  products(o: ProductOptions): NewProduct[] {
105    const out: NewProduct[] = [];
106    const codes: string[] = [];
107    const cats = this.categoryList.map((c) => c.id);
108    for (const b of o.brands) {
109      const myCats = this.rng.shuffle(cats.slice()).slice(0, this.rng.int(o.categoriesPerBrand[0], o.categoriesPerBrand[1]));
110      const style = this.rng.int(0, 3);
111      const used = new Set<string>();
112      const n = this.rng.int(o.skuMin, o.skuMax);
113      for (let i = 0; i < n; i++) {
114        let sku = codes.length && this.rng.chance(o.sharedSkuShare) ? this.rng.pick(codes) : this.sku(style);
115        while (used.has(sku)) sku = this.sku(style);
116        used.add(sku);
117        codes.push(sku);
118        const category = this.rng.pick(myCats);
119        const c = this.category(category);
120        out.push({
121          brand_id: b.id, sku, category_id: category, name: `${this.rng.pick(this.names(category))}`,
122          shelf_life_days: c.shelf_life_days ? Math.round(c.shelf_life_days * (0.8 + this.rng.next() * 0.4)) : null,
123        });
124      }
125    }
126    return out;
127  }
128
129  private sku(style: number): string {
130    const d = (k: number) => Array.from({ length: k }, () => this.rng.int(0, 9)).join('');
131    const L = () => String.fromCharCode(65 + this.rng.int(0, 25));
132    switch (style) {
133      case 0: return d(10);                          // 0986494123
134      case 1: return `${L()}${L()} ${d(3)} ${d(3)}`; // AB 123 456
135      case 2: return `${d(3)}.${d(3)}.${d(2)}`;      // 123.456.78
136      default: return `${L()}${d(6)}`;               // K123456
137    }
138  }
139
140  /**
141   * Склад партії приймання qty одиниць за пакуванням категорії: цілі пакування + розсип-залишок.
142   * loose — приймати все розсипом (наприклад, переміщення без пакування).
143   */
144  lot(categoryId: number, qty: number, at: number, loose = false): GeneratedLot {
145    const c = this.category(categoryId);
146    const lines: LotLine[] = [];
147    if (!loose && c.pack1_size > 1 && qty >= c.pack1_size) {
148      lines.push({ pack_type: c.pack1_type, pack_size: c.pack1_size, pack_count: Math.floor(qty / c.pack1_size) });
149      if (qty % c.pack1_size) lines.push({ pack_type: PackType.unit, pack_size: 1, pack_count: qty % c.pack1_size });
150    } else {
151      lines.push({ pack_type: PackType.unit, pack_size: 1, pack_count: qty });
152    }
153    return { lines, ...this.dates(categoryId, at), locationId: this.location() };
154  }
155
156  /** Дата виготовлення і «придатний до»: товар приходить із віком до 30% строку. */
157  dates(categoryId: number, at: number): { mfgDate: string | null; expiryDate: string | null } {
158    const life = this.category(categoryId).shelf_life_days;
159    if (!life) return { mfgDate: null, expiryDate: null };
160    const mfg = at - this.rng.int(0, Math.floor(life * 0.3)) * DAY;
161    return { mfgDate: ymd(mfg), expiryDate: ymd(mfg + life * DAY) };
162  }
163
164  /** Адреса розміщення (умовний id комірки). */
165  location(): number {
166    return this.rng.int(1, 100_000);
167  }
168
169  /** Кількість у партії, округлена вгору до меншого пакування категорії. */
170  roundToPack(categoryId: number, qty: number): number {
171    const p = this.category(categoryId).pack1_size;
172    return p > 1 ? Math.ceil(qty / p) * p : qty;
173  }
174}
175