Files
dashback/src/api/routes/stock.js
2026-10-10 02:08:10 +02:00

139 lines
4.9 KiB
JavaScript

import * as db from '../../db/stock.js';
import { emit } from '../sse.js';
// #region Helpers
function requireSelectedCompany(req) {
const companyId = req.user?.selectedCompanyId;
if (companyId == null) {
return { error: 'No company selected' };
}
return { companyId };
}
function stockErrorStatus(error) {
if (error.message === 'No company selected') return 400;
if (error.message === 'Not authorized') return 403;
if (error.message === 'Company not found') return 404;
if (error.message === 'Article not found') return 404;
if (error.message === 'Warehouse not found') return 404;
if (error.message?.includes('SKU required')) return 400;
if (error.message?.includes('Warehouse required')) return 400;
if (error.message?.includes('Amount must be')) return 400;
if (error.message?.includes('Invalid amount')) return 400;
if (error.message === 'No items to adjust') return 400;
if (error.message?.includes('cannot have stock') || error.message?.includes('A parent article cannot have') || error.message?.includes('parent article') || error.message?.includes('Stückliste')) return 400;
if (error.message?.includes('Stock tracking is disabled')) return 409;
return 500;
}
function emitStockEvents(companyId, body, result) {
emit('stock', { companyId });
emit('ledger', { companyId });
emit('articles', { companyId });
if (body.sku) {
emit(`article-${body.sku}`, { companyId });
}
if (Array.isArray(body.lines)) {
for (const line of body.lines) {
if (line?.sku) {
emit(`article-${line.sku}`, { companyId });
}
}
}
if (Array.isArray(result?.lines)) {
for (const line of result.lines) {
if (line?.sku) {
emit(`article-${line.sku}`, { companyId });
}
}
}
}
// #endregion
/**
* Registers stock adjustment routes for the authenticated user's selected company.
* All operations append to the append-only ledger under an implicit "adjustment" manifest.
*
* @param {import('express').Application} app
* @param {string} [basePath='']
*/
export function register(app, basePath = '') {
/**
* @openapi
* /stock/adjust:
* post:
* tags: [Stock]
* summary: Adjust stock manually
* description: |
* Writes signed (+ or -) entries to the append-only ledger under an implicit manifest
* of type "adjustment", allocating a number from the "adjustment" number scheme.
*
* **Note:** `sku` must be a string (e.g. `"25"`), not a number. For single-item adjustments, provide `sku` and `amount` at top-level. For batch adjustments, provide `lines: [{ sku, amount, ... }]`.
* security:
* - cookieAuth: []
* x-signals: [stock, ledger, articles, article-<sku>]
* x-markdown: stock/adjust.md
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/StockAdjustmentInput'
* responses:
* 201:
* description: Stock adjusted successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/StockAdjustmentResult'
* 400:
* description: Missing fields, invalid amount, parent article cannot have stock, or 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: Article or warehouse not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
// #region POST /stock/adjust
app.post(`${basePath}/stock/adjust`, async (req, res) => {
const selected = requireSelectedCompany(req);
if (selected.error) {
return res.status(400).json({ error: selected.error });
}
try {
const result = await db.adjust(req.user.id, req.body ?? {});
emitStockEvents(selected.companyId, req.body ?? {}, result);
res.status(201).json(result);
} catch (error) {
const status = stockErrorStatus(error);
if (status === 500) console.error('Stock adjust failed:', error);
res.status(status).json({ error: error.message });
}
});
// #endregion
}