techtools

lab.ts

TypeScript · 53 рядків

1// Помічники тестів операцій. Усе — через API (як сторінка, заливка й прогін); жодного SQL у тестах.
2import assert from 'node:assert/strict';
3import { after, afterEach } from 'node:test';
4import { Api } from '../scripts/client.ts';
5import type { InvariantsOutput } from '../src/features/invariants.ts';
6import type { ProductState } from '../src/features/product-state.ts';
7
8export const PACK = { unit: 0, bag: 1, box: 2, carton: 3, bundle: 4, pallet: 5 } as const;
9
10let seq = 0;
11const runId = `${process.pid.toString(36)}${Date.now().toString(36).slice(-4)}`.toUpperCase();
12
13/**
14 * Підключитися до тестового сервера (LAB_URL з test/global-setup.ts).
15 * Після кожного тесту — перевірка інваріантів усієї бази: тест, що зламав облік, падає з кодом правила.
16 */
17export function useLab() {
18  const api = new Api(process.env.LAB_URL ?? 'http://127.0.0.1:3000');
19  afterEach(async () => {
20    const inv = await api.get<InvariantsOutput>('/api/invariants');
21    assert.deepEqual(inv.violations, [], `інваріанти порушено: ${inv.violations.map((v) => v.code).join(', ')}`);
22  });
23  after(() => api.close());
24
25  const categories = async (): Promise<any[]> => (await api.get('/api/meta')).categories;
26
27  return {
28    api,
29    /** Новий товар з унікальним SKU; категорія — перша, що задовольняє умову. */
30    async product(pick: (c: any) => boolean = (c) => !c.is_serial): Promise<{ id: number; categoryId: number }> {
31      const c = (await categories()).find(pick);
32      assert.ok(c, 'немає категорії під умову');
33      const p = await api.post('/api/products', { brandId: 1, sku: `T-${runId}-${++seq}`, name: 'тестовий товар', categoryId: c.id });
34      return { id: p.id, categoryId: c.id };
35    },
36    state: (productId: number) => api.get<ProductState>(`/api/products/${productId}/state`),
37    async receive(productId: number, lot: Record<string, unknown>, warehouseId = 1) {
38      return api.post('/api/receipts', { warehouseId, productId, locationId: 10101, ...lot });
39    },
40    async issue(productId: number, qty: number, extra: Record<string, unknown> = {}, warehouseId = 1) {
41      return api.post('/api/issues', { warehouseId, lines: [{ productId, qty }], ...extra });
42    },
43  };
44}
45
46/** Записи inventory_item складу: компактно для порівняння — тип:розмір×кількість (контейнер — з «[ ]»). */
47export function shape(state: ProductState, warehouseId = 1): string[] {
48  return state.items.filter((i: any) => i.warehouse_id === warehouseId).map((i: any) =>
49    `${i.is_container ? '[' : i.contained_in_id ? ' └' : ''}${i.pack_type}:${i.pack_size}×${i.pack_count}${i.is_container ? ']' : ''}`);
50}
51
52export const stockOf = (s: ProductState, warehouseId = 1) => s.stock.find((r: any) => r.warehouse_id === warehouseId) as any;
53