This commit is contained in:
seb
2026-10-16 22:09:15 +02:00
parent 188cd71f63
commit d7f7d669f9
13 changed files with 446 additions and 171 deletions

View File

@@ -168,10 +168,12 @@ function deliveryErrorStatus(error) {
if (error.message === 'Attachment not found') return 404;
if (error.message === 'File not found') return 404;
if (error.message === 'Supplier not found') return 404;
if (error.message === 'Warehouse not found') return 404;
if (error.message === 'Invalid supplierId') return 400;
if (error.message === 'Article not found') return 404;
if (error.message === 'Invalid delivery') return 400;
if (error.message === 'Invalid lines') return 400;
if (error.message === 'Delivery has no lines') return 400;
if (error.message === 'Invalid file') return 400;
if (error.message === 'Invalid JSON in "data" field') return 400;
if (error.message === 'Only PDF or text files are accepted as attachments') return 400;
@@ -204,13 +206,46 @@ export function register(app, basePath = '') {
* summary: List deliveries
* description: |
* Lists goods receipts (`manifest` rows with `type = 'delivery'`)
* for the authenticated user's selected company.
* for the authenticated user's selected company. Supports pagination and filtering.
* security:
* - cookieAuth: []
* x-markdown: delivery/list.md
* parameters:
* - name: offset
* in: query
* schema:
* type: integer
* default: 0
* description: Number of records to skip
* - name: limit
* in: query
* schema:
* type: integer
* default: 50
* description: Number of records to return (1-1000)
* - name: search
* in: query
* schema:
* type: string
* description: Substring match for delivery number, external number, or supplier name
* - name: onlyUnbooked
* in: query
* schema:
* type: boolean
* description: When true, returns only deliveries with unbooked stock items
* - name: supplierId
* in: query
* schema:
* type: integer
* description: Filter by supplier entity id
* - name: seekMonths
* in: query
* schema:
* type: integer
* description: Negative integer cutoff months ago (e.g. -1)
* responses:
* 200:
* description: Delivery list
* description: Delivery list (windowed when pagination/filters are used)
* content:
* application/json:
* schema:
@@ -220,6 +255,14 @@ export function register(app, basePath = '') {
* type: array
* items:
* $ref: '#/components/schemas/DeliverySummary'
* total:
* type: integer
* unfilteredTotal:
* type: integer
* offset:
* type: integer
* limit:
* type: integer
* 400:
* description: No company selected
* content:
@@ -358,9 +401,67 @@ export function register(app, basePath = '') {
return res.status(400).json({ error: selected.error });
}
const rawOffset = req.query.offset;
const rawLimit = req.query.limit;
let offset = 0;
let limit = 50;
if (rawOffset !== undefined) {
offset = parseInt(rawOffset, 10);
if (!Number.isInteger(offset) || offset < 0) {
return res.status(400).json({ error: 'offset must be an integer >= 0' });
}
}
if (rawLimit !== undefined) {
limit = parseInt(rawLimit, 10);
if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {
return res.status(400).json({ error: 'limit must be an integer between 1 and 1000' });
}
}
const search = typeof req.query.search === 'string' && req.query.search.trim() !== ''
? req.query.search.trim()
: undefined;
const onlyUnbooked = req.query.onlyUnbooked === 'true';
let supplierId = undefined;
if (req.query.supplierId !== undefined && req.query.supplierId !== '') {
const parsedSupplier = parseInt(req.query.supplierId, 10);
if (!Number.isInteger(parsedSupplier) || parsedSupplier <= 0) {
return res.status(400).json({ error: 'supplierId must be a positive integer' });
}
supplierId = parsedSupplier;
}
let seekMonths = undefined;
if (req.query.seekMonths !== undefined && req.query.seekMonths !== '') {
const parsedSeek = parseInt(req.query.seekMonths, 10);
if (!Number.isInteger(parsedSeek)) {
return res.status(400).json({ error: 'seekMonths must be an integer' });
}
seekMonths = parsedSeek;
}
const isPaged = rawOffset !== undefined || rawLimit !== undefined || search !== undefined || onlyUnbooked || supplierId !== undefined || seekMonths !== undefined;
try {
const deliveries = await db.list(req.user.id);
res.status(200).json({ deliveries });
if (isPaged) {
const result = await db.list(req.user.id, {
offset,
limit,
search,
onlyUnbooked: onlyUnbooked ? true : undefined,
supplierId,
seekMonths,
});
res.status(200).json(result);
} else {
const deliveries = await db.list(req.user.id);
res.status(200).json({ deliveries: Array.isArray(deliveries) ? deliveries : (deliveries.deliveries || []) });
}
} catch (error) {
res.locals.error = error;
const status = deliveryErrorStatus(error);
@@ -369,6 +470,21 @@ export function register(app, basePath = '') {
}
});
app.post(`${basePath}/delivery/rebuild-summaries`, async (req, res) => {
const selected = requireSelectedCompany(req);
if (selected.error) {
return res.status(400).json({ error: selected.error });
}
try {
const result = await db.rebuildSummaries(req.user.id);
res.status(200).json(result);
} catch (error) {
const status = deliveryErrorStatus(error);
if (status === 500) console.error('Rebuild delivery summaries failed:', error);
res.status(status).json({ error: status === 500 ? 'Internal server error' : error.message });
}
});
// #endregion
// #region POST /delivery
@@ -749,6 +865,8 @@ export function register(app, basePath = '') {
// #endregion
/**
* @openapi
* /delivery/{id}/file/{fileId}:

View File

@@ -30,85 +30,6 @@ function ledgerErrorStatus(error) {
* @param {string} [basePath='']
*/
export function register(app, basePath = '') {
/**
* @openapi
* /ledger:
* post:
* tags: [Ledger]
* summary: Add ledger entry
* description: |
* Appends a new entry to the append-only ledger table.
* `hash_version` is fixed to 1. `prev_hash` is cryptographically chained:
* for the genesis row it defaults to `TODO_TSE_BASED_INITHASH`, and for subsequent rows
* it is the SHA-512 hex hash of the canonical JSON representation of the previous highest-id entry.
* Requires authentication and membership in the company owning the referenced manifest article.
* security:
* - cookieAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/LedgerEntryInput'
* example:
* manifestarticle_id: 1
* transaction_type: 'PAYMENT'
* amount: 150.00
* transaction_text: 'Payment received for invoice'
* responses:
* 201:
* description: Ledger entry added successfully
* content:
* application/json:
* schema:
* type: object
* properties:
* ledger:
* $ref: '#/components/schemas/LedgerEntry'
* 400:
* description: Invalid ledger entry 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: Manifest article or company not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
// #region POST /ledger
app.post(`${basePath}/ledger`, async (req, res) => {
const selected = requireSelectedCompany(req);
if (selected.error) {
return res.status(400).json({ error: selected.error });
}
try {
const ledger = await db.add(req.user.id, req.body ?? {});
res.status(201).json({ ledger });
} catch (error) {
const status = ledgerErrorStatus(error);
if (status === 500) console.error('Add ledger entry failed:', error);
res.status(status).json({ error: error.message });
}
});
// #endregion
/**
* @openapi

View File

@@ -135,4 +135,146 @@ export function register(app, basePath = '') {
});
// #endregion
/**
* @openapi
* /stock/accept:
* post:
* tags: [Stock]
* summary: Accept delivery manifest item(s)
* description: |
* Books acceptance for a delivery manifest item on the ledger (warehouse_id = null).
* If the connected article has stock tracking enabled, an adjustment entry is also
* booked to adjust physical stock in the target warehouse.
* If line amount is negative, books as a delivery return (outgoing).
* security:
* - cookieAuth: []
* x-signals: [stock, ledger, articles, delivery]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* manifestarticleId:
* type: integer
* description: Manifest article ID of the delivery line
* warehouseId:
* type: integer
* description: Optional warehouse ID for inventory intake
* items:
* type: array
* items:
* type: object
* required: [manifestarticleId]
* properties:
* manifestarticleId:
* type: integer
* warehouseId:
* type: integer
* responses:
* 200:
* description: Delivery item(s) accepted successfully
* 400:
* description: Validation error or no company selected
* 404:
* description: Manifest article or warehouse not found
* 409:
* description: Delivery line already accepted on ledger
*/
// #region POST /stock/accept
app.post(`${basePath}/stock/accept`, async (req, res) => {
const selected = requireSelectedCompany(req);
if (selected.error) {
return res.status(400).json({ error: selected.error });
}
try {
const result = await db.accept(req.user.id, req.body ?? {});
emit('stock', { companyId: selected.companyId });
emit('ledger', { companyId: selected.companyId });
emit('articles', { companyId: selected.companyId });
emit('delivery', { companyId: selected.companyId });
res.status(200).json(result);
} catch (error) {
const status = stockErrorStatus(error);
if (status === 500) console.error('Stock accept failed:', error);
res.status(status).json({ error: error.message });
}
});
// #endregion
/**
* @openapi
* /stock/ship:
* post:
* tags: [Stock]
* summary: Ship shipment manifest item(s)
* description: |
* Books shipment for a shipment manifest item on the ledger (warehouse_id = null).
* If the connected article has stock tracking enabled, an adjustment entry is also
* booked to deduct physical stock from the target warehouse.
* If line amount is negative, books as a customer retoure (incoming).
* security:
* - cookieAuth: []
* x-signals: [stock, ledger, articles, shipping]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* manifestarticleId:
* type: integer
* description: Manifest article ID of the shipment line
* warehouseId:
* type: integer
* description: Optional warehouse ID for inventory deduction
* items:
* type: array
* items:
* type: object
* required: [manifestarticleId]
* properties:
* manifestarticleId:
* type: integer
* warehouseId:
* type: integer
* responses:
* 200:
* description: Shipment item(s) shipped successfully
* 400:
* description: Validation error or no company selected
* 404:
* description: Manifest article or warehouse not found
* 409:
* description: Shipment line already shipped on ledger
*/
// #region POST /stock/ship
app.post(`${basePath}/stock/ship`, async (req, res) => {
const selected = requireSelectedCompany(req);
if (selected.error) {
return res.status(400).json({ error: selected.error });
}
try {
const result = await db.ship(req.user.id, req.body ?? {});
emit('stock', { companyId: selected.companyId });
emit('ledger', { companyId: selected.companyId });
emit('articles', { companyId: selected.companyId });
emit('shipping', { companyId: selected.companyId });
res.status(200).json(result);
} catch (error) {
const status = stockErrorStatus(error);
if (status === 500) console.error('Stock ship failed:', error);
res.status(status).json({ error: error.message });
}
});
// #endregion
}