techtools
Головна / research / lab / stock-lab / src / features / import-catalog.ts

import-catalog.ts

TypeScript · 61 рядків

1// POST /api/catalog/import — пакетне завантаження довідників і товарів (скрипт заливки).
2// Склади, бренди, категорії — upsert за id; товари — вставка пакетом, id повертаються в порядку входу.
3import { z } from 'zod';
4import { feature } from '../platform/http.ts';
5
6const Category = z.object({
7  id: z.number().int(), name: z.string(), kind: z.enum(['part', 'consumable', 'assembly']),
8  pack1_type: z.number().int(), pack1_size: z.number().int(), pack2_type: z.number().int().nullable(), pack2_size: z.number().int().nullable(),
9  shelf_life_days: z.number().int().nullable(), is_serial: z.boolean(),
10});
11const Product = z.object({ brand_id: z.number().int(), sku: z.string(), name: z.string(), category_id: z.number().int(), shelf_life_days: z.number().int().nullable() });
12
13export const ImportCatalogInput = z.object({
14  warehouses: z.array(z.object({ id: z.number().int(), name: z.string() })).default([]),
15  brands: z.array(z.object({ id: z.number().int(), name: z.string() })).default([]),
16  categories: z.array(Category).default([]),
17  products: z.array(Product).max(20_000).default([]),
18});
19
20export default feature({
21  name: 'importCatalog',
22  method: 'POST',
23  path: '/api/catalog/import',
24  summary: 'Пакетна заливка складів, брендів, категорій і товарів (до 20 000 за запит)',
25  input: ImportCatalogInput,
26  tx: 'write',
27  run: async (sql, { warehouses: w, brands: b, categories: c, products: p }) => {
28    if (w.length) {
29      await sql.query(`
30        INSERT INTO stock.warehouse (id, name) SELECT * FROM unnest(:ids::smallint[], :names::text[])
31        ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name`, { ids: w.map((x) => x.id), names: w.map((x) => x.name) });
32    }
33    if (b.length) {
34      await sql.query(`
35        INSERT INTO stock.brand (id, name) SELECT * FROM unnest(:ids::smallint[], :names::text[])
36        ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name`, { ids: b.map((x) => x.id), names: b.map((x) => x.name) });
37    }
38    if (c.length) {
39      await sql.query(`
40        INSERT INTO stock.category (id, name, kind, pack1_type, pack1_size, pack2_type, pack2_size, shelf_life_days, is_serial)
41        SELECT * FROM unnest(:ids::smallint[], :names::text[], :kinds::text[], :p1t::smallint[], :p1s::int[], :p2t::smallint[], :p2s::int[],
42                             :life::int[], :serial::boolean[])
43        ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, kind = EXCLUDED.kind, pack1_type = EXCLUDED.pack1_type, pack1_size = EXCLUDED.pack1_size,
44          pack2_type = EXCLUDED.pack2_type, pack2_size = EXCLUDED.pack2_size, shelf_life_days = EXCLUDED.shelf_life_days, is_serial = EXCLUDED.is_serial`, {
45        ids: c.map((x) => x.id), names: c.map((x) => x.name), kinds: c.map((x) => x.kind), p1t: c.map((x) => x.pack1_type), p1s: c.map((x) => x.pack1_size),
46        p2t: c.map((x) => x.pack2_type), p2s: c.map((x) => x.pack2_size), life: c.map((x) => x.shelf_life_days), serial: c.map((x) => x.is_serial),
47      });
48    }
49    const productIds = !p.length ? [] : (await sql.query<{ id: number }>(`
50      INSERT INTO stock.product (brand_id, sku, name, category_id, shelf_life_days)
51      SELECT b, s, n, c, l FROM unnest(:brands::smallint[], :skus::text[], :names::text[], :categories::smallint[], :life::int[])
52        WITH ORDINALITY AS x(b, s, n, c, l, ord)
53      ORDER BY ord
54      RETURNING id`, {
55      brands: p.map((x) => x.brand_id), skus: p.map((x) => x.sku), names: p.map((x) => x.name),
56      categories: p.map((x) => x.category_id), life: p.map((x) => x.shelf_life_days),
57    })).map((r) => r.id);
58    return { warehouses: w.length, brands: b.length, categories: c.length, productIds };
59  },
60});
61