This commit is contained in:
seb
2026-10-12 19:48:04 +02:00
parent cc77bf4377
commit f743ace6af
26 changed files with 1694 additions and 1375 deletions

386
src/api/routes/shipment.js Normal file
View File

@@ -0,0 +1,386 @@
import * as db from '../../db/shipment.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')
) {
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 partial or full shipment manifest for the order.
* Validates that article positions belong to the order and cumulative shipped quantities
* do not exceed ordered quantities.
* security:
* - cookieAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Order ID
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required: [lines]
* properties:
* date:
* type: string
* format: date
* externalNumber:
* type: string
* lines:
* type: array
* items:
* type: object
* required: [sku, amount]
* properties:
* sku:
* type: string
* amount:
* type: number
* 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
* 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/{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}:
* 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
}

View File

@@ -23,7 +23,12 @@ function shippingErrorStatus(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')) return 400;
if (
error.message?.endsWith(' required') ||
error.message?.includes('not a shipment')
) {
return 400;
}
if (
error.message?.includes('cannot be deleted') ||
error.message?.includes('cannot be undone') ||
@@ -227,6 +232,178 @@ export function register(app, basePath = '') {
// #endregion
/**
* @openapi
* /shipment/{id}/shipping:
* get:
* tags: [Shipping]
* summary: List packages of a shipment
* description: Lists all packages (shippings) belonging to the specified shipment manifest.
* security:
* - cookieAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Shipment ID
* responses:
* 200:
* description: List of packages
* content:
* application/json:
* schema:
* type: object
* properties:
* shippings:
* type: array
* items:
* $ref: '#/components/schemas/Shipping'
* 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/shipping
app.get(`${basePath}/shipment/:id/shipping`, 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 shippings = await db.listByManifestId(req.user.id, parsedId.id);
res.status(200).json({ shippings });
} catch (error) {
const status = shippingErrorStatus(error);
if (status === 500) console.error('List shipment packages failed:', error);
res.status(status).json({ error: error.message });
}
});
// #endregion
/**
* @openapi
* /shipment/{id}/shipping:
* post:
* tags: [Shipping]
* summary: Create package for a shipment
* description: |
* Creates a physical package (shipping) for the shipment manifest.
* Accepts carrier and parcel tracking code. If state is `shipped`,
* deducts stock for the shipment's lines via ledger movements.
* security:
* - cookieAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Shipment ID
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required: [type, state]
* properties:
* type:
* type: string
* state:
* type: string
* trackingCode:
* type: string
* description: Carrier parcel tracking code
* carrier:
* type: string
* description: Carrier name (e.g. DHL, UPS, DPD)
* warehouseId:
* type: integer
* description: Optional warehouse ID for stock deduction when state is shipped
* responses:
* 201:
* description: Created package
* content:
* application/json:
* schema:
* type: object
* properties:
* shipping:
* $ref: '#/components/schemas/Shipping'
* 400:
* description: Validation error, manifest is not a shipment, 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 or warehouse not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
// #region POST /shipment/:id/shipping
app.post(`${basePath}/shipment/:id/shipping`, 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 shipping = await db.create(req.user.id, {
...(req.body ?? {}),
manifestId: parsedId.id,
});
if (String(shipping.state || '').trim().toLowerCase() === 'shipped') {
emitShippingEvents(selected.companyId);
}
res.status(201).json({ shipping });
} catch (error) {
const status = shippingErrorStatus(error);
if (status === 500) console.error('Create shipment package failed:', error);
res.status(status).json({ error: error.message });
}
});
// #endregion
/**
* @openapi
* /shipping/{id}:
@@ -256,6 +433,12 @@ export function register(app, basePath = '') {
* type: string
* state:
* type: string
* trackingCode:
* type: string
* description: Carrier parcel tracking code
* carrier:
* type: string
* description: Carrier name (e.g. DHL, UPS, DPD)
* warehouseId:
* type: integer
* description: Warehouse ID for stock deduction when transitioning to shipped