diff --git a/docs/api/README.md b/docs/api/README.md index 0c3b678..db3feee 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -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/_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/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/_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` | @@ -233,7 +234,7 @@ Clients subscribe via [`GET /events`](routes/events.md) (`text/event-stream`). A | Signal | Emitted by | |--------|------------| | `article-` | `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` | | `vfs` | `POST /vfs/mkdir`, `POST /vfs/rename`, `POST /vfs/upload`, `DELETE /vfs/{*path}`, `PUT /vfs/{*path}` | diff --git a/docs/api/routes-all.md b/docs/api/routes-all.md index 8aface2..5fbff91 100644 --- a/docs/api/routes-all.md +++ b/docs/api/routes-all.md @@ -1,6 +1,6 @@ # Dash API Routes Overview (All) -Overview of all 191 API endpoints across all modules. +Overview of all 192 API endpoints across all modules. ### Notation @@ -232,7 +232,7 @@ _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 }[] }` #### Delete category — `DELETE /category/{id}` -- Params: `id: int` +- Params: `id: int, query: recursive?: bool` - Returns: `204 void` #### Update category (rename or move) — `PATCH /category/{id}` - Params: `id: int, body: { name?: str, parentId?: int }` @@ -510,6 +510,9 @@ _none_ #### Update property name — `PATCH /propertyname/{id}` - Params: `id: int, body: { name?: str, sort?: int, exclusive?: bool }` - 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` - 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 }[] }` diff --git a/docs/api/routes.md b/docs/api/routes.md index a333b90..94c73b2 100644 --- a/docs/api/routes.md +++ b/docs/api/routes.md @@ -212,7 +212,7 @@ _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 }[] }` #### Delete category — `DELETE /category/{id}` -- Params: `id: int` +- Params: `id: int, query: recursive?: bool` - Returns: `204 void` #### Update category (rename or move) — `PATCH /category/{id}` - Params: `id: int, body: { name?: str, parentId?: int }` diff --git a/docs/api/routes/category/delete.md b/docs/api/routes/category/delete.md index 2252d9b..f0f8545 100644 --- a/docs/api/routes/category/delete.md +++ b/docs/api/routes/category/delete.md @@ -4,7 +4,7 @@ Protected. Requires a valid session cookie (`credentials: 'include'`). 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 @@ -12,9 +12,15 @@ Deletes a category the user is authorized for (not the company root). |-------|----------|------|-------------| | `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 -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` diff --git a/docs/api/routes/public/telemetry/crash.md b/docs/api/routes/public/telemetry/crash.md new file mode 100644 index 0000000..e7250e6 --- /dev/null +++ b/docs/api/routes/public/telemetry/crash.md @@ -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`._ diff --git a/src/api/index.js b/src/api/index.js index 81d7e29..8580da9 100644 --- a/src/api/index.js +++ b/src/api/index.js @@ -74,7 +74,7 @@ function corsMiddleware(req, res, next) { if (req.path.startsWith('/api/public') || req.path.startsWith('/public')) { res.setHeader('Access-Control-Allow-Origin', origin || '*'); 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') { return res.sendStatus(204); } diff --git a/src/api/openapiSpec.js b/src/api/openapiSpec.js index 1f47182..f121c74 100644 --- a/src/api/openapiSpec.js +++ b/src/api/openapiSpec.js @@ -47,6 +47,7 @@ export const openApiOptions = { { name: 'Serper', description: 'Serper Google image search and thumbnail streaming' }, { name: 'PublicCatalog', description: 'Public product catalog API' }, { name: 'Vfs', description: 'Virtual filesystem file management and preview' }, + { name: 'Telemetry', description: 'Telemetry and crash reporting' }, ], }, apis: [ diff --git a/src/api/routes/category.js b/src/api/routes/category.js index 6cd4ab2..149b72e 100644 --- a/src/api/routes/category.js +++ b/src/api/routes/category.js @@ -14,6 +14,13 @@ function emitCategorySignal(req) { 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) { const id = Number(value); if (!Number.isInteger(id) || id <= 0) { @@ -453,10 +460,10 @@ export function register(app, basePath = '') { * delete: * tags: [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: * - cookieAuth: [] - * x-signals: [category] + * x-signals: [category, articles] * x-markdown: category/delete.md * parameters: * - in: path @@ -465,6 +472,12 @@ export function register(app, basePath = '') { * schema: * type: integer * 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: * 204: * description: Deleted @@ -504,13 +517,18 @@ export function register(app, basePath = '') { if (parsed.error) { return res.status(400).json({ error: parsed.error }); } + const recursive = req.query.recursive === 'true'; try { await db.deleteCategory({ googleAuthId: req.user.id, id: parsed.id, + recursive, }); emitCategorySignal(req); + if (recursive) { + emitArticlesSignal(req); + } res.sendStatus(204); } catch (error) { const status = categoryErrorStatus(error); diff --git a/src/api/routes/telemetry.js b/src/api/routes/telemetry.js new file mode 100644 index 0000000..23b5287 --- /dev/null +++ b/src/api/routes/telemetry.js @@ -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' }); + } + }); +} diff --git a/src/db/category.js b/src/db/category.js index fee2850..bf20865 100644 --- a/src/db/category.js +++ b/src/db/category.js @@ -10,9 +10,9 @@ export async function 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(); - await store.category.delete({ googleAuthId, id }); + await store.category.delete({ googleAuthId, id, recursive }); } export async function getCategoryArticles(googleAuthId, categoryId) {