feat: add article search index endpoint and category export.zip

- Add GET /api/articleIndex returning the article search index (listSearchIndex)
- Add GET /api/category/export.zip returning a kategorien.zip with a
  Windows-1252 CSV (depth-first, Ebene N columns) plus one AVIF per category image
  (content-addressed, deduplicated) using jszip
This commit is contained in:
seb
2026-08-04 00:30:32 +02:00
parent bfcb073e32
commit c6cb1bc229
19 changed files with 1718 additions and 1 deletions

View File

@@ -39,6 +39,7 @@ function articleErrorStatus(error) {
if (error.message === 'Invalid unitamount') return 400;
if (error.message === 'Unit not found') return 404;
if (error.message === 'Invalid eans') return 400;
if (error.message === 'Company not found') return 404;
if (error.message === 'Brand not found') return 404;
if (error.message === 'Invalid weight') return 400;
if (error.message === 'Invalid categoryIds') return 400;
@@ -1074,4 +1075,85 @@ export function register(app, basePath = '') {
res.status(status).json({ error: error.message });
}
});
/**
* @openapi
* /articleIndex:
* get:
* tags: [Article]
* summary: List article search index
* description: |
* Returns every article reachable via the company's category tree.
* Designed for client-side search / autocomplete preload.
* Auth via company access.
* security:
* - cookieAuth: []
* responses:
* 200:
* description: Search index
* content:
* application/json:
* schema:
* type: object
* properties:
* articles:
* type: array
* items:
* type: object
* properties:
* id:
* type: integer
* sku:
* type: string
* name:
* type: string
* nullable: true
* eans:
* type: array
* items:
* type: string
* categoryIds:
* type: array
* items:
* type: integer
* 400:
* description: No company selected
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 401:
* description: Unauthorized
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 403:
* description: Not authorized
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Company not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
app.get(`${basePath}/articleIndex`, async (req, res) => {
const companyId = req.user.selectedCompanyId;
if (companyId == null) {
return res.status(400).json({ error: 'No company selected' });
}
try {
const articles = await db.listSearchIndex(req.user.id, companyId);
res.status(200).json({ articles });
} catch (error) {
const status = articleErrorStatus(error);
if (status === 500) console.error('List article search index failed:', error);
res.status(status).json({ error: error.message });
}
});
}

View File

@@ -1,5 +1,8 @@
import express from 'express';
import JSZip from 'jszip';
import * as db from '../../db/category.js';
import * as picDb from '../../db/pic.js';
import { buildKategorienCsv, toWindows1252 } from '../../util/kategorienCsv.js';
const AVIF_BODY_LIMIT = '20mb';
@@ -101,6 +104,91 @@ export function register(app, basePath = '') {
}
});
/**
* @openapi
* /category/export.zip:
* get:
* tags: [Category]
* summary: Export categories as ZIP
* description: |
* Builds a `kategorien.zip` for the authenticated user's selected company.
* The ZIP contains `kategorien.csv` (semicolon-separated, Windows-1252,
* depth-first in sort order with an `Ebene N` name column per tree depth)
* plus one AVIF entry per category image, named `<fullHash>.avif`
* (content-addressed, so shared hashes are deduplicated).
* security:
* - cookieAuth: []
* responses:
* 200:
* description: ZIP archive
* content:
* application/zip:
* schema:
* type: string
* format: binary
* 400:
* description: No company selected
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 401:
* description: Unauthorized
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 403:
* description: Not authorized
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Company not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
app.get(`${basePath}/category/export.zip`, async (req, res) => {
const companyId = req.user.selectedCompanyId;
if (companyId == null) {
return res.status(400).json({ error: 'No company selected' });
}
try {
const { tree } = await db.getTreeForCompany(req.user.id, companyId);
const csv = buildKategorienCsv(tree, tree.find((n) => n.parentId == null)?.id ?? null);
const zip = new JSZip();
zip.file('kategorien.csv', toWindows1252(csv));
const seen = new Set();
for (const node of tree) {
const fullHash = node.fullHash;
if (!fullHash || seen.has(fullHash)) continue;
seen.add(fullHash);
try {
const { buffer } = await picDb.getImageByHash(req.user.id, fullHash);
zip.file(`${fullHash}.avif`, buffer);
} catch (error) {
// Skip images this user cannot access; CSV already carries the hash.
}
}
const content = await zip.generateAsync({ type: 'nodebuffer' });
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', 'attachment; filename="kategorien.zip"');
res.status(200).send(content);
} catch (error) {
const status = categoryErrorStatus(error);
if (status === 500) console.error('Export categories failed:', error);
res.status(status).json({ error: error.message });
}
});
/**
* @openapi
* /category:

View File

@@ -59,3 +59,8 @@ export async function setCategoryIdsBySku(googleAuthId, sku, categoryIds) {
const store = await getStore();
return store.article.setCategoryIdsBySku(googleAuthId, sku, categoryIds);
}
export async function listSearchIndex(googleAuthId, companyId) {
const store = await getStore();
return store.article.listSearchIndex(googleAuthId, companyId);
}

76
src/util/kategorienCsv.js Normal file
View File

@@ -0,0 +1,76 @@
export const ROOT_CATEGORY_NAME = 'Home';
/** Escape a value for a CSV field ("..." double-quoting per RFC 4180). */
function csvField(value) {
const text = value == null ? '' : String(value);
return /[";\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
}
function categoryDisplayName(name, categoryId, rootCategoryId) {
if (rootCategoryId != null && String(categoryId) === String(rootCategoryId)) {
return ROOT_CATEGORY_NAME;
}
return (name ?? '').trim();
}
/**
* Build the kategorien.csv string from the flattened category tree returned by
* `getTreeForCompany`. Each row carries FullHash;Id and one name cell in the
* `Ebene N` column matching the category's tree depth (root = Ebene 1).
* Mirrors the frontend's client-side export format exactly.
*/
export function buildKategorienCsv(tree, rootCategoryId) {
if (!Array.isArray(tree) || tree.length === 0) return '';
const children = new Map();
const keyOf = (parentId) =>
parentId == null || parentId === 0 ? 'ROOT' : String(parentId);
for (const node of tree) {
const key = keyOf(node.parentId);
if (!children.has(key)) children.set(key, []);
children.get(key).push(node);
}
children.forEach((arr) =>
arr.sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0) || a.id - b.id),
);
const root = tree.find((n) => keyOf(n.parentId) === 'ROOT');
const ordered = [];
const visited = new Set();
const walk = (node, depth) => {
if (node == null || visited.has(String(node.id))) return;
visited.add(String(node.id));
ordered.push({ node, depth });
(children.get(String(node.id)) ?? []).forEach((kid) => walk(kid, depth + 1));
};
walk(root, 0);
const maxDepth = ordered.reduce((m, item) => Math.max(m, item.depth), 0);
const levelHeaders = Array.from({ length: maxDepth + 1 }, (_, i) => `Ebene ${i + 1}`);
const headers = ['FullHash', 'Id', ...levelHeaders];
const lines = [
'sep=;',
headers.map(csvField).join(';'),
...ordered.map(({ node, depth }) => {
const name = categoryDisplayName(node.name, node.id, rootCategoryId);
return [
csvField(node.fullHash ?? ''),
csvField(node.id),
...levelHeaders.map((_, index) => (index === depth ? csvField(name) : '')),
].join(';');
}),
];
return lines.join('\r\n');
}
/** Encode a string as Windows-1252 bytes (single-byte; out-of-range → '?'). */
export function toWindows1252(str) {
const bytes = Buffer.alloc(str.length);
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
bytes[i] = code <= 0xff ? code : 0x3f; // '?'
}
return bytes;
}