export
This commit is contained in:
@@ -1,5 +1,8 @@
|
||||
import express from 'express';
|
||||
import JSZip from 'jszip';
|
||||
import * as db from '../../db/article.js';
|
||||
import * as picDb from '../../db/pic.js';
|
||||
import { buildArtikelCsv, toWindows1252 } from '../../util/artikelCsv.js';
|
||||
|
||||
const AVIF_BODY_LIMIT = '20mb';
|
||||
const FULL_HASH_RE = /^[a-fA-F0-9]{64}$/;
|
||||
@@ -138,6 +141,110 @@ export function register(app, basePath = '') {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/export.zip:
|
||||
* get:
|
||||
* tags: [Article]
|
||||
* summary: Export articles as ZIP
|
||||
* description: |
|
||||
* Builds an `artikel.zip` for the authenticated user's selected company.
|
||||
* `categoryId` (optional) restricts the export to that category and below;
|
||||
* it must be reachable via the company's root category. Defaults to the
|
||||
* whole company root tree.
|
||||
* The ZIP contains `artikel.csv` (semicolon-separated, Windows-1252)
|
||||
* plus one AVIF entry per article image, named `<fullHash>.avif`
|
||||
* (content-addressed, so shared hashes are deduplicated).
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: categoryId
|
||||
* required: false
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Restrict export to this category subtree
|
||||
* 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}/article/export.zip`, async (req, res) => {
|
||||
const companyId = req.user.selectedCompanyId;
|
||||
if (companyId == null) {
|
||||
return res.status(400).json({ error: 'No company selected' });
|
||||
}
|
||||
|
||||
let categoryId = null;
|
||||
if (req.query.categoryId != null && req.query.categoryId !== '') {
|
||||
const parsed = parsePositiveInt(req.query.categoryId, 'categoryId');
|
||||
if (parsed.error) {
|
||||
return res.status(400).json({ error: parsed.error });
|
||||
}
|
||||
categoryId = parsed.id;
|
||||
}
|
||||
|
||||
try {
|
||||
const rows = await db.listExport(req.user.id, companyId, categoryId);
|
||||
|
||||
const csv = buildArtikelCsv(rows);
|
||||
|
||||
const zip = new JSZip();
|
||||
zip.file('artikel.csv', toWindows1252(csv));
|
||||
|
||||
const seen = new Set();
|
||||
for (const row of rows) {
|
||||
for (const fullHash of row.fullHashes ?? []) {
|
||||
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="artikel.zip"');
|
||||
res.status(200).send(content);
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Export articles failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}:
|
||||
|
||||
@@ -64,3 +64,8 @@ export async function listSearchIndex(googleAuthId, companyId) {
|
||||
const store = await getStore();
|
||||
return store.article.listSearchIndex(googleAuthId, companyId);
|
||||
}
|
||||
|
||||
export async function listExport(googleAuthId, companyId, categoryId) {
|
||||
const store = await getStore();
|
||||
return store.article.listExport(googleAuthId, companyId, categoryId);
|
||||
}
|
||||
|
||||
70
src/util/artikelCsv.js
Normal file
70
src/util/artikelCsv.js
Normal file
@@ -0,0 +1,70 @@
|
||||
function csvField(value) {
|
||||
const text = value == null ? '' : String(value);
|
||||
return /[";\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
|
||||
}
|
||||
|
||||
const COLUMNS = [
|
||||
'FullHash',
|
||||
'Id',
|
||||
'SKU',
|
||||
'Name',
|
||||
'Slug',
|
||||
'Einheit',
|
||||
'EinheitSymbol',
|
||||
'Menge',
|
||||
'Marke',
|
||||
'Netto',
|
||||
'MwSt',
|
||||
'EANs',
|
||||
'Kategorien',
|
||||
'KategorienPfad',
|
||||
];
|
||||
|
||||
function formatNumber(value) {
|
||||
if (value == null || Number.isNaN(Number(value))) return '';
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build artikel.csv from the article export rows returned by `listExport`.
|
||||
* Rows are sorted by Id (server-side ORDER BY a.id). Semicolon separated with a
|
||||
* `sep=;` hint; Windows-1252 encoding is applied in the route via toWindows1252.
|
||||
*/
|
||||
export function buildArtikelCsv(rows) {
|
||||
if (!Array.isArray(rows) || rows.length === 0) return '';
|
||||
|
||||
const lines = [
|
||||
'sep=;',
|
||||
COLUMNS.map(csvField).join(';'),
|
||||
...rows.map((row) =>
|
||||
[
|
||||
csvField((row.fullHashes ?? []).join(', ')),
|
||||
csvField(row.id),
|
||||
csvField(row.sku),
|
||||
csvField(row.name ?? ''),
|
||||
csvField(row.slug ?? ''),
|
||||
csvField(row.unitSi ?? ''),
|
||||
csvField(row.unitSymbol ?? ''),
|
||||
csvField(row.unitamount),
|
||||
csvField(row.brandName ?? ''),
|
||||
formatNumber(row.net),
|
||||
formatNumber(row.taxRate),
|
||||
csvField((row.eans ?? []).join(', ')),
|
||||
csvField((row.categoryIds ?? []).join(', ')),
|
||||
csvField((row.categoryBreadcrumbs ?? []).join(', ')),
|
||||
].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;
|
||||
}
|
||||
Reference in New Issue
Block a user