Compare commits
3 Commits
c2d3cdb088
...
f4ae04af15
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4ae04af15 | ||
|
|
bc323f2891 | ||
|
|
8111c3f377 |
@@ -183,6 +183,7 @@ Generated from `@openapi` annotations in [`src/api/routes/`](../../src/api/route
|
|||||||
| [`routes/propertyname/order.md`](routes/propertyname/order.md) | `PUT /propertyname/order` |
|
| [`routes/propertyname/order.md`](routes/propertyname/order.md) | `PUT /propertyname/order` |
|
||||||
| [`routes/propertyname/_id.delete.md`](routes/propertyname/_id.delete.md) | `DELETE /propertyname/{id}` |
|
| [`routes/propertyname/_id.delete.md`](routes/propertyname/_id.delete.md) | `DELETE /propertyname/{id}` |
|
||||||
| [`routes/propertyname/_id.patch.md`](routes/propertyname/_id.patch.md) | `PATCH /propertyname/{id}` |
|
| [`routes/propertyname/_id.patch.md`](routes/propertyname/_id.patch.md) | `PATCH /propertyname/{id}` |
|
||||||
|
| [`routes/public/telemetry/crash.md`](routes/public/telemetry/crash.md) | `POST /public/telemetry/crash` |
|
||||||
| [`routes/public/_companyId/articles.md`](routes/public/_companyId/articles.md) | `GET /public/{companyId}/articles` |
|
| [`routes/public/_companyId/articles.md`](routes/public/_companyId/articles.md) | `GET /public/{companyId}/articles` |
|
||||||
| [`routes/public/_companyId/articles/_sku.md`](routes/public/_companyId/articles/_sku.md) | `GET /public/{companyId}/articles/{sku}` |
|
| [`routes/public/_companyId/articles/_sku.md`](routes/public/_companyId/articles/_sku.md) | `GET /public/{companyId}/articles/{sku}` |
|
||||||
| [`routes/public/_companyId/categories.md`](routes/public/_companyId/categories.md) | `GET /public/{companyId}/categories` |
|
| [`routes/public/_companyId/categories.md`](routes/public/_companyId/categories.md) | `GET /public/{companyId}/categories` |
|
||||||
@@ -233,7 +234,7 @@ Clients subscribe via [`GET /events`](routes/events.md) (`text/event-stream`). A
|
|||||||
| Signal | Emitted by |
|
| Signal | Emitted by |
|
||||||
|--------|------------|
|
|--------|------------|
|
||||||
| `article-<sku>` | `PUT /article/{sku}/brand`, `PUT /article/{sku}/categories`, `PUT /article/{sku}/eans`, `POST /article/{sku}/image`, `DELETE /article/{sku}/image/{fullHash}`, `PUT /article/{sku}/images/order`, `PUT /article/{sku}/prices`, `POST /article/{sku}/supplier`, `PUT /article/{sku}/supplier/order`, `DELETE /article/{sku}/supplier/{id}`, `PATCH /article/{sku}/supplier/{id}`, `PUT /article/{sku}/track_stock`, `PUT /article/{sku}/weight` |
|
| `article-<sku>` | `PUT /article/{sku}/brand`, `PUT /article/{sku}/categories`, `PUT /article/{sku}/eans`, `POST /article/{sku}/image`, `DELETE /article/{sku}/image/{fullHash}`, `PUT /article/{sku}/images/order`, `PUT /article/{sku}/prices`, `POST /article/{sku}/supplier`, `PUT /article/{sku}/supplier/order`, `DELETE /article/{sku}/supplier/{id}`, `PATCH /article/{sku}/supplier/{id}`, `PUT /article/{sku}/track_stock`, `PUT /article/{sku}/weight` |
|
||||||
| `articles` | `POST /article`, `DELETE /article/{sku}`, `PATCH /article/{sku}` |
|
| `articles` | `POST /article`, `DELETE /article/{sku}`, `PATCH /article/{sku}`, `DELETE /category/{id}` |
|
||||||
| `category` | `POST /category`, `PUT /category/order`, `DELETE /category/{id}`, `PATCH /category/{id}`, `DELETE /category/{id}/image`, `POST /category/{id}/image` |
|
| `category` | `POST /category`, `PUT /category/order`, `DELETE /category/{id}`, `PATCH /category/{id}`, `DELETE /category/{id}/image`, `POST /category/{id}/image` |
|
||||||
| `vfs` | `POST /vfs/mkdir`, `POST /vfs/rename`, `POST /vfs/upload`, `DELETE /vfs/{*path}`, `PUT /vfs/{*path}` |
|
| `vfs` | `POST /vfs/mkdir`, `POST /vfs/rename`, `POST /vfs/upload`, `DELETE /vfs/{*path}`, `PUT /vfs/{*path}` |
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Dash API Routes Overview (All)
|
# Dash API Routes Overview (All)
|
||||||
|
|
||||||
Overview of all 191 API endpoints across all modules.
|
Overview of all 192 API endpoints across all modules.
|
||||||
|
|
||||||
### Notation
|
### Notation
|
||||||
|
|
||||||
@@ -232,7 +232,7 @@ _none_
|
|||||||
_none_
|
_none_
|
||||||
- Returns: `200 { languageId: int, tree: { id: int, sort: int, posterminalIds: int[], parentId?: int|null, name?: str|null, slug?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null }[], articles: { id: int, sku: str, name: str, slug: str, track_stock: bool, optionsCount: int, articleListCount: int, childCount: int, net?: num|null, taxRate?: num|null, parentArticleId?: int|null, parentSku?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null, brand?: T28|null }[] }`
|
- Returns: `200 { languageId: int, tree: { id: int, sort: int, posterminalIds: int[], parentId?: int|null, name?: str|null, slug?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null }[], articles: { id: int, sku: str, name: str, slug: str, track_stock: bool, optionsCount: int, articleListCount: int, childCount: int, net?: num|null, taxRate?: num|null, parentArticleId?: int|null, parentSku?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null, brand?: T28|null }[] }`
|
||||||
#### Delete category — `DELETE /category/{id}`
|
#### Delete category — `DELETE /category/{id}`
|
||||||
- Params: `id: int`
|
- Params: `id: int, query: recursive?: bool`
|
||||||
- Returns: `204 void`
|
- Returns: `204 void`
|
||||||
#### Update category (rename or move) — `PATCH /category/{id}`
|
#### Update category (rename or move) — `PATCH /category/{id}`
|
||||||
- Params: `id: int, body: { name?: str, parentId?: int }`
|
- Params: `id: int, body: { name?: str, parentId?: int }`
|
||||||
@@ -510,6 +510,9 @@ _none_
|
|||||||
#### Update property name — `PATCH /propertyname/{id}`
|
#### Update property name — `PATCH /propertyname/{id}`
|
||||||
- Params: `id: int, body: { name?: str, sort?: int, exclusive?: bool }`
|
- Params: `id: int, body: { name?: str, sort?: int, exclusive?: bool }`
|
||||||
- Returns: `200 { propertyname: T41 }`
|
- Returns: `200 { propertyname: T41 }`
|
||||||
|
#### Receipt crash dump — `POST /public/telemetry/crash`
|
||||||
|
- Params: `body: { content: any }`
|
||||||
|
- Returns: `200 { ok: bool, filename: str }`
|
||||||
#### List public articles — `GET /public/{companyId}/articles`
|
#### List public articles — `GET /public/{companyId}/articles`
|
||||||
- Params: `companyId: int, query: categoryId?: int, search?: str, limit?: int, offset?: int`
|
- Params: `companyId: int, query: categoryId?: int, search?: str, limit?: int, offset?: int`
|
||||||
- Returns: `200 { articles: { id: int, sku: str, name: str, slug: str, net: num|null, taxRate: num|null, gross: num|null, trackStock: bool, brand: { id: int|null, name: str }, fullHash: str|null, thumbW: int|null, thumbH: int|null, thumbHash: str|null }[] }`
|
- Returns: `200 { articles: { id: int, sku: str, name: str, slug: str, net: num|null, taxRate: num|null, gross: num|null, trackStock: bool, brand: { id: int|null, name: str }, fullHash: str|null, thumbW: int|null, thumbH: int|null, thumbHash: str|null }[] }`
|
||||||
|
|||||||
@@ -212,7 +212,7 @@ _none_
|
|||||||
_none_
|
_none_
|
||||||
- Returns: `200 { languageId: int, tree: { id: int, sort: int, posterminalIds: int[], parentId?: int|null, name?: str|null, slug?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null }[], articles: { id: int, sku: str, name: str, slug: str, track_stock: bool, optionsCount: int, articleListCount: int, childCount: int, net?: num|null, taxRate?: num|null, parentArticleId?: int|null, parentSku?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null, brand?: T27|null }[] }`
|
- Returns: `200 { languageId: int, tree: { id: int, sort: int, posterminalIds: int[], parentId?: int|null, name?: str|null, slug?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null }[], articles: { id: int, sku: str, name: str, slug: str, track_stock: bool, optionsCount: int, articleListCount: int, childCount: int, net?: num|null, taxRate?: num|null, parentArticleId?: int|null, parentSku?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null, brand?: T27|null }[] }`
|
||||||
#### Delete category — `DELETE /category/{id}`
|
#### Delete category — `DELETE /category/{id}`
|
||||||
- Params: `id: int`
|
- Params: `id: int, query: recursive?: bool`
|
||||||
- Returns: `204 void`
|
- Returns: `204 void`
|
||||||
#### Update category (rename or move) — `PATCH /category/{id}`
|
#### Update category (rename or move) — `PATCH /category/{id}`
|
||||||
- Params: `id: int, body: { name?: str, parentId?: int }`
|
- Params: `id: int, body: { name?: str, parentId?: int }`
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ Protected. Requires a valid session cookie (`credentials: 'include'`).
|
|||||||
|
|
||||||
Delete category
|
Delete category
|
||||||
|
|
||||||
Deletes a category the user is authorized for (not the company root).
|
Deletes a category the user is authorized for (not the company root). When recursive=true, recursively deletes all child categories, unassigns POS terminals, and deletes articles that only exist in the deleted subtree (including their children).
|
||||||
|
|
||||||
## Path parameters
|
## Path parameters
|
||||||
|
|
||||||
@@ -12,9 +12,15 @@ Deletes a category the user is authorized for (not the company root).
|
|||||||
|-------|----------|------|-------------|
|
|-------|----------|------|-------------|
|
||||||
| `id` | yes | integer | Category id |
|
| `id` | yes | integer | Category id |
|
||||||
|
|
||||||
|
## Query parameters
|
||||||
|
|
||||||
|
| Param | Required | Type | Description |
|
||||||
|
|-------|----------|------|-------------|
|
||||||
|
| `recursive` | no | boolean | When true, recursively deletes the category subtree and articles that only exist within it. |
|
||||||
|
|
||||||
## Signals
|
## Signals
|
||||||
|
|
||||||
On success, emits SSE signal: `category` (see [`GET /events`](../events.md)).
|
On success, emits SSE signals: `category`, `articles` (see [`GET /events`](../events.md)).
|
||||||
|
|
||||||
## Response `204`
|
## Response `204`
|
||||||
|
|
||||||
|
|||||||
41
docs/api/routes/public/telemetry/crash.md
Normal file
41
docs/api/routes/public/telemetry/crash.md
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
# `POST /public/telemetry/crash`
|
||||||
|
|
||||||
|
Public. No cookie required.
|
||||||
|
|
||||||
|
Receipt crash dump
|
||||||
|
|
||||||
|
Public endpoint to receive crash dumps. Saves the content parameter to a file named with the epoch millisecond.
|
||||||
|
|
||||||
|
## Body (JSON)
|
||||||
|
|
||||||
|
| Field | Required | Type | Description |
|
||||||
|
|-------|----------|------|-------------|
|
||||||
|
| `content` | yes | | Crash dump content to store |
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"content": "…"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Response `200`
|
||||||
|
|
||||||
|
Crash dump saved
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"ok": true,
|
||||||
|
"filename": "1728395535123"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Errors
|
||||||
|
|
||||||
|
| Status | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| 400 | Missing content parameter |
|
||||||
|
| 500 | Storage failure |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
_Generated from `@openapi` JSDoc. Do not edit by hand — run `npm run docs:api`._
|
||||||
@@ -74,7 +74,7 @@ function corsMiddleware(req, res, next) {
|
|||||||
if (req.path.startsWith('/api/public') || req.path.startsWith('/public')) {
|
if (req.path.startsWith('/api/public') || req.path.startsWith('/public')) {
|
||||||
res.setHeader('Access-Control-Allow-Origin', origin || '*');
|
res.setHeader('Access-Control-Allow-Origin', origin || '*');
|
||||||
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
||||||
res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS');
|
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
|
||||||
if (req.method === 'OPTIONS') {
|
if (req.method === 'OPTIONS') {
|
||||||
return res.sendStatus(204);
|
return res.sendStatus(204);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ export const openApiOptions = {
|
|||||||
{ name: 'Serper', description: 'Serper Google image search and thumbnail streaming' },
|
{ name: 'Serper', description: 'Serper Google image search and thumbnail streaming' },
|
||||||
{ name: 'PublicCatalog', description: 'Public product catalog API' },
|
{ name: 'PublicCatalog', description: 'Public product catalog API' },
|
||||||
{ name: 'Vfs', description: 'Virtual filesystem file management and preview' },
|
{ name: 'Vfs', description: 'Virtual filesystem file management and preview' },
|
||||||
|
{ name: 'Telemetry', description: 'Telemetry and crash reporting' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
apis: [
|
apis: [
|
||||||
|
|||||||
@@ -14,6 +14,13 @@ function emitCategorySignal(req) {
|
|||||||
emit('category', { companyId });
|
emit('category', { companyId });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Notify SSE subscribers of the actor's selected company after an article change. */
|
||||||
|
function emitArticlesSignal(req) {
|
||||||
|
const companyId = req.user?.selectedCompanyId;
|
||||||
|
if (companyId == null) return;
|
||||||
|
emit('articles', { companyId });
|
||||||
|
}
|
||||||
|
|
||||||
function parsePositiveInt(value, field) {
|
function parsePositiveInt(value, field) {
|
||||||
const id = Number(value);
|
const id = Number(value);
|
||||||
if (!Number.isInteger(id) || id <= 0) {
|
if (!Number.isInteger(id) || id <= 0) {
|
||||||
@@ -453,10 +460,10 @@ export function register(app, basePath = '') {
|
|||||||
* delete:
|
* delete:
|
||||||
* tags: [Category]
|
* tags: [Category]
|
||||||
* summary: Delete category
|
* summary: Delete category
|
||||||
* description: Deletes a category the user is authorized for (not the company root).
|
* description: Deletes a category the user is authorized for (not the company root). When recursive=true, recursively deletes all child categories, unassigns POS terminals, and deletes articles that only exist in the deleted subtree (including their children).
|
||||||
* security:
|
* security:
|
||||||
* - cookieAuth: []
|
* - cookieAuth: []
|
||||||
* x-signals: [category]
|
* x-signals: [category, articles]
|
||||||
* x-markdown: category/delete.md
|
* x-markdown: category/delete.md
|
||||||
* parameters:
|
* parameters:
|
||||||
* - in: path
|
* - in: path
|
||||||
@@ -465,6 +472,12 @@ export function register(app, basePath = '') {
|
|||||||
* schema:
|
* schema:
|
||||||
* type: integer
|
* type: integer
|
||||||
* description: Category id
|
* description: Category id
|
||||||
|
* - in: query
|
||||||
|
* name: recursive
|
||||||
|
* required: false
|
||||||
|
* schema:
|
||||||
|
* type: boolean
|
||||||
|
* description: When true, recursively deletes the category subtree and articles that only exist within it.
|
||||||
* responses:
|
* responses:
|
||||||
* 204:
|
* 204:
|
||||||
* description: Deleted
|
* description: Deleted
|
||||||
@@ -504,13 +517,18 @@ export function register(app, basePath = '') {
|
|||||||
if (parsed.error) {
|
if (parsed.error) {
|
||||||
return res.status(400).json({ error: parsed.error });
|
return res.status(400).json({ error: parsed.error });
|
||||||
}
|
}
|
||||||
|
const recursive = req.query.recursive === 'true';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await db.deleteCategory({
|
await db.deleteCategory({
|
||||||
googleAuthId: req.user.id,
|
googleAuthId: req.user.id,
|
||||||
id: parsed.id,
|
id: parsed.id,
|
||||||
|
recursive,
|
||||||
});
|
});
|
||||||
emitCategorySignal(req);
|
emitCategorySignal(req);
|
||||||
|
if (recursive) {
|
||||||
|
emitArticlesSignal(req);
|
||||||
|
}
|
||||||
res.sendStatus(204);
|
res.sendStatus(204);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const status = categoryErrorStatus(error);
|
const status = categoryErrorStatus(error);
|
||||||
|
|||||||
109
src/api/routes/telemetry.js
Normal file
109
src/api/routes/telemetry.js
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
|
const __dirname = path.dirname(__filename);
|
||||||
|
const CRASH_DUMP_DIR = process.env.CRASH_DUMP_DIR || path.resolve(__dirname, '../../../logs/crash-dumps');
|
||||||
|
|
||||||
|
function telemetryErrorStatus(error) {
|
||||||
|
if (error.message?.includes('required')) return 400;
|
||||||
|
return 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers public telemetry endpoints (no session/cookie auth required).
|
||||||
|
* @param {import('express').Application} app
|
||||||
|
* @param {string} [basePath='']
|
||||||
|
*/
|
||||||
|
export function register(app, basePath = '') {
|
||||||
|
/**
|
||||||
|
* @openapi
|
||||||
|
* /public/telemetry/crash:
|
||||||
|
* post:
|
||||||
|
* tags: [Telemetry]
|
||||||
|
* summary: Receipt crash dump
|
||||||
|
* description: Public endpoint to receive crash dumps. Saves the content parameter to a file named with the epoch millisecond.
|
||||||
|
* security: []
|
||||||
|
* requestBody:
|
||||||
|
* required: true
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* required:
|
||||||
|
* - content
|
||||||
|
* properties:
|
||||||
|
* content:
|
||||||
|
* description: Crash dump content to store
|
||||||
|
* oneOf:
|
||||||
|
* - type: string
|
||||||
|
* - type: object
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Crash dump saved
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* ok:
|
||||||
|
* type: boolean
|
||||||
|
* example: true
|
||||||
|
* filename:
|
||||||
|
* type: string
|
||||||
|
* example: "1728395535123"
|
||||||
|
* 400:
|
||||||
|
* description: Missing content parameter
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* error:
|
||||||
|
* type: string
|
||||||
|
* example: content is required
|
||||||
|
* 500:
|
||||||
|
* description: Storage failure
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* error:
|
||||||
|
* type: string
|
||||||
|
*/
|
||||||
|
const routePaths = [`${basePath}/public/telemetry/crash`];
|
||||||
|
if (basePath && !routePaths.includes('/public/telemetry/crash')) {
|
||||||
|
routePaths.push('/public/telemetry/crash');
|
||||||
|
}
|
||||||
|
|
||||||
|
app.post(routePaths, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { content } = req.body || {};
|
||||||
|
if (content === undefined || content === null) {
|
||||||
|
return res.status(400).json({ error: 'content is required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.promises.mkdir(CRASH_DUMP_DIR, { recursive: true });
|
||||||
|
|
||||||
|
let ts = Date.now();
|
||||||
|
let filePath = path.join(CRASH_DUMP_DIR, String(ts));
|
||||||
|
while (fs.existsSync(filePath)) {
|
||||||
|
ts++;
|
||||||
|
filePath = path.join(CRASH_DUMP_DIR, String(ts));
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = typeof content === 'string' ? content : JSON.stringify(content, null, 2);
|
||||||
|
await fs.promises.writeFile(filePath, data, 'utf8');
|
||||||
|
|
||||||
|
res.status(200).json({ ok: true, filename: String(ts) });
|
||||||
|
} catch (error) {
|
||||||
|
const status = telemetryErrorStatus(error);
|
||||||
|
if (status === 500) {
|
||||||
|
console.error('Crash dump error:', error);
|
||||||
|
}
|
||||||
|
res.status(status).json({ error: error.message || 'Internal server error' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -10,9 +10,9 @@ export async function createUnderParent({ googleAuthId, parentId, name }) {
|
|||||||
return store.category.createUnderParent({ googleAuthId, parentId, name });
|
return store.category.createUnderParent({ googleAuthId, parentId, name });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteCategory({ googleAuthId, id }) {
|
export async function deleteCategory({ googleAuthId, id, recursive = false }) {
|
||||||
const store = await getStore();
|
const store = await getStore();
|
||||||
await store.category.delete({ googleAuthId, id });
|
await store.category.delete({ googleAuthId, id, recursive });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getCategoryArticles(googleAuthId, categoryId) {
|
export async function getCategoryArticles(googleAuthId, categoryId) {
|
||||||
|
|||||||
@@ -91,6 +91,73 @@ export function parseCsvRecords(text) {
|
|||||||
return records;
|
return records;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalizes common variant attribute names and typos from JTL exports.
|
||||||
|
*
|
||||||
|
* @param {string} name
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function normalizeAttributeName(name) {
|
||||||
|
const clean = (name || '').trim();
|
||||||
|
if (!clean) return 'Variante';
|
||||||
|
const lower = clean.toLowerCase();
|
||||||
|
if (lower === 'menge' || lower === 'mange' || lower === 'meneg') return 'Menge';
|
||||||
|
if (lower === 'farbe') return 'Farbe';
|
||||||
|
if (lower === 'größe' || lower === 'grosse') return 'Größe';
|
||||||
|
if (lower === 'sorte') return 'Sorte';
|
||||||
|
if (lower === 'geschmack') return 'Geschmack';
|
||||||
|
if (lower === 'typ') return 'Typ';
|
||||||
|
if (lower === 'stück' || lower === 'stueck') return 'Stück';
|
||||||
|
if (lower === 'ausführung' || lower === 'ausfuehrung') return 'Ausführung';
|
||||||
|
if (lower === 'motiv') return 'Motiv';
|
||||||
|
return clean.charAt(0).toUpperCase() + clean.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extracts or derives a variant attribute value for a child article
|
||||||
|
* based on its name relative to its parent name, or SKU suffixes.
|
||||||
|
*
|
||||||
|
* @param {string} parentName
|
||||||
|
* @param {string} childName
|
||||||
|
* @param {string} childSku
|
||||||
|
* @param {string} parentSku
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function extractVariantValue(parentName, childName, childSku, parentSku) {
|
||||||
|
let pName = (parentName || '').replace(/[©®™]/g, '').trim();
|
||||||
|
let cName = (childName || '').replace(/[©®™]/g, '').trim();
|
||||||
|
|
||||||
|
if (pName && cName) {
|
||||||
|
// Child name starts with parent name
|
||||||
|
if (cName.toLowerCase().startsWith(pName.toLowerCase())) {
|
||||||
|
let val = cName.slice(pName.length).trim().replace(/^[-–—:/,\s]+/, '').trim();
|
||||||
|
if (val) return val;
|
||||||
|
}
|
||||||
|
// Match common leading tokens
|
||||||
|
const pWords = pName.toLowerCase().split(/\s+/);
|
||||||
|
const cWords = cName.split(/\s+/);
|
||||||
|
if (cWords.length > 1 && pWords[0] === cWords[0].toLowerCase()) {
|
||||||
|
let matchCount = 0;
|
||||||
|
while (matchCount < pWords.length && matchCount < cWords.length && pWords[matchCount] === cWords[matchCount].toLowerCase()) {
|
||||||
|
matchCount++;
|
||||||
|
}
|
||||||
|
if (matchCount > 0) {
|
||||||
|
const remaining = cWords.slice(matchCount).join(' ').trim().replace(/^[-–—:/,\s]+/, '').trim();
|
||||||
|
if (remaining) return remaining;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SKU suffix: "42001505-1" with parent "42001505" -> "1"
|
||||||
|
if (parentSku && childSku && childSku.startsWith(parentSku)) {
|
||||||
|
let suffix = childSku.slice(parentSku.length).trim().replace(/^[-_]+/, '').trim();
|
||||||
|
if (suffix) return suffix;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cName && cName !== pName) return cName;
|
||||||
|
return childSku || 'Standard';
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Executes full catalog import from preserved files in importDir.
|
* Executes full catalog import from preserved files in importDir.
|
||||||
*
|
*
|
||||||
@@ -502,23 +569,152 @@ export async function executeCompanyImport({
|
|||||||
console.log(`[Import] Linking ${variantChildren.length} child variants to parents...`);
|
console.log(`[Import] Linking ${variantChildren.length} child variants to parents...`);
|
||||||
onProgress('variants', 0, variantChildren.length, 'Linking variants');
|
onProgress('variants', 0, variantChildren.length, 'Linking variants');
|
||||||
|
|
||||||
let variantsLinked = 0;
|
// Fetch existing attribute names for this company
|
||||||
for (let i = 0; i < variantChildren.length; i++) {
|
const attributeMap = new Map(); // lowercase name -> attributeId
|
||||||
const child = variantChildren[i];
|
try {
|
||||||
const childSku = String(child.cArtNr || '').trim();
|
const attrList = await store.attributename.list(googleAuthId);
|
||||||
|
for (const attr of attrList) {
|
||||||
|
if (attr.name) {
|
||||||
|
attributeMap.set(attr.name.trim().toLowerCase(), attr.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
log.warn('Could not list attributes:', err.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper to resolve or create an attribute name
|
||||||
|
const resolveAttributeId = async (rawName) => {
|
||||||
|
const normalized = normalizeAttributeName(rawName);
|
||||||
|
const key = normalized.toLowerCase();
|
||||||
|
if (attributeMap.has(key)) {
|
||||||
|
return attributeMap.get(key);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const created = await store.attributename.create(googleAuthId, {
|
||||||
|
name: normalized,
|
||||||
|
exclusive: true,
|
||||||
|
});
|
||||||
|
attributeMap.set(key, created.id);
|
||||||
|
return created.id;
|
||||||
|
} catch (err) {
|
||||||
|
log.warn(`Could not create attribute "${normalized}":`, err.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Group children by parent SKU and preserve parent row reference
|
||||||
|
const parentChildrenMap = new Map();
|
||||||
|
for (const child of variantChildren) {
|
||||||
const parentJtlId = String(child.kVaterArtikel || '').trim();
|
const parentJtlId = String(child.kVaterArtikel || '').trim();
|
||||||
const parentSku = jtlArtIdToSku.get(parentJtlId);
|
const parentSku = jtlArtIdToSku.get(parentJtlId);
|
||||||
|
const childSku = String(child.cArtNr || '').trim();
|
||||||
|
if (!parentSku || !childSku || parentSku === childSku) continue;
|
||||||
|
|
||||||
if (childSku && parentSku && childSku !== parentSku) {
|
if (!parentChildrenMap.has(parentSku)) {
|
||||||
|
const parentRow = includedArticles.find((a) => String(a.kArtikel) === parentJtlId) || null;
|
||||||
|
parentChildrenMap.set(parentSku, { parentRow, children: [] });
|
||||||
|
}
|
||||||
|
parentChildrenMap.get(parentSku).children.push(child);
|
||||||
|
}
|
||||||
|
|
||||||
|
let variantsLinked = 0;
|
||||||
|
let processedCount = 0;
|
||||||
|
|
||||||
|
for (const [parentSku, { parentRow, children }] of parentChildrenMap.entries()) {
|
||||||
|
let parentDetail = null;
|
||||||
try {
|
try {
|
||||||
|
const res = await store.article.getBySku(googleAuthId, parentSku);
|
||||||
|
parentDetail = res.article;
|
||||||
|
} catch (err) {
|
||||||
|
log.warn(`[Import] Could not load parent ${parentSku}:`, err.message);
|
||||||
|
processedCount += children.length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine variant attribute name from parent row or children variations
|
||||||
|
let rawAttrName = null;
|
||||||
|
try {
|
||||||
|
const pVars = JSON.parse(parentRow?.variations || '[]');
|
||||||
|
rawAttrName = pVars[0]?.cEigenschaftName?.trim() || null;
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
if (!rawAttrName) {
|
||||||
|
for (const child of children) {
|
||||||
|
try {
|
||||||
|
const cVars = JSON.parse(child.variations || '[]');
|
||||||
|
rawAttrName = cVars[0]?.cEigenschaftName?.trim() || null;
|
||||||
|
if (rawAttrName) break;
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetAttrId = await resolveAttributeId(rawAttrName || 'Variante');
|
||||||
|
|
||||||
|
// Ensure parent has is_parent = 1 and parentattributename_id set
|
||||||
|
let parentAttrId = parentDetail?.parentAttributeNameId;
|
||||||
|
if (!parentDetail?.isParent || !parentAttrId) {
|
||||||
|
if (targetAttrId) {
|
||||||
|
try {
|
||||||
|
await store.article.toggleParent(googleAuthId, parentSku, {
|
||||||
|
isParent: true,
|
||||||
|
attributeNameId: targetAttrId,
|
||||||
|
});
|
||||||
|
parentAttrId = targetAttrId;
|
||||||
|
} catch (err) {
|
||||||
|
log.warn(`[Import] Could not toggle parent for ${parentSku}:`, err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const parentName = parentDetail?.name || '';
|
||||||
|
const usedValues = new Set();
|
||||||
|
|
||||||
|
for (const child of children) {
|
||||||
|
processedCount++;
|
||||||
|
const childSku = String(child.cArtNr || '').trim();
|
||||||
|
let childName = '';
|
||||||
|
try {
|
||||||
|
const desc = JSON.parse(child.descriptions || '[]');
|
||||||
|
childName = (Array.isArray(desc) ? desc[0]?.cName : desc?.cName) || '';
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
// Determine attribute value from child variations, falling back to name derivation
|
||||||
|
let val = null;
|
||||||
|
try {
|
||||||
|
const cVars = JSON.parse(child.variations || '[]');
|
||||||
|
val = cVars[0]?.selectedValues?.[0]?.cEigenschaftWertName?.trim() ||
|
||||||
|
cVars[0]?.variationValues?.[0]?.cEigenschaftWertName?.trim() || null;
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
if (!val) {
|
||||||
|
val = extractVariantValue(parentName, childName, childSku, parentSku);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (usedValues.has(val.toLowerCase())) {
|
||||||
|
val = `${val} (${childSku})`;
|
||||||
|
}
|
||||||
|
usedValues.add(val.toLowerCase());
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (parentAttrId) {
|
||||||
|
await store.article.attachChild(googleAuthId, parentSku, {
|
||||||
|
sku: childSku,
|
||||||
|
value: val,
|
||||||
|
reparent: true,
|
||||||
|
});
|
||||||
|
variantsLinked++;
|
||||||
|
} else {
|
||||||
|
// Fallback to setParentBySku if toggleParent failed
|
||||||
await store.article.setParentBySku(googleAuthId, childSku, parentSku);
|
await store.article.setParentBySku(googleAuthId, childSku, parentSku);
|
||||||
variantsLinked++;
|
variantsLinked++;
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.warn(`[Import] Failed to link child ${childSku} to parent ${parentSku}:`, err.message);
|
console.warn(`[Import] Failed to attach child ${childSku} to parent ${parentSku}:`, err.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (processedCount % 20 === 0 || processedCount === variantChildren.length) {
|
||||||
|
onProgress('variants', processedCount, variantChildren.length, `${childSku} -> ${parentSku}`);
|
||||||
}
|
}
|
||||||
if (i % 20 === 0 || i === variantChildren.length - 1) {
|
|
||||||
onProgress('variants', i + 1, variantChildren.length, `${childSku} -> ${parentSku}`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console.log(`[Import] Linked ${variantsLinked}/${variantChildren.length} variants`);
|
console.log(`[Import] Linked ${variantsLinked}/${variantChildren.length} variants`);
|
||||||
@@ -554,6 +750,144 @@ export async function executeCompanyImport({
|
|||||||
|
|
||||||
console.log(`[Import] Completed article pictures: ${totalImagesImported} images processed`);
|
console.log(`[Import] Completed article pictures: ${totalImagesImported} images processed`);
|
||||||
|
|
||||||
|
// ─── Phase 5: Orders (Manifests) Import ──────────────────────────────────
|
||||||
|
const manCsvPath = path.join(importDir, 'manifests.csv');
|
||||||
|
const itemsCsvPath = path.join(importDir, 'manifestitems.csv');
|
||||||
|
let ordersImported = 0;
|
||||||
|
let ordersSkipped = 0;
|
||||||
|
let totalOrders = 0;
|
||||||
|
|
||||||
|
if (fs.existsSync(manCsvPath) && fs.existsSync(itemsCsvPath)) {
|
||||||
|
const manRecords = parseCsvRecords(fs.readFileSync(manCsvPath, 'utf8'));
|
||||||
|
const itemRecords = parseCsvRecords(fs.readFileSync(itemsCsvPath, 'utf8'));
|
||||||
|
totalOrders = manRecords.length;
|
||||||
|
console.log(`[Import] Manifests found: ${totalOrders} orders, ${itemRecords.length} items`);
|
||||||
|
onProgress('orders', 0, totalOrders, 'Starting orders import');
|
||||||
|
|
||||||
|
// Group line items by kAuftrag
|
||||||
|
const itemsByAuftrag = new Map();
|
||||||
|
for (const it of itemRecords) {
|
||||||
|
const kAuftrag = String(it.kAuftrag || '').trim();
|
||||||
|
if (!kAuftrag) continue;
|
||||||
|
if (!itemsByAuftrag.has(kAuftrag)) {
|
||||||
|
itemsByAuftrag.set(kAuftrag, []);
|
||||||
|
}
|
||||||
|
itemsByAuftrag.get(kAuftrag).push(it);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pre-fetch existing orders to make import idempotent
|
||||||
|
const existingOrders = await store.order.list(googleAuthId);
|
||||||
|
const existingOrderNumbers = new Set(
|
||||||
|
existingOrders.map((o) => (o.number || '').trim()).filter(Boolean)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Pre-fetch customer groups and existing entities to resolve customer
|
||||||
|
let defaultCustomerGroupId = null;
|
||||||
|
try {
|
||||||
|
const groups = await store.customergroup.list(googleAuthId);
|
||||||
|
defaultCustomerGroupId = groups[0]?.id || null;
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
const entityMap = new Map(); // lowercase name -> entityId
|
||||||
|
try {
|
||||||
|
const entities = await store.entity.list(googleAuthId);
|
||||||
|
for (const ent of entities) {
|
||||||
|
if (ent.name) {
|
||||||
|
entityMap.set(ent.name.trim().toLowerCase(), ent.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
const resolveEntityId = async (name, firstName) => {
|
||||||
|
const cleanName = (name || '').trim();
|
||||||
|
if (!cleanName || !defaultCustomerGroupId) return null;
|
||||||
|
const key = cleanName.toLowerCase();
|
||||||
|
if (entityMap.has(key)) return entityMap.get(key);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const ent = await store.entity.create(googleAuthId, {
|
||||||
|
customergroupId: defaultCustomerGroupId,
|
||||||
|
name: cleanName,
|
||||||
|
firstName: (firstName || '').trim() || undefined,
|
||||||
|
});
|
||||||
|
entityMap.set(key, ent.id);
|
||||||
|
return ent.id;
|
||||||
|
} catch (err) {
|
||||||
|
log.warn(`[Import] Could not create entity "${cleanName}":`, err.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let i = 0; i < totalOrders; i++) {
|
||||||
|
const m = manRecords[i];
|
||||||
|
const orderNumber = String(m.cAuftragsNr || '').trim();
|
||||||
|
if (!orderNumber) continue;
|
||||||
|
|
||||||
|
if (existingOrderNumbers.has(orderNumber)) {
|
||||||
|
ordersSkipped++;
|
||||||
|
if (i % 50 === 0 || i === totalOrders - 1) {
|
||||||
|
onProgress('orders', i + 1, totalOrders, `${orderNumber} (skipped)`);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawItems = itemsByAuftrag.get(String(m.kAuftrag || '').trim()) || [];
|
||||||
|
if (rawItems.length === 0) {
|
||||||
|
ordersSkipped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = rawItems.map((it) => {
|
||||||
|
const sku = (it.cArtNr || '').trim() || null;
|
||||||
|
const name = (it.cName || it.cNameStandard || '').trim() || (sku ? `Artikel ${sku}` : 'Artikel');
|
||||||
|
const amount = parseFloat(String(it.fAnzahl || '1').replace(',', '.')) || 1;
|
||||||
|
const net = parseFloat(String(it.fVKNetto || '0').replace(',', '.')) || 0;
|
||||||
|
const taxrate = parseFloat(String(it.fMwSt || '19').replace(',', '.')) || 0;
|
||||||
|
const rebate = parseFloat(String(it.fRabatt || '0').replace(',', '.')) || 0;
|
||||||
|
const comment = (it.cHinweis || '').trim() || null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
sku,
|
||||||
|
name,
|
||||||
|
amount,
|
||||||
|
net,
|
||||||
|
taxrate,
|
||||||
|
rebate,
|
||||||
|
comment,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const custName = (m.cName || '').trim() || 'Laufkunde';
|
||||||
|
const custFirstName = (m.cVorname || '').trim();
|
||||||
|
const entityId = await resolveEntityId(custName, custFirstName);
|
||||||
|
|
||||||
|
const dateStr = (m.dErstellt || '').trim();
|
||||||
|
const parsedDate = dateStr ? new Date(dateStr) : new Date();
|
||||||
|
const validDate = !Number.isNaN(parsedDate.getTime()) ? parsedDate.toISOString() : new Date().toISOString();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await store.order.create(googleAuthId, {
|
||||||
|
number: orderNumber,
|
||||||
|
externalNumber: (m.cExterneAuftragsnummer || '').trim() || null,
|
||||||
|
date: validDate,
|
||||||
|
createdAt: validDate,
|
||||||
|
entityId: entityId || undefined,
|
||||||
|
lines,
|
||||||
|
});
|
||||||
|
existingOrderNumbers.add(orderNumber);
|
||||||
|
ordersImported++;
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`[Import] Failed to create order ${orderNumber}:`, err.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i % 50 === 0 || i === totalOrders - 1) {
|
||||||
|
onProgress('orders', i + 1, totalOrders, orderNumber);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[Import] Orders import complete: ${ordersImported} created, ${ordersSkipped} skipped`);
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
message: 'Import erfolgreich abgeschlossen.',
|
message: 'Import erfolgreich abgeschlossen.',
|
||||||
@@ -569,6 +903,9 @@ export async function executeCompanyImport({
|
|||||||
articlesUpdated,
|
articlesUpdated,
|
||||||
variantsLinked,
|
variantsLinked,
|
||||||
articlePictures: totalImagesImported,
|
articlePictures: totalImagesImported,
|
||||||
|
ordersTotal: totalOrders,
|
||||||
|
ordersImported,
|
||||||
|
ordersSkipped,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user