diff --git a/docs/api/README.md b/docs/api/README.md index 120e37b..c5d532c 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -159,8 +159,7 @@ Generated from `@openapi` annotations in [`src/api/routes/`](../../src/api/route | [`routes/labeltemplate/get.md`](routes/labeltemplate/get.md) | `GET /labeltemplate/{id}` | | [`routes/labeltemplate/update.md`](routes/labeltemplate/update.md) | `PATCH /labeltemplate/{id}` | | [`routes/labeltemplate/update.md`](routes/labeltemplate/update.md) | `PUT /labeltemplate/{id}` | -| [`routes/ledger.get.md`](routes/ledger.get.md) | `GET /ledger` | -| [`routes/ledger.post.md`](routes/ledger.post.md) | `POST /ledger` | +| [`routes/ledger.md`](routes/ledger.md) | `GET /ledger` | | [`routes/ledger/manifestarticle/_manifestarticleId.md`](routes/ledger/manifestarticle/_manifestarticleId.md) | `GET /ledger/manifestarticle/{manifestarticleId}` | | [`routes/ledger/sku/_sku.md`](routes/ledger/sku/_sku.md) | `GET /ledger/sku/{sku}` | | [`routes/mcp.md`](routes/mcp.md) | `POST /mcp` | @@ -248,7 +247,9 @@ Generated from `@openapi` annotations in [`src/api/routes/`](../../src/api/route | [`routes/shipping/_id/package.get.md`](routes/shipping/_id/package.get.md) | `GET /shipping/{id}/package` | | [`routes/shipping/_id/package.post.md`](routes/shipping/_id/package.post.md) | `POST /shipping/{id}/package` | | [`routes/smallthumb/get.md`](routes/smallthumb/get.md) | `GET /smallthumb/{fullHash}` | +| [`routes/stock/accept.md`](routes/stock/accept.md) | `POST /stock/accept` | | [`routes/stock/adjust.md`](routes/stock/adjust.md) | `POST /stock/adjust` | +| [`routes/stock/ship.md`](routes/stock/ship.md) | `POST /stock/ship` | | [`routes/supplier/list.md`](routes/supplier/list.md) | `GET /supplier` | | [`routes/supplier/create.md`](routes/supplier/create.md) | `POST /supplier` | | [`routes/supplier/delete.md`](routes/supplier/delete.md) | `DELETE /supplier/{id}` | @@ -291,13 +292,13 @@ 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`, `POST /stock/adjust` | -| `articles` | `POST /article`, `DELETE /article/{sku}`, `PATCH /article/{sku}`, `DELETE /category/{id}`, `POST /stock/adjust` | +| `articles` | `POST /article`, `DELETE /article/{sku}`, `PATCH /article/{sku}`, `DELETE /category/{id}`, `POST /stock/accept`, `POST /stock/adjust`, `POST /stock/ship` | | `attributename` | `POST /attributename`, `PUT /attributename/order`, `DELETE /attributename/{id}`, `PATCH /attributename/{id}`, `DELETE /attributevalue/{id}/image`, `POST /attributevalue/{id}/image` | | `brand` | `POST /brand`, `DELETE /brand/{id}`, `PATCH /brand/{id}`, `DELETE /brand/{id}/image`, `POST /brand/{id}/image` | | `category` | `POST /category`, `PUT /category/order`, `DELETE /category/{id}`, `PATCH /category/{id}`, `DELETE /category/{id}/image`, `POST /category/{id}/image` | -| `delivery` | `DELETE /delivery/{id}/file/{fileId}`, `POST /delivery/{id}/pdf` | +| `delivery` | `DELETE /delivery/{id}/file/{fileId}`, `POST /delivery/{id}/pdf`, `POST /stock/accept` | | `labeltemplate` | `POST /labeltemplate`, `DELETE /labeltemplate/{id}`, `PATCH /labeltemplate/{id}`, `PUT /labeltemplate/{id}` | -| `ledger` | `POST /stock/adjust` | +| `ledger` | `POST /stock/accept`, `POST /stock/adjust`, `POST /stock/ship` | | `modelconversation` | `POST /modelconversation`, `DELETE /modelconversation/{id}` | | `modelconversation-` | `POST /modelconversation/{id}/message` | | `order` | `DELETE /order/{id}/file/{fileId}`, `POST /order/{id}/pdf`, `PATCH /shipment/{id}`, `DELETE /shipment/{id}/file/{fileId}` | @@ -305,7 +306,8 @@ Clients subscribe via [`GET /events`](routes/events.md) (`text/event-stream`). A | `propertyname` | `POST /propertyname`, `PUT /propertyname/order`, `DELETE /propertyname/{id}`, `PATCH /propertyname/{id}` | | `quote` | `DELETE /quote/{id}/file/{fileId}`, `POST /quote/{id}/pdf` | | `shipment` | `PATCH /shipment/{id}`, `DELETE /shipment/{id}/file/{fileId}`, `POST /shipment/{id}/pdf` | -| `stock` | `POST /stock/adjust` | +| `shipping` | `POST /stock/ship` | +| `stock` | `POST /stock/accept`, `POST /stock/adjust`, `POST /stock/ship` | | `vfs` | `POST /vfs/applets/restore`, `POST /vfs/mkdir`, `POST /vfs/rename`, `POST /vfs/skills/restore`, `POST /vfs/upload`, `DELETE /vfs/{*path}`, `POST /vfs/{*path}`, `PUT /vfs/{*path}` | | `warehouse` | `POST /warehouse`, `PUT /warehouse/order`, `DELETE /warehouse/{id}`, `PUT /warehouse/{id}` | diff --git a/docs/api/routes-all.md b/docs/api/routes-all.md index ad7494c..1004292 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 249 API endpoints across all modules. +Overview of all 250 API endpoints across all modules. ### Notation @@ -392,8 +392,8 @@ _none_ ### Section: /delivery #### List deliveries — `GET /delivery` -_none_ -- Returns: `200 { deliveries: { id: int, number: str, type: str, supplierId: int|null, date: str, externalNumber?: str|null, createdAt?: str, ledger?: T50 }[] }` +- Params: `query: offset?: int, limit?: int, search?: str, onlyUnbooked?: bool, supplierId?: int, seekMonths?: int` +- Returns: `200 { deliveries: { id: int, number: str, type: str, supplierId: int|null, date: str, externalNumber?: str|null, createdAt?: str, ledger?: T50 }[], total: int, unfilteredTotal: int, offset: int, limit: int }` #### Create delivery — `POST /delivery` - Params: `body: { externalNumber: str, date: str, lines: T33[], supplierId?: int|null, files?: { mimetype: str, name: str, content: str, sort?: int, size?: int, hash?: str, created?: str, modified?: str, meta?: { [k]: str } }[] }` - Returns: `201 T9` @@ -521,9 +521,6 @@ _none_ #### Query ledger by manifest article ID or SKU — `GET /ledger` - Params: `query: manifestarticle_id?: int, sku?: str, transaction_type?: str` - Returns: `200 T21` -#### Add ledger entry — `POST /ledger` -- Params: `body: { manifestarticle_id: int, transaction_type: str, amount: num, transaction_text: str }` -- Returns: `201 { ledger: T22 }` #### Query ledger by manifest article ID — `GET /ledger/manifestarticle/{manifestarticleId}` - Params: `manifestarticleId: int, query: transaction_type?: str` - Returns: `200 T21` @@ -842,9 +839,15 @@ _none_ ### Section: /stock +#### Accept delivery manifest item(s) — `POST /stock/accept` +- Params: `body: { manifestarticleId?: int, warehouseId?: int, items?: { manifestarticleId: int, warehouseId?: int }[] }` +- Returns: `200` #### Adjust stock manually — `POST /stock/adjust` - Params: `body: { sku?: str, warehouseId?: int, amount?: num, text?: str|null, lines?: { sku: str, amount: num, warehouseId?: int, text?: str }[] }` - Returns: `201 { manifest: { id: int, number: str, type: str, date: str, createdAt: str }, lines: { manifestarticle_id: int, sku: str, name: str, warehouse_id: int, amount: num, text: str }[], ledger: T22[] }` +#### Ship shipment manifest item(s) — `POST /stock/ship` +- Params: `body: { manifestarticleId?: int, warehouseId?: int, items?: { manifestarticleId: int, warehouseId?: int }[] }` +- Returns: `200` ### Section: /supplier diff --git a/docs/api/routes.md b/docs/api/routes.md index 36448b4..756765e 100644 --- a/docs/api/routes.md +++ b/docs/api/routes.md @@ -1,6 +1,6 @@ # Dash API Routes Overview -Overview of all 174 API endpoints across all modules. +Overview of all 175 API endpoints across all modules. ### Notation @@ -310,8 +310,8 @@ _none_ ### Section: /delivery #### List deliveries — `GET /delivery` -_none_ -- Returns: `200 { deliveries: { id: int, number: str, type: str, supplierId: int|null, date: str, externalNumber?: str|null, createdAt?: str, ledger?: T42 }[] }` +- Params: `query: offset?: int, limit?: int, search?: str, onlyUnbooked?: bool, supplierId?: int, seekMonths?: int` +- Returns: `200 { deliveries: { id: int, number: str, type: str, supplierId: int|null, date: str, externalNumber?: str|null, createdAt?: str, ledger?: T42 }[], total: int, unfilteredTotal: int, offset: int, limit: int }` #### Create delivery — `POST /delivery` - Params: `body: { externalNumber: str, date: str, lines: T27[], supplierId?: int|null, files?: { mimetype: str, name: str, content: str, sort?: int, size?: int, hash?: str, created?: str, modified?: str, meta?: { [k]: str } }[] }` - Returns: `201 T9` @@ -402,9 +402,6 @@ _none_ #### Query ledger by manifest article ID or SKU — `GET /ledger` - Params: `query: manifestarticle_id?: int, sku?: str, transaction_type?: str` - Returns: `200 T17` -#### Add ledger entry — `POST /ledger` -- Params: `body: { manifestarticle_id: int, transaction_type: str, amount: num, transaction_text: str }` -- Returns: `201 { ledger: T18 }` #### Query ledger by manifest article ID — `GET /ledger/manifestarticle/{manifestarticleId}` - Params: `manifestarticleId: int, query: transaction_type?: str` - Returns: `200 T17` @@ -594,9 +591,15 @@ _none_ ### Section: /stock +#### Accept delivery manifest item(s) — `POST /stock/accept` +- Params: `body: { manifestarticleId?: int, warehouseId?: int, items?: { manifestarticleId: int, warehouseId?: int }[] }` +- Returns: `200` #### Adjust stock manually — `POST /stock/adjust` - Params: `body: { sku?: str, warehouseId?: int, amount?: num, text?: str|null, lines?: { sku: str, amount: num, warehouseId?: int, text?: str }[] }` - Returns: `201 { manifest: { id: int, number: str, type: str, date: str, createdAt: str }, lines: { manifestarticle_id: int, sku: str, name: str, warehouse_id: int, amount: num, text: str }[], ledger: T18[] }` +#### Ship shipment manifest item(s) — `POST /stock/ship` +- Params: `body: { manifestarticleId?: int, warehouseId?: int, items?: { manifestarticleId: int, warehouseId?: int }[] }` +- Returns: `200` ### Section: /supplier diff --git a/docs/api/routes/delivery/list.md b/docs/api/routes/delivery/list.md index 23f2c32..16402e2 100644 --- a/docs/api/routes/delivery/list.md +++ b/docs/api/routes/delivery/list.md @@ -5,12 +5,23 @@ Protected. Requires a valid session cookie (`credentials: 'include'`). List deliveries 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. +## Query parameters + +| Param | Required | Type | Description | +|-------|----------|------|-------------| +| `offset` | no | integer | Number of records to skip | +| `limit` | no | integer | Number of records to return (1-1000) | +| `search` | no | string | Substring match for delivery number, external number, or supplier name | +| `onlyUnbooked` | no | boolean | When true, returns only deliveries with unbooked stock items | +| `supplierId` | no | integer | Filter by supplier entity id | +| `seekMonths` | no | integer | Negative integer cutoff months ago (e.g. -1) | + ## Response `200` -Delivery list +Delivery list (windowed when pagination/filters are used) ```json { @@ -28,7 +39,11 @@ Delivery list "completelyOnLedgerPositions": 1 } } - ] + ], + "total": 1, + "unfilteredTotal": 1, + "offset": 1, + "limit": 1 } ``` diff --git a/docs/api/routes/ledger.get.md b/docs/api/routes/ledger.md similarity index 100% rename from docs/api/routes/ledger.get.md rename to docs/api/routes/ledger.md diff --git a/docs/api/routes/ledger.post.md b/docs/api/routes/ledger.post.md deleted file mode 100644 index e22e16e..0000000 --- a/docs/api/routes/ledger.post.md +++ /dev/null @@ -1,63 +0,0 @@ -# `POST /ledger` - -Protected. Requires a valid session cookie (`credentials: 'include'`). - -Add ledger entry - -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. - - -## Body (JSON) - -| Field | Required | Type | Description | -|-------|----------|------|-------------| -| `manifestarticle_id` | yes | integer | References manifestarticle.id | -| `transaction_type` | yes | string | Transaction identifier / type (max 100 chars) | -| `amount` | yes | number | Movement amount | -| `transaction_text` | yes | string | Transaction memo / details | - -```json -{ - "manifestarticle_id": 1, - "transaction_type": "…", - "amount": 1, - "transaction_text": "…" -} -``` - -## Response `201` - -Ledger entry added successfully - -```json -{ - "ledger": { - "id": 1, - "manifestarticle_id": 1, - "transaction_type": "…", - "amount": 1, - "transaction_text": "…", - "hash_version": 1, - "prev_hash": "…", - "sku": "…", - "created_at": "2026-08-10T00:00:00.000Z" - } -} -``` - -## Errors - -| Status | Description | -|--------|-------------| -| 400 | Invalid ledger entry or no company selected — `{"error":"…"}` | -| 401 | Unauthorized — `{"error":"…"}` | -| 403 | Not authorized — `{"error":"…"}` | -| 404 | Manifest article or company not found — `{"error":"…"}` | - ---- - -_Generated from `@openapi` JSDoc. Do not edit by hand — run `npm run docs:api`._ diff --git a/docs/api/routes/stock/accept.md b/docs/api/routes/stock/accept.md new file mode 100644 index 0000000..e35afe8 --- /dev/null +++ b/docs/api/routes/stock/accept.md @@ -0,0 +1,54 @@ +# `POST /stock/accept` + +Protected. Requires a valid session cookie (`credentials: 'include'`). + +Accept delivery manifest item(s) + +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). + + +## Body (JSON) + +| Field | Required | Type | Description | +|-------|----------|------|-------------| +| `manifestarticleId` | no | integer | Manifest article ID of the delivery line | +| `warehouseId` | no | integer | Optional warehouse ID for inventory intake | +| `items` | no | object[] | | +| `items[].manifestarticleId` | yes | integer | | +| `items[].warehouseId` | no | integer | | + +```json +{ + "manifestarticleId": 1, + "warehouseId": 1, + "items": [ + { + "manifestarticleId": 1, + "warehouseId": 1 + } + ] +} +``` + +## Signals + +On success, emits SSE signals: `stock`, `ledger`, `articles`, `delivery` (see [`GET /events`](../events.md)). + +## Response `200` + +Delivery item(s) accepted successfully + +## Errors + +| Status | Description | +|--------|-------------| +| 400 | Validation error or no company selected | +| 404 | Manifest article or warehouse not found | +| 409 | Delivery line already accepted on ledger | + +--- + +_Generated from `@openapi` JSDoc. Do not edit by hand — run `npm run docs:api`._ diff --git a/docs/api/routes/stock/ship.md b/docs/api/routes/stock/ship.md new file mode 100644 index 0000000..2b05758 --- /dev/null +++ b/docs/api/routes/stock/ship.md @@ -0,0 +1,54 @@ +# `POST /stock/ship` + +Protected. Requires a valid session cookie (`credentials: 'include'`). + +Ship shipment manifest item(s) + +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). + + +## Body (JSON) + +| Field | Required | Type | Description | +|-------|----------|------|-------------| +| `manifestarticleId` | no | integer | Manifest article ID of the shipment line | +| `warehouseId` | no | integer | Optional warehouse ID for inventory deduction | +| `items` | no | object[] | | +| `items[].manifestarticleId` | yes | integer | | +| `items[].warehouseId` | no | integer | | + +```json +{ + "manifestarticleId": 1, + "warehouseId": 1, + "items": [ + { + "manifestarticleId": 1, + "warehouseId": 1 + } + ] +} +``` + +## Signals + +On success, emits SSE signals: `stock`, `ledger`, `articles`, `shipping` (see [`GET /events`](../events.md)). + +## Response `200` + +Shipment item(s) shipped successfully + +## Errors + +| Status | Description | +|--------|-------------| +| 400 | Validation error or no company selected | +| 404 | Manifest article or warehouse not found | +| 409 | Shipment line already shipped on ledger | + +--- + +_Generated from `@openapi` JSDoc. Do not edit by hand — run `npm run docs:api`._ diff --git a/src/api/routes/delivery.js b/src/api/routes/delivery.js index 80c1cbe..55ce252 100644 --- a/src/api/routes/delivery.js +++ b/src/api/routes/delivery.js @@ -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}: diff --git a/src/api/routes/ledger.js b/src/api/routes/ledger.js index 96e9e2c..2cb0973 100644 --- a/src/api/routes/ledger.js +++ b/src/api/routes/ledger.js @@ -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 diff --git a/src/api/routes/stock.js b/src/api/routes/stock.js index 6d76f37..c447be9 100644 --- a/src/api/routes/stock.js +++ b/src/api/routes/stock.js @@ -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 } diff --git a/src/db/delivery.js b/src/db/delivery.js index cbf05bb..48941bb 100644 --- a/src/db/delivery.js +++ b/src/db/delivery.js @@ -10,15 +10,27 @@ async function formatDelivery(delivery) { return delivery; } -export async function list(googleAuthId) { +export async function list(googleAuthId, opts) { const store = await getStore(); - const result = await store.delivery.list(googleAuthId); + const result = await store.delivery.list(googleAuthId, opts); if (Array.isArray(result)) { return Promise.all(result.map(formatDelivery)); } + if (result && Array.isArray(result.deliveries)) { + const deliveries = await Promise.all(result.deliveries.map(formatDelivery)); + return { + ...result, + deliveries, + }; + } return result; } +export async function rebuildSummaries(googleAuthId) { + const store = await getStore(); + return store.delivery.rebuildSummaries(googleAuthId); +} + export async function getById(googleAuthId, id) { const store = await getStore(); const delivery = await store.delivery.getById(googleAuthId, id); @@ -42,6 +54,12 @@ export async function remove(googleAuthId, id) { return store.delivery.delete(googleAuthId, id); } +export async function book(googleAuthId, data) { + const store = await getStore(); + const delivery = await store.delivery.book(googleAuthId, data); + return formatDelivery(delivery); +} + export async function getFile(googleAuthId, deliveryId, fileId) { const store = await getStore(); return store.manifestattachment.getById(googleAuthId, deliveryId, fileId); @@ -63,5 +81,3 @@ export async function removeAttachment(googleAuthId, deliveryId, fileId) { const store = await getStore(); return store.manifestattachment.remove(googleAuthId, deliveryId, fileId); } - - diff --git a/src/db/stock.js b/src/db/stock.js index 31864e0..be7c267 100644 --- a/src/db/stock.js +++ b/src/db/stock.js @@ -4,3 +4,13 @@ export async function adjust(googleAuthId, data) { const store = await getStore(); return store.stock.adjust(googleAuthId, data); } + +export async function accept(googleAuthId, data) { + const store = await getStore(); + return store.stock.accept(googleAuthId, data); +} + +export async function ship(googleAuthId, data) { + const store = await getStore(); + return store.stock.ship(googleAuthId, data); +}