import * as db from '../../db/shipment.js'; import { createAndAttachManifestPdf } from '../../services/manifestPdf.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 parsePositiveInt(value, field) { const id = Number(value); if (!Number.isInteger(id) || id <= 0) { return { error: `${field} is required` }; } return { id }; } function shipmentErrorStatus(error) { if (error.message === 'No company selected') return 400; if (error.message === 'Not authorized') return 403; if (error.message?.endsWith(' not found')) return 404; if ( error.message?.endsWith(' required') || error.message?.startsWith('Article (') || error.message?.includes('Invalid lines') || error.message === 'Invalid state' || error.message === 'Invalid offset' || error.message === 'Invalid limit' || error.message === 'Invalid seekMonths' ) { return 400; } if ( error.message?.startsWith('Shipment amount exceeds') || error.message?.includes('cannot be deleted') || error.message?.includes('cannot be undone') || error.message?.includes('already shipped') ) { return 409; } return 500; } function emitShipmentEvents(companyId) { emit('order', { companyId }); emit('shipment', { companyId }); } // #endregion /** * Registers shipment routes (shipments belong to an order). * @param {import('express').Application} app * @param {string} [basePath=''] */ export function register(app, basePath = '') { /** * @openapi * /order/{id}/shipment: * get: * tags: [Shipment] * summary: List shipments of an order * description: Lists all shipment manifests belonging to the specified order. * security: * - cookieAuth: [] * parameters: * - in: path * name: id * required: true * schema: * type: integer * description: Order ID * responses: * 200: * description: List of shipments * content: * application/json: * schema: * type: object * properties: * shipments: * type: array * items: * $ref: '#/components/schemas/Shipment' * 400: * description: Invalid ID or no company selected * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 401: * description: Unauthorized * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 404: * description: Order not found * content: * application/json: * schema: * $ref: '#/components/schemas/Error' */ // #region GET /order/:id/shipment app.get(`${basePath}/order/:id/shipment`, async (req, res) => { const selected = requireSelectedCompany(req); if (selected.error) { return res.status(400).json({ error: selected.error }); } const parsedId = parsePositiveInt(req.params.id, 'id'); if (parsedId.error) { return res.status(400).json({ error: parsedId.error }); } try { const shipments = await db.listByOrderId(req.user.id, parsedId.id); res.status(200).json({ shipments }); } catch (error) { const status = shipmentErrorStatus(error); if (status === 500) console.error('List shipments failed:', error); res.status(status).json({ error: error.message }); } }); // #endregion /** * @openapi * /order/{id}/shipment: * post: * tags: [Shipment] * summary: Create shipment for an order * description: | * Creates a new shipment manifest (Lieferschein) for an order containing one, some, or all items from the order. * If `lines` is omitted or empty, all remaining unshipped items from the order are included automatically. * On individual line items, `amount` is optional and defaults to the remaining unshipped quantity for that article. * Auto-assigns the shipment number formatted as ``, e.g. `AUF-000001-L-1`. * Updates the materialized `ordersummary` table (`shipped_quantity`, `is_shipped`) and emits SSE events * (`order`, `shipment`) so that the order list and summary tables are rerendered in real time. * security: * - cookieAuth: [] * parameters: * - in: path * name: id * required: true * schema: * type: integer * description: Order ID * requestBody: * required: false * content: * application/json: * schema: * type: object * properties: * date: * type: string * format: date * description: Optional shipment date (defaults to current date) * externalNumber: * type: string * description: Optional external delivery note reference (defaults to order.externalNumber or order.number) * lines: * type: array * description: Optional positions to ship. If omitted, all remaining unshipped items are shipped. * items: * type: object * required: [sku] * properties: * sku: * type: string * description: Article SKU * amount: * type: number * description: Quantity to ship. Defaults to remaining unshipped quantity for this SKU. * name: * type: string * pu: * type: number * net: * type: number * rebate: * type: number * taxrate: * type: number * comment: * type: string * responses: * 201: * description: Created shipment * content: * application/json: * schema: * type: object * properties: * shipment: * $ref: '#/components/schemas/Shipment' * 400: * description: Validation error or article not in order * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 401: * description: Unauthorized * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 404: * description: Order not found * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 409: * description: Cumulative shipment amount exceeds ordered amount, or all items are already shipped * content: * application/json: * schema: * $ref: '#/components/schemas/Error' */ // #region POST /order/:id/shipment app.post(`${basePath}/order/:id/shipment`, async (req, res) => { const selected = requireSelectedCompany(req); if (selected.error) { return res.status(400).json({ error: selected.error }); } const parsedId = parsePositiveInt(req.params.id, 'id'); if (parsedId.error) { return res.status(400).json({ error: parsedId.error }); } try { const shipment = await db.create(req.user.id, { ...(req.body ?? {}), orderId: parsedId.id, }); emitShipmentEvents(selected.companyId); res.status(201).json({ shipment }); } catch (error) { const status = shipmentErrorStatus(error); if (status === 500) console.error('Create shipment failed:', error); res.status(status).json({ error: error.message }); } }); // #endregion /** * @openapi * /shipment: * get: * tags: [Shipment] * summary: List shipments * description: | * Company-wide paginated list of shipment manifests (`manifest` rows with `type = 'shipment'`) * with delivery state, package tracking info, and order references. * security: * - cookieAuth: [] * parameters: * - in: query * name: offset * schema: * type: integer * default: 0 * minimum: 0 * description: Number of shipments to skip * - in: query * name: limit * schema: * type: integer * default: 50 * minimum: 1 * maximum: 1000 * description: Number of shipments to return * - in: query * name: search * schema: * type: string * description: Free-text search matching shipment number, order number, external number, tracking code, or customer name * - in: query * name: state * schema: * type: string * enum: [new, delivered, returned] * description: Optional filter by delivery state * - in: query * name: seekMonths * schema: * type: integer * description: Negative integer for cutoff months ago (e.g. -1 for shipments older than 1 month) * responses: * 200: * description: Paginated shipment list * content: * application/json: * schema: * type: object * required: [shipments, total, unfilteredTotal, offset, limit] * properties: * shipments: * type: array * items: * $ref: '#/components/schemas/ShipmentSummary' * total: * type: integer * unfilteredTotal: * type: integer * offset: * type: integer * limit: * type: integer * 400: * description: Invalid query parameters 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' */ // #region GET /shipment app.get(`${basePath}/shipment`, async (req, res) => { const selected = requireSelectedCompany(req); if (selected.error) { 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; let state = undefined; if (typeof req.query.state === 'string' && req.query.state.trim() !== '') { const trimmedState = req.query.state.trim().toLowerCase(); if (!['new', 'delivered', 'returned'].includes(trimmedState)) { return res.status(400).json({ error: 'Invalid state' }); } state = trimmedState; } 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; } try { const result = await db.list(req.user.id, { offset, limit, search, state, seekMonths, }); res.status(200).json(result); } catch (error) { const status = shipmentErrorStatus(error); if (status === 500) console.error('List shipments failed:', error); res.status(status).json({ error: error.message }); } }); // #endregion /** * @openapi * /shipment/{id}: * get: * tags: [Shipment] * summary: Get shipment by ID * description: Retrieves shipment header, article positions, and attached packages. * security: * - cookieAuth: [] * parameters: * - in: path * name: id * required: true * schema: * type: integer * description: Shipment ID * responses: * 200: * description: Shipment details * content: * application/json: * schema: * type: object * properties: * shipment: * $ref: '#/components/schemas/Shipment' * 400: * description: Invalid ID or no company selected * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 401: * description: Unauthorized * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 404: * description: Shipment not found * content: * application/json: * schema: * $ref: '#/components/schemas/Error' */ // #region GET /shipment/:id app.get(`${basePath}/shipment/:id`, async (req, res) => { const selected = requireSelectedCompany(req); if (selected.error) { return res.status(400).json({ error: selected.error }); } const parsedId = parsePositiveInt(req.params.id, 'id'); if (parsedId.error) { return res.status(400).json({ error: parsedId.error }); } try { const shipment = await db.getById(req.user.id, parsedId.id); res.status(200).json({ shipment }); } catch (error) { const status = shipmentErrorStatus(error); if (status === 500) console.error('Get shipment failed:', error); res.status(status).json({ error: error.message }); } }); // #endregion /** * @openapi * /shipment/{id}: * patch: * tags: [Shipment] * summary: Update shipment state or metadata * description: | * Updates delivery state (`new`, `delivered`, `returned`) for the shipment. * Emits SSE events (`shipment`, `order`) so connected clients rerender in real time. * security: * - cookieAuth: [] * x-signals: [shipment, order] * parameters: * - in: path * name: id * required: true * schema: * type: integer * description: Shipment ID * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * state: * type: string * enum: [new, delivered, returned] * description: Delivery state * example: * state: delivered * responses: * 200: * description: Updated shipment * content: * application/json: * schema: * type: object * properties: * shipment: * $ref: '#/components/schemas/Shipment' * 400: * description: Invalid state, invalid ID, or no company selected * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 401: * description: Unauthorized * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 404: * description: Shipment not found * content: * application/json: * schema: * $ref: '#/components/schemas/Error' */ // #region PATCH /shipment/:id app.patch(`${basePath}/shipment/:id`, async (req, res) => { const selected = requireSelectedCompany(req); if (selected.error) { return res.status(400).json({ error: selected.error }); } const parsedId = parsePositiveInt(req.params.id, 'id'); if (parsedId.error) { return res.status(400).json({ error: parsedId.error }); } const { state } = req.body ?? {}; if (state !== undefined) { if (typeof state !== 'string' || !['new', 'delivered', 'returned'].includes(state.trim().toLowerCase())) { return res.status(400).json({ error: 'Invalid state' }); } } try { const shipment = await db.update(req.user.id, parsedId.id, { state: state ? state.trim().toLowerCase() : undefined, }); emitShipmentEvents(selected.companyId); res.status(200).json({ shipment }); } catch (error) { const status = shipmentErrorStatus(error); if (status === 500) console.error('Update shipment failed:', error); res.status(status).json({ error: error.message }); } }); // #endregion /** * @openapi * /shipment/{id}: * delete: * tags: [Shipment] * summary: Delete shipment * description: Deletes an unshipped shipment manifest. Shipped shipments cannot be deleted. * security: * - cookieAuth: [] * parameters: * - in: path * name: id * required: true * schema: * type: integer * description: Shipment ID * responses: * 204: * description: Shipment deleted * 400: * description: Invalid ID or no company selected * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 401: * description: Unauthorized * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 404: * description: Shipment not found * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 409: * description: Shipped shipment cannot be deleted * content: * application/json: * schema: * $ref: '#/components/schemas/Error' */ // #region DELETE /shipment/:id app.delete(`${basePath}/shipment/:id`, async (req, res) => { const selected = requireSelectedCompany(req); if (selected.error) { return res.status(400).json({ error: selected.error }); } const parsedId = parsePositiveInt(req.params.id, 'id'); if (parsedId.error) { return res.status(400).json({ error: parsedId.error }); } try { await db.remove(req.user.id, parsedId.id); emitShipmentEvents(selected.companyId); res.status(204).end(); } catch (error) { const status = shipmentErrorStatus(error); if (status === 500) console.error('Delete shipment failed:', error); res.status(status).json({ error: error.message }); } }); // #endregion /** * @openapi * /shipment/{id}/pdf: * post: * tags: [Shipment] * summary: Generate and attach shipment PDF (delivery note) * description: | * Generates an A4 delivery note PDF document for the shipment with line items and package tracking. * Shipping slips contain no price information. * Attaches the PDF as a `manifestattachment` to the shipment so it can be printed or attached to packages. * security: * - cookieAuth: [] * x-signals: [shipment] * parameters: * - in: path * name: id * required: true * schema: * type: integer * description: Shipment ID * responses: * 201: * description: PDF generated and attached to shipment * content: * application/json: * schema: * type: object * required: [attachment, fileUrl] * properties: * attachment: * $ref: '#/components/schemas/DeliveryFile' * fileUrl: * type: string * example: /shipment/1/file/5 * 400: * description: Invalid ID 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: Shipment not found * content: * application/json: * schema: * $ref: '#/components/schemas/Error' */ // #region POST /shipment/:id/pdf app.post(`${basePath}/shipment/:id/pdf`, async (req, res) => { const selected = requireSelectedCompany(req); if (selected.error) { return res.status(400).json({ error: selected.error }); } const parsedId = parsePositiveInt(req.params.id, 'id'); if (parsedId.error) { return res.status(400).json({ error: parsedId.error }); } try { const { attachment } = await createAndAttachManifestPdf( req.user.id, selected.companyId, parsedId.id, 'shipment' ); res.status(201).json({ attachment, fileUrl: `/shipment/${parsedId.id}/file/${attachment.fileId}`, }); } catch (error) { const status = shipmentErrorStatus(error); if (status === 500) console.error('Create shipment PDF failed:', error); res.status(status).json({ error: error.message }); } }); // #endregion /** * @openapi * /shipment/{id}/file/{fileId}: * get: * tags: [Shipment] * summary: Get shipment attachment file content * description: | * Returns the full binary content of an attached file (e.g. shipment delivery note PDF) * for the specified shipment. Supports HTTP caching via ETag (SHA-256 hash) and 304 Not Modified. * security: * - cookieAuth: [] * parameters: * - in: path * name: id * required: true * schema: * type: integer * description: Shipment ID * - in: path * name: fileId * required: true * schema: * type: integer * description: File ID or attachment ID * - in: query * name: download * required: false * schema: * type: boolean * description: When true, sets Content-Disposition to attachment instead of inline * responses: * 200: * description: Binary file content * content: * application/pdf: * schema: * type: string * format: binary * application/octet-stream: * schema: * type: string * format: binary * 304: * description: Not modified * 400: * description: Invalid ID or no company selected * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * 404: * description: Shipment or file not found * content: * application/json: * schema: * $ref: '#/components/schemas/Error' */ // #region GET /shipment/:id/file/:fileId app.get(`${basePath}/shipment/:id/file/:fileId`, async (req, res) => { const selected = requireSelectedCompany(req); if (selected.error) { return res.status(400).json({ error: selected.error }); } const parsedId = parsePositiveInt(req.params.id, 'id'); if (parsedId.error) { return res.status(400).json({ error: parsedId.error }); } const parsedFileId = parsePositiveInt(req.params.fileId, 'fileId'); if (parsedFileId.error) { return res.status(400).json({ error: parsedFileId.error }); } try { const attachment = await db.getFile(req.user.id, parsedId.id, parsedFileId.id); if (attachment.hash) { const etag = `"${attachment.hash}"`; res.setHeader('ETag', etag); const ifNoneMatch = req.headers['if-none-match']; if (ifNoneMatch === etag || ifNoneMatch === attachment.hash) { return res.status(304).end(); } } const isDownload = req.query.download === '1' || req.query.download === 'true'; const dispositionType = isDownload ? 'attachment' : 'inline'; const filename = attachment.name || `file-${attachment.fileId}`; const asciiName = filename.replace(/["\r\n\\]/g, '_'); const encodedName = encodeURIComponent(filename).replace(/['()]/g, escape); res.setHeader('Content-Type', attachment.mimetype || 'application/octet-stream'); res.setHeader('Content-Disposition', `${dispositionType}; filename="${asciiName}"; filename*=UTF-8''${encodedName}`); res.setHeader('Cache-Control', 'private, max-age=86400'); if (attachment.content && Buffer.isBuffer(attachment.content)) { res.setHeader('Content-Length', String(attachment.content.length)); return res.status(200).send(attachment.content); } else { const buffer = Buffer.from(attachment.content || ''); res.setHeader('Content-Length', String(buffer.length)); return res.status(200).send(buffer); } } catch (error) { const status = shipmentErrorStatus(error); if (status === 500) console.error('Get shipment file failed:', error); res.status(status).json({ error: error.message }); } }); // #endregion /** * @openapi * /shipment/{id}/file/{fileId}: * delete: * tags: [Shipment] * summary: Delete shipment file attachment * description: | * Removes a file attachment from the shipment and deletes the underlying file. * security: * - cookieAuth: [] * x-signals: [shipment, order] * parameters: * - in: path * name: id * required: true * schema: * type: integer * description: Shipment ID * - in: path * name: fileId * required: true * schema: * type: integer * description: File ID or attachment ID * responses: * 204: * description: Attachment deleted * 400: * description: Invalid parameters 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: Shipment or attachment not found * content: * application/json: * schema: * $ref: '#/components/schemas/Error' */ // #region DELETE /shipment/:id/file/:fileId app.delete(`${basePath}/shipment/:id/file/:fileId`, async (req, res) => { const selected = requireSelectedCompany(req); if (selected.error) { return res.status(400).json({ error: selected.error }); } const id = Number(req.params.id); if (!Number.isInteger(id) || id <= 0) { return res.status(400).json({ error: 'id is required' }); } const fileId = Number(req.params.fileId); if (!Number.isInteger(fileId) || fileId <= 0) { return res.status(400).json({ error: 'fileId is required' }); } try { await db.removeAttachment(req.user.id, id, fileId); emitShipmentEvents(selected.companyId); res.sendStatus(204); } catch (error) { const status = shipmentErrorStatus(error); if (status === 500) console.error('Delete shipment attachment failed:', error); res.status(status).json({ error: error.message }); } }); // #endregion }