u
This commit is contained in:
@@ -1023,8 +1023,28 @@
|
||||
* $ref: '#/components/schemas/Payment'
|
||||
* paid:
|
||||
* type: boolean
|
||||
* description: True when paidTotal equals orderTotal
|
||||
* shipped:
|
||||
* type: boolean
|
||||
* description: True when shippedQuantity equals orderedQuantity
|
||||
* delivered:
|
||||
* type: boolean
|
||||
* orderTotal:
|
||||
* type: number
|
||||
* description: Gross sum across order positions
|
||||
* paidTotal:
|
||||
* type: number
|
||||
* description: Sum of all payments connected to order
|
||||
* orderedQuantity:
|
||||
* type: number
|
||||
* description: Total ordered items
|
||||
* shippedQuantity:
|
||||
* type: number
|
||||
* description: Total shipped items across order shipments
|
||||
* shipments:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/Shipment'
|
||||
* ArticleImage:
|
||||
* type: object
|
||||
* required: [picId, sort, full, thumb, hash, thumbHash]
|
||||
@@ -1209,10 +1229,53 @@
|
||||
* number:
|
||||
* type: string
|
||||
* description: Shipping number from the `shipping` number sequence
|
||||
* trackingCode:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* description: Carrier parcel tracking code
|
||||
* carrier:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* description: Carrier name (e.g. DHL, UPS, DPD)
|
||||
* type:
|
||||
* type: string
|
||||
* state:
|
||||
* type: string
|
||||
* Shipment:
|
||||
* type: object
|
||||
* required: [id, number, type, date, lines, shippings]
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* number:
|
||||
* type: string
|
||||
* description: Shipment compound number `<orderNumber><shipmentPrefix><y>`
|
||||
* type:
|
||||
* type: string
|
||||
* enum: [shipment]
|
||||
* entityId:
|
||||
* type: integer
|
||||
* nullable: true
|
||||
* externalNumber:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* date:
|
||||
* type: string
|
||||
* createdAt:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* lineCount:
|
||||
* type: integer
|
||||
* packageCount:
|
||||
* type: integer
|
||||
* lines:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/ManifestLine'
|
||||
* shippings:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/Shipping'
|
||||
* Package:
|
||||
* type: object
|
||||
* required: [id, shippingId, entityaddressId, number, type, state]
|
||||
|
||||
@@ -36,6 +36,8 @@ export const openApiOptions = {
|
||||
{ name: 'Delivery', description: 'Company-scoped goods receipts (Lieferungen)' },
|
||||
{ name: 'Quote', description: 'Company-scoped quotes (Angebote)' },
|
||||
{ name: 'Order', description: 'Company-scoped sales orders (Aufträge)' },
|
||||
{ name: 'Shipment', description: 'Company-scoped shipment manifests (Lieferscheine)' },
|
||||
{ name: 'Shipping', description: 'Shipment packages, carriers, and tracking codes' },
|
||||
{ name: 'Customergroup', description: 'Company-scoped customer groups' },
|
||||
{ name: 'Entity', description: 'Company-scoped entities, addresses, and contacts' },
|
||||
{ name: 'Image', description: 'Content-addressed AVIF by fullHash' },
|
||||
|
||||
386
src/api/routes/shipment.js
Normal file
386
src/api/routes/shipment.js
Normal 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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -1,22 +1,84 @@
|
||||
import { getStore } from './store.js';
|
||||
|
||||
function round2(num) {
|
||||
return Math.round((Number(num) || 0) * 100) / 100;
|
||||
}
|
||||
|
||||
function calculateOrderGrossTotal(lines = []) {
|
||||
let total = 0;
|
||||
for (const line of lines) {
|
||||
const amount = Number(line.amount || 0);
|
||||
const net = Number(line.net || 0);
|
||||
const rebate = Number(line.rebate || 0);
|
||||
const taxrate = Number(line.taxrate || 0);
|
||||
const netAfterRebate = net * (1 - rebate / 100);
|
||||
const gross = netAfterRebate * (1 + taxrate / 100);
|
||||
total += amount * gross;
|
||||
}
|
||||
return round2(total);
|
||||
}
|
||||
|
||||
function calculatePaidTotal(payments = []) {
|
||||
let total = 0;
|
||||
for (const payment of payments) {
|
||||
total += Number(payment.amount || 0);
|
||||
}
|
||||
return round2(total);
|
||||
}
|
||||
|
||||
function calculateOrderedQuantity(lines = []) {
|
||||
let qty = 0;
|
||||
for (const line of lines) {
|
||||
qty += Number(line.amount || 0);
|
||||
}
|
||||
return Math.round(qty * 1000) / 1000;
|
||||
}
|
||||
|
||||
function calculateShippedQuantity(shipments = []) {
|
||||
let qty = 0;
|
||||
for (const shipment of shipments) {
|
||||
for (const line of shipment.lines || []) {
|
||||
qty += Number(line.amount || 0);
|
||||
}
|
||||
}
|
||||
return Math.round(qty * 1000) / 1000;
|
||||
}
|
||||
|
||||
async function enrichSingleOrder(store, googleAuthId, order) {
|
||||
if (!order) return order;
|
||||
const [shippings, payments] = await Promise.all([
|
||||
const [shippings, payments, shipments] = await Promise.all([
|
||||
store.shipping.listByManifestId(googleAuthId, order.id).catch(() => []),
|
||||
store.payment.listByManifestId(googleAuthId, order.id).catch(() => []),
|
||||
store.shipment.listByOrderId(googleAuthId, order.id).catch(() => []),
|
||||
]);
|
||||
|
||||
const isPaid = Array.isArray(payments) && payments.length > 0;
|
||||
const isDelivered = Array.isArray(shippings) && shippings.some((s) => s.state === 'shipped' || s.state === 'delivered');
|
||||
const orderLines = Array.isArray(order.lines) ? order.lines : [];
|
||||
const paymentsList = Array.isArray(payments) ? payments : [];
|
||||
const shipmentsList = Array.isArray(shipments) ? shipments : [];
|
||||
const shippingsList = Array.isArray(shippings) ? shippings : [];
|
||||
|
||||
const orderTotal = calculateOrderGrossTotal(orderLines);
|
||||
const paidTotal = calculatePaidTotal(paymentsList);
|
||||
const orderedQuantity = calculateOrderedQuantity(orderLines);
|
||||
const shippedQuantity = calculateShippedQuantity(shipmentsList);
|
||||
|
||||
const isPaid = orderTotal > 0 && Math.abs(paidTotal - orderTotal) < 0.01;
|
||||
const isShipped = orderedQuantity > 0 && Math.abs(shippedQuantity - orderedQuantity) < 0.001;
|
||||
const isDelivered = isShipped || shippingsList.some((s) => s.state === 'shipped' || s.state === 'delivered');
|
||||
|
||||
return {
|
||||
...order,
|
||||
shipping: shippings[0] ?? null,
|
||||
shippings: shippings ?? [],
|
||||
payment: payments[0] ?? null,
|
||||
payments: payments ?? [],
|
||||
shipping: shippingsList[0] ?? (shipmentsList[0]?.shippings?.[0] ?? null),
|
||||
shippings: shippingsList.length > 0 ? shippingsList : shipmentsList.flatMap((s) => s.shippings || []),
|
||||
payment: paymentsList[0] ?? null,
|
||||
payments: paymentsList,
|
||||
shipments: shipmentsList,
|
||||
orderTotal,
|
||||
paidTotal,
|
||||
orderedQuantity,
|
||||
shippedQuantity,
|
||||
paid: isPaid,
|
||||
shipped: isShipped,
|
||||
delivered: isDelivered,
|
||||
};
|
||||
}
|
||||
|
||||
21
src/db/shipment.js
Normal file
21
src/db/shipment.js
Normal file
@@ -0,0 +1,21 @@
|
||||
import { getStore } from './store.js';
|
||||
|
||||
export async function create(googleAuthId, data) {
|
||||
const store = await getStore();
|
||||
return store.shipment.create(googleAuthId, data);
|
||||
}
|
||||
|
||||
export async function getById(googleAuthId, id) {
|
||||
const store = await getStore();
|
||||
return store.shipment.getById(googleAuthId, id);
|
||||
}
|
||||
|
||||
export async function listByOrderId(googleAuthId, orderId) {
|
||||
const store = await getStore();
|
||||
return store.shipment.listByOrderId(googleAuthId, orderId);
|
||||
}
|
||||
|
||||
export async function remove(googleAuthId, id) {
|
||||
const store = await getStore();
|
||||
return store.shipment.delete(googleAuthId, id);
|
||||
}
|
||||
@@ -62,6 +62,19 @@ export async function importOrders({
|
||||
defaultCustomerGroupId = groups[0]?.id || null;
|
||||
} catch {}
|
||||
|
||||
let defaultWarehouseId = null;
|
||||
try {
|
||||
const warehouses = await store.warehouse.list(googleAuthId);
|
||||
if (warehouses && warehouses.length > 0) {
|
||||
defaultWarehouseId = warehouses[0].id;
|
||||
} else {
|
||||
const wh = await store.warehouse.create(googleAuthId, { name: 'Standardlager' });
|
||||
defaultWarehouseId = wh.id;
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn('Could not ensure warehouse:', err.message);
|
||||
}
|
||||
|
||||
const entityMap = new Map();
|
||||
try {
|
||||
const entities = await store.entity.list(googleAuthId);
|
||||
@@ -220,19 +233,37 @@ export async function importOrders({
|
||||
|
||||
// Handle Delivery / Shipping
|
||||
const shippingType = cleanValue(m.shippingType);
|
||||
if (shippingType) {
|
||||
const isShipped = String(m.shipped ?? '').trim() === '1';
|
||||
const shippingState = isShipped ? 'shipped' : 'open';
|
||||
const isShipped = String(m.shipped ?? '').trim() === '1';
|
||||
|
||||
try {
|
||||
await store.shipping.create(googleAuthId, {
|
||||
manifestId: createdOrder.id,
|
||||
type: shippingType,
|
||||
state: shippingState,
|
||||
});
|
||||
shippingsImported++;
|
||||
} catch (err) {
|
||||
log.warn(`Failed to create shipping for order ${orderNumber}:`, err.message);
|
||||
if (isShipped || shippingType) {
|
||||
const shippableLines = lines
|
||||
.filter((l) => l.sku)
|
||||
.map((l) => ({ sku: l.sku, amount: l.amount }));
|
||||
|
||||
if (shippableLines.length > 0) {
|
||||
try {
|
||||
const shipment = await store.shipment.create(googleAuthId, {
|
||||
orderId: createdOrder.id,
|
||||
date: validDate,
|
||||
lines: shippableLines,
|
||||
});
|
||||
|
||||
const trackingCode = cleanValue(m.trackingCode ?? m.tracking_code ?? m.cTracking);
|
||||
const carrier = cleanValue(m.carrier ?? m.cCarrier);
|
||||
const shippingState = isShipped ? 'shipped' : 'draft';
|
||||
|
||||
await store.shipping.create(googleAuthId, {
|
||||
manifestId: shipment.id,
|
||||
type: shippingType || 'standard',
|
||||
state: shippingState,
|
||||
trackingCode: trackingCode || undefined,
|
||||
carrier: carrier || undefined,
|
||||
warehouseId: defaultWarehouseId || undefined,
|
||||
});
|
||||
shippingsImported++;
|
||||
} catch (err) {
|
||||
log.warn(`Failed to create shipment/shipping for order ${orderNumber}:`, err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user