Add article history by SKU and SSE update signals for live clients.

Expose getHistoryBySku as GET /article/:sku/history, and document mutation-emitted company signals via GET /events.
This commit is contained in:
seb
2026-08-05 09:54:56 +02:00
parent 4a9403bfd1
commit 782c49a680
28 changed files with 757 additions and 2 deletions

View File

@@ -2,11 +2,26 @@ import express from 'express';
import JSZip from 'jszip';
import * as db from '../../db/article.js';
import * as picDb from '../../db/pic.js';
import { emit } from '../sse.js';
import { buildArtikelCsv, toWindows1252 } from '../../util/artikelCsv.js';
const AVIF_BODY_LIMIT = '20mb';
const FULL_HASH_RE = /^[a-fA-F0-9]{64}$/;
/** Notify SSE subscribers after create / rename-ish list-level article changes. */
function emitArticlesSignal(req) {
const companyId = req.user?.selectedCompanyId;
if (companyId == null) return;
emit('articles', { companyId });
}
/** Notify SSE subscribers of a single-article detail change. */
function emitArticleSignal(req, sku) {
const companyId = req.user?.selectedCompanyId;
if (companyId == null) return;
emit(`article-${sku}`, { companyId });
}
function parsePositiveInt(value, field) {
const id = Number(value);
if (!Number.isInteger(id) || id <= 0) {
@@ -64,6 +79,7 @@ export function register(app, basePath = '') {
* description: Creates an article under an authorized category (`parentId`).
* security:
* - cookieAuth: []
* x-signals: [articles]
* x-markdown: article/create.md
* requestBody:
* required: true
@@ -133,6 +149,7 @@ export function register(app, basePath = '') {
parentId: parent.id,
name,
});
emitArticlesSignal(req);
res.status(201).json({ article });
} catch (error) {
const status = articleErrorStatus(error);
@@ -304,6 +321,7 @@ export function register(app, basePath = '') {
* `unitSi` must already exist for the company. Returns the same detail shape as GET.
* security:
* - cookieAuth: []
* x-signals: [articles]
* x-markdown: article/update.md
* parameters:
* - in: path
@@ -373,6 +391,7 @@ export function register(app, basePath = '') {
* Auth like GET by SKU.
* security:
* - cookieAuth: []
* x-signals: [articles]
* x-markdown: article/delete.md
* parameters:
* - in: path
@@ -425,6 +444,87 @@ export function register(app, basePath = '') {
}
});
/**
* @openapi
* /article/{sku}/history:
* get:
* tags: [Article]
* summary: Get article history by SKU
* description: |
* Returns `articlehistory` rows for the article, newest first (`date` DESC, `id` DESC).
* Auth like GET by SKU.
* security:
* - cookieAuth: []
* x-markdown: article/history.md
* parameters:
* - in: path
* name: sku
* required: true
* schema:
* type: string
* description: Article SKU
* responses:
* 200:
* description: Article history (newest first)
* content:
* application/json:
* schema:
* type: object
* required: [history]
* properties:
* history:
* type: array
* items:
* $ref: '#/components/schemas/ArticleHistoryEntry'
* example:
* history:
* - id: 42
* date: '2026-08-05T07:15:00.000Z'
* text: "Name geändert von \"Tee\" auf \"Grüner Tee\"\nEinheit geändert von \"500g\" auf \"1kg\""
* - id: 41
* date: '2026-08-01T09:00:00.000Z'
* text: 'Name geändert von "" auf "Tee"'
* 400:
* description: Missing sku
* 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: Article not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
app.get(`${basePath}/article/:sku/history`, async (req, res) => {
const sku = typeof req.params.sku === 'string' ? req.params.sku.trim() : '';
if (!sku) {
return res.status(400).json({ error: 'sku is required' });
}
try {
const history = await db.getHistoryBySku(req.user.id, decodeURIComponent(sku));
res.status(200).json({ history });
} catch (error) {
const status = articleErrorStatus(error);
if (status === 500) console.error('Get article history by sku failed:', error);
res.status(status).json({ error: error.message });
}
});
app.patch(`${basePath}/article/:sku`, async (req, res) => {
const sku = typeof req.params.sku === 'string' ? req.params.sku.trim() : '';
if (!sku) {
@@ -448,7 +548,9 @@ export function register(app, basePath = '') {
}
try {
const article = await db.updateBySku(req.user.id, decodeURIComponent(sku), patch);
const decodedSku = decodeURIComponent(sku);
const article = await db.updateBySku(req.user.id, decodedSku, patch);
emitArticlesSignal(req);
res.status(200).json({ article });
} catch (error) {
const status = articleErrorStatus(error);
@@ -465,6 +567,7 @@ export function register(app, basePath = '') {
try {
await db.remove(req.user.id, parsed.sku);
emitArticlesSignal(req);
res.sendStatus(204);
} catch (error) {
const status = articleErrorStatus(error);
@@ -485,6 +588,7 @@ export function register(app, basePath = '') {
* Empty `prices` clears all POS prices. Returns the same shape as GET by SKU.
* security:
* - cookieAuth: []
* x-signals: [article-<sku>]
* x-markdown: article/set-prices.md
* parameters:
* - in: path
@@ -569,6 +673,7 @@ export function register(app, basePath = '') {
try {
const article = await db.setPricesBySku(req.user.id, skuParsed.sku, req.body.prices);
emitArticleSignal(req, skuParsed.sku);
res.status(200).json({ article });
} catch (error) {
const status = articleErrorStatus(error);
@@ -590,6 +695,7 @@ export function register(app, basePath = '') {
* Auth like GET by SKU.
* security:
* - cookieAuth: []
* x-signals: [article-<sku>]
* x-markdown: article/add-image.md
* parameters:
* - in: path
@@ -655,7 +761,9 @@ export function register(app, basePath = '') {
}
try {
const image = await db.addImage(req.user.id, decodeURIComponent(sku), imageBuffer);
const decodedSku = decodeURIComponent(sku);
const image = await db.addImage(req.user.id, decodedSku, imageBuffer);
emitArticleSignal(req, decodedSku);
res.status(201).json({ image });
} catch (error) {
const status = articleErrorStatus(error);
@@ -674,6 +782,7 @@ export function register(app, basePath = '') {
* description: Removes `articlepic` and the `pic` row for this article (`fullHash`). Auth like GET by SKU.
* security:
* - cookieAuth: []
* x-signals: [article-<sku>]
* x-markdown: article/delete-image.md
* parameters:
* - in: path
@@ -727,6 +836,7 @@ export function register(app, basePath = '') {
try {
await db.deleteImage(req.user.id, skuParsed.sku, hashParsed.fullHash);
emitArticleSignal(req, skuParsed.sku);
res.sendStatus(204);
} catch (error) {
const status = articleErrorStatus(error);
@@ -746,6 +856,7 @@ export function register(app, basePath = '') {
* `fullHashes` must list every image of the article exactly once.
* security:
* - cookieAuth: []
* x-signals: [article-<sku>]
* x-markdown: article/order-images.md
* parameters:
* - in: path
@@ -829,6 +940,7 @@ export function register(app, basePath = '') {
try {
const result = await db.orderImages(req.user.id, skuParsed.sku, { fullHashes });
emitArticleSignal(req, skuParsed.sku);
res.status(200).json(result);
} catch (error) {
const status = articleErrorStatus(error);
@@ -848,6 +960,7 @@ export function register(app, basePath = '') {
* empty array clears all EANs. Returns the same shape as GET by SKU.
* security:
* - cookieAuth: []
* x-signals: [article-<sku>]
* x-markdown: article/set-eans.md
* parameters:
* - in: path
@@ -916,6 +1029,7 @@ export function register(app, basePath = '') {
try {
const article = await db.setEansBySku(req.user.id, skuParsed.sku, req.body.eans);
emitArticleSignal(req, skuParsed.sku);
res.status(200).json({ article });
} catch (error) {
const status = articleErrorStatus(error);
@@ -935,6 +1049,7 @@ export function register(app, basePath = '') {
* Pass `null` to clear the brand. Returns the same shape as GET by SKU.
* security:
* - cookieAuth: []
* x-signals: [article-<sku>]
* x-markdown: article/set-brand.md
* parameters:
* - in: path
@@ -1000,6 +1115,7 @@ export function register(app, basePath = '') {
try {
const article = await db.setBrandIdBySku(req.user.id, skuParsed.sku, brandId);
emitArticleSignal(req, skuParsed.sku);
res.status(200).json({ article });
} catch (error) {
const status = articleErrorStatus(error);
@@ -1019,6 +1135,7 @@ export function register(app, basePath = '') {
* Returns the same shape as GET by SKU.
* security:
* - cookieAuth: []
* x-signals: [article-<sku>]
* x-markdown: article/set-weight.md
* parameters:
* - in: path
@@ -1083,6 +1200,7 @@ export function register(app, basePath = '') {
try {
const article = await db.setWeightBySku(req.user.id, skuParsed.sku, weight);
emitArticleSignal(req, skuParsed.sku);
res.status(200).json({ article });
} catch (error) {
const status = articleErrorStatus(error);
@@ -1103,6 +1221,7 @@ export function register(app, basePath = '') {
* article from all categories. Returns the same shape as GET by SKU.
* security:
* - cookieAuth: []
* x-signals: [article-<sku>]
* x-markdown: article/set-categories.md
* parameters:
* - in: path
@@ -1175,6 +1294,7 @@ export function register(app, basePath = '') {
skuParsed.sku,
req.body.categoryIds,
);
emitArticleSignal(req, skuParsed.sku);
res.status(200).json({ article });
} catch (error) {
const status = articleErrorStatus(error);

View File

@@ -2,10 +2,18 @@ import express from 'express';
import JSZip from 'jszip';
import * as db from '../../db/category.js';
import * as picDb from '../../db/pic.js';
import { emit } from '../sse.js';
import { buildKategorienCsv, toWindows1252 } from '../../util/kategorienCsv.js';
const AVIF_BODY_LIMIT = '20mb';
/** Notify SSE subscribers of the actor's selected company after a real category change. */
function emitCategorySignal(req) {
const companyId = req.user?.selectedCompanyId;
if (companyId == null) return;
emit('category', { companyId });
}
function parsePositiveInt(value, field) {
const id = Number(value);
if (!Number.isInteger(id) || id <= 0) {
@@ -198,6 +206,7 @@ export function register(app, basePath = '') {
* description: Creates a category under an authorized parent.
* security:
* - cookieAuth: []
* x-signals: [category]
* x-markdown: category/create.md
* requestBody:
* required: true
@@ -266,6 +275,7 @@ export function register(app, basePath = '') {
parentId: parent.id,
name,
});
emitCategorySignal(req);
res.status(201).json({ category });
} catch (error) {
const status = categoryErrorStatus(error);
@@ -352,6 +362,7 @@ export function register(app, basePath = '') {
* Either `name` or `parentId` (or both) is required.
* security:
* - cookieAuth: []
* x-signals: [category]
* x-markdown: category/update.md
* parameters:
* - in: path
@@ -426,6 +437,7 @@ export function register(app, basePath = '') {
* description: Deletes a category the user is authorized for (not the company root).
* security:
* - cookieAuth: []
* x-signals: [category]
* x-markdown: category/delete.md
* parameters:
* - in: path
@@ -467,6 +479,7 @@ export function register(app, basePath = '') {
googleAuthId: req.user.id,
id: parsed.id,
});
emitCategorySignal(req);
res.sendStatus(204);
} catch (error) {
const status = categoryErrorStatus(error);
@@ -517,6 +530,7 @@ export function register(app, basePath = '') {
}
}
emitCategorySignal(req);
res.status(200).json({ category });
} catch (error) {
const status = categoryErrorStatus(error);
@@ -538,6 +552,7 @@ export function register(app, basePath = '') {
* to its index `0..n-1` in one transaction.
* security:
* - cookieAuth: []
* x-signals: [category]
* x-markdown: category/order.md
* requestBody:
* required: true
@@ -615,6 +630,7 @@ export function register(app, basePath = '') {
try {
const result = await db.order({ googleAuthId: req.user.id, parentId, categoryIds });
emitCategorySignal(req);
res.status(200).json(result);
} catch (error) {
const status = categoryErrorStatus(error);
@@ -636,6 +652,7 @@ export function register(app, basePath = '') {
* Auth like GET /category/tree — user must be authorized for the category's company.
* security:
* - cookieAuth: []
* x-signals: [category]
* x-markdown: category/add-image.md
* parameters:
* - in: path
@@ -702,6 +719,7 @@ export function register(app, basePath = '') {
* Auth like GET /category/tree — user must be authorized for the category's company.
* security:
* - cookieAuth: []
* x-signals: [category]
* x-markdown: category/delete-image.md
* parameters:
* - in: path
@@ -767,6 +785,7 @@ export function register(app, basePath = '') {
try {
const category = await db.addImage(req.user.id, parsed.id, imageBuffer);
emitCategorySignal(req);
res.status(201).json({ category });
} catch (error) {
const status = categoryErrorStatus(error);
@@ -784,6 +803,7 @@ export function register(app, basePath = '') {
try {
const category = await db.deleteImage(req.user.id, parsed.id);
emitCategorySignal(req);
res.status(200).json({ category });
} catch (error) {
const status = categoryErrorStatus(error);

99
src/api/routes/events.js Normal file
View File

@@ -0,0 +1,99 @@
import { subscribe } from '../sse.js';
/**
* Registers the SSE update-events stream (requires auth).
* @param {import('express').Application} app - Express app
* @param {string} [basePath=''] - Optional URL prefix for all routes in this module
*/
export function register(app, basePath = '') {
/**
* @openapi
* /events:
* get:
* tags: [Events]
* summary: Subscribe to update signals (SSE)
* description: |
* Opens a Server-Sent Events stream for the authenticated user's
* **selected company**. Clients receive named signals when another
* request successfully mutates shared data for that company
* (including the same browser's other tabs).
*
* Use `EventSource` with credentials so the session cookie is sent:
*
* ```js
* const es = new EventSource('https://…/api/events', { withCredentials: true });
* es.addEventListener('category', () => { refetchCategoryTree(); });
* es.addEventListener('articles', () => { refetchArticleIndex(); });
* es.addEventListener('article-42000045', () => { refetchArticle('42000045'); });
* ```
*
* Keep-alive comments (`: keepalive`) are sent roughly every 25s.
* Reconnect after changing the selected company (the stream is bound
* to the company at connect time).
*
* ## Signals
*
* | Signal | Emitted after successful |
* |--------|--------------------------|
* | `category` | `POST /category`, `PATCH /category/{id}`, `PUT /category/order`, `DELETE /category/{id}`, `POST /category/{id}/image`, `DELETE /category/{id}/image` |
* | `articles` | `POST /article`, `PATCH /article/{sku}`, `DELETE /article/{sku}` |
* | `article-<sku>` | `PUT /article/{sku}/weight`, `PUT /article/{sku}/prices`, `PUT /article/{sku}/eans`, `PUT /article/{sku}/categories`, `PUT /article/{sku}/brand`, `PUT /article/{sku}/images/order`, `POST /article/{sku}/image`, `DELETE /article/{sku}/image/{fullHash}` |
*
* Signals are only sent when the mutation actually succeeds (2xx).
* Failed or no-op validation errors do not emit. The `article-<sku>`
* event name uses the concrete SKU (e.g. `article-42000045`).
* security:
* - cookieAuth: []
* x-markdown: events.md
* responses:
* 200:
* description: |
* SSE stream (`text/event-stream`). Each signal is an SSE event
* whose name is the signal id and whose data is `{}`.
* content:
* text/event-stream:
* schema:
* type: string
* example: |
* event: category
* data: {}
*
* event: articles
* data: {}
*
* event: article-42000045
* data: {}
* 400:
* description: No company selected
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 401:
* description: Unauthorized
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
app.get(`${basePath}/events`, (req, res) => {
const companyId = req.user.selectedCompanyId;
if (companyId == null) {
return res.status(400).json({ error: 'No company selected' });
}
req.socket.setTimeout(0);
res.setTimeout(0);
res.status(200);
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
res.flushHeaders?.();
res.write(': connected\n\n');
subscribe(res, { companyId, userId: req.user.id });
});
}