This commit is contained in:
seb
2026-10-20 05:33:11 +02:00
parent 5cb38874ca
commit bcefd81af7
23 changed files with 514 additions and 150 deletions

View File

@@ -27,34 +27,30 @@ export default function create(provider) {
const q = queriesFor(provider);
/**
* Creates a shipment manifest for an order containing one, some, or all items from the order.
* If input.lines is omitted or empty, all remaining unshipped items from the order are shipped.
* Creates a shipment manifest for an order containing specified items from the order.
* On individual lines, amount is optional and defaults to the remaining unshipped quantity.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {object} input - The shipment input.
* @param {number} input.orderId - The parent order manifest id.
* @param {Array<{sku: string, amount?: number, name?: string, pu?: number, net?: number, rebate?: number, taxrate?: number, comment?: string}>} input.lines - The shipment positions.
* @param {string|Date} [input.date] - Optional shipment date (defaults to current date).
* @param {'new'|'delivered'|'returned'} [input.state='new'] - Optional delivery state (defaults to 'new').
* @param {string} [input.externalNumber] - Optional external delivery note number (defaults to order.externalNumber or order.number).
* @param {Array<{sku: string, amount?: number, name?: string, pu?: number, net?: number, rebate?: number, taxrate?: number, comment?: string}>} [input.lines] - The shipment positions (optional).
* @param {object} [tx] - Optional transaction.
* @returns {Promise<object>} The created shipment manifest.
* @throws {Error} If order not found, invalid lines, all items already shipped, or article ceiling invariant exceeded.
* @throws {Error} If order not found, invalid lines, or article ceiling invariant exceeded.
*
* @example
* const shipment = await store.shipment.create(googleAuthId, {
* orderId: 10,
* lines: [{ sku: 'ITEM-A', amount: 5 }]
* });
*
* // Ship all remaining items from the order:
* const fullShipment = await store.shipment.create(googleAuthId, { orderId: 10 });
*/
return async (googleAuthId, input = {}, tx) => {
const orderId = requireId(input.orderId, 'Order');
if (input.lines !== undefined && input.lines !== null && !Array.isArray(input.lines)) {
if (!Array.isArray(input.lines) || input.lines.length === 0) {
throw new Error('Invalid lines');
}
@@ -115,81 +111,97 @@ export default function create(provider) {
shippedAmountBySku.set(sku, Number(row.shippedAmount || 0));
}
// 5. Determine lines to ship (one, some, or all items)
const rawLines = input.lines;
const isAutoAll = !Array.isArray(rawLines) || rawLines.length === 0;
// 5. Determine warehouse and load stock for tracked articles
let targetWarehouseId = input.warehouseId ?? input.warehouse_id;
if (targetWarehouseId != null) {
targetWarehouseId = Number(targetWarehouseId);
} else {
const defWh = await runner.query(q.GET_DEFAULT_WAREHOUSE, { companyId });
targetWarehouseId = defWh.rows[0]?.id ?? null;
}
const articleInfoBySku = new Map();
const remainingStockBySku = new Map();
for (const sku of orderAmountBySku.keys()) {
const artRes = await runner.query(q.GET_ARTICLE_TRACK_STOCK, { companyId, sku });
const art = artRes.rows[0];
const isTracked = Number(art?.track_stock ?? 0) === 1;
let availableStock = Infinity;
if (isTracked && targetWarehouseId != null) {
const stockRes = await runner.query(q.GET_ARTICLE_WAREHOUSE_STOCK, {
warehouseId: targetWarehouseId,
companyId,
sku,
articleId: art?.id ?? null,
});
availableStock = Number(stockRes.rows[0]?.stock ?? 0);
}
articleInfoBySku.set(sku, {
articleId: art?.id,
isTracked,
availableStock,
});
remainingStockBySku.set(sku, availableStock);
}
// 6. Determine lines to ship
const linesToInsert = [];
const proposedBySku = new Map();
if (isAutoAll) {
// Automatically ship all remaining unshipped items from the order
for (const [sku, ordered] of orderAmountBySku.entries()) {
const alreadyShipped = shippedAmountBySku.get(sku) || 0;
const remaining = Math.round((ordered - alreadyShipped) * 1000) / 1000;
if (remaining > 0) {
const ol = orderLineBySku.get(sku);
linesToInsert.push({
sku,
name: ol?.name ?? sku,
pu: ol?.pu ?? 1,
amount: remaining,
net: Number(ol?.net ?? 0),
rebate: Number(ol?.rebate ?? 0),
taxrate: Number(ol?.taxrate ?? 0),
comment: ol?.comment ?? null,
});
proposedBySku.set(sku, remaining);
}
for (const line of input.lines) {
const sku = String(line?.sku ?? '').trim();
if (!sku || !orderAmountBySku.has(sku)) {
throw new Error(`Article (${sku}) is not part of order (${order.number})`);
}
if (linesToInsert.length === 0) {
throw new Error('All items already shipped');
}
} else {
// Specific lines requested (one, some, or all items)
for (const line of rawLines) {
const sku = String(line?.sku ?? '').trim();
if (!sku || !orderAmountBySku.has(sku)) {
throw new Error(`Article (${sku}) is not part of order (${order.number})`);
const ordered = orderAmountBySku.get(sku) || 0;
const alreadyShipped = shippedAmountBySku.get(sku) || 0;
const remaining = Math.round((ordered - alreadyShipped) * 1000) / 1000;
let amount;
if (line.amount !== undefined && line.amount !== null) {
amount = Number(line.amount);
if (!Number.isFinite(amount) || amount === 0) {
throw new Error('Invalid lines');
}
const ordered = orderAmountBySku.get(sku) || 0;
const alreadyShipped = shippedAmountBySku.get(sku) || 0;
const remaining = Math.round((ordered - alreadyShipped) * 1000) / 1000;
let amount;
if (line.amount !== undefined && line.amount !== null) {
amount = Number(line.amount);
if (!Number.isFinite(amount) || amount === 0) {
throw new Error('Invalid lines');
}
} else {
// Default to remaining quantity
if (remaining <= 0) {
throw new Error(`Shipment amount exceeds ordered amount for article (${sku})`);
}
amount = remaining;
}
const currentProposed = proposedBySku.get(sku) || 0;
if (amount > 0 && alreadyShipped + currentProposed + amount > ordered) {
} else {
// Default to remaining quantity
if (remaining <= 0) {
throw new Error(`Shipment amount exceeds ordered amount for article (${sku})`);
}
proposedBySku.set(sku, currentProposed + amount);
const ol = orderLineBySku.get(sku);
linesToInsert.push({
sku,
name: line.name ?? ol?.name ?? sku,
pu: line.pu !== undefined ? line.pu : (ol?.pu ?? 1),
amount,
net: line.net !== undefined ? Number(line.net) : Number(ol?.net ?? 0),
rebate: line.rebate !== undefined ? Number(line.rebate) : Number(ol?.rebate ?? 0),
taxrate: line.taxrate !== undefined ? Number(line.taxrate) : Number(ol?.taxrate ?? 0),
comment: line.comment !== undefined ? (line.comment ? String(line.comment) : null) : (ol?.comment ?? null),
});
amount = remaining;
}
const currentProposed = proposedBySku.get(sku) || 0;
if (amount > 0 && alreadyShipped + currentProposed + amount > ordered) {
throw new Error(`Shipment amount exceeds ordered amount for article (${sku})`);
}
const info = articleInfoBySku.get(sku);
if (amount > 0 && info?.isTracked) {
const available = remainingStockBySku.get(sku) ?? 0;
if (amount > available) {
throw new Error(`Insufficient stock for article (${sku}): available ${available}, requested ${amount}`);
}
remainingStockBySku.set(sku, available - amount);
}
proposedBySku.set(sku, currentProposed + amount);
const ol = orderLineBySku.get(sku);
linesToInsert.push({
sku,
name: line.name ?? ol?.name ?? sku,
pu: line.pu !== undefined ? line.pu : (ol?.pu ?? 1),
amount,
net: line.net !== undefined ? Number(line.net) : Number(ol?.net ?? 0),
rebate: line.rebate !== undefined ? Number(line.rebate) : Number(ol?.rebate ?? 0),
taxrate: line.taxrate !== undefined ? Number(line.taxrate) : Number(ol?.taxrate ?? 0),
comment: line.comment !== undefined ? (line.comment ? String(line.comment) : null) : (ol?.comment ?? null),
});
}
// 6. Resolve next index <y>