u
This commit is contained in:
195
src/store/shipment/create.js
Normal file
195
src/store/shipment/create.js
Normal file
@@ -0,0 +1,195 @@
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import taxEnsure from '../tax/ensure.js';
|
||||
import { insertLines, parseDate } from '../manifestLines.js';
|
||||
import makeRunner from '../runner.js';
|
||||
import { loadShipment, queriesFor } from './helpers.js';
|
||||
|
||||
function requireId(val, name) {
|
||||
const n = Number(val);
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
throw new Error(`${name} is required`);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new shipment manifest for an order.
|
||||
* Validates that all article positions belong to the order and do not exceed remaining ordered quantities.
|
||||
*
|
||||
* @param {import('../../providers/provider.js').DatabaseProvider} provider
|
||||
*/
|
||||
export default function create(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const ensureTax = taxEnsure(provider);
|
||||
const q = queriesFor(provider);
|
||||
|
||||
/**
|
||||
* Creates a shipment manifest for an order.
|
||||
*
|
||||
* @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 {string|Date} [input.date] - Optional shipment date (defaults to current date).
|
||||
* @param {string} [input.externalNumber] - Optional external delivery note number.
|
||||
* @param {Array<{sku: string, amount: number, name?: string, pu?: number, net?: number, rebate?: number, taxrate?: number, comment?: string}>} input.lines - The shipment positions.
|
||||
* @param {object} [tx] - Optional transaction.
|
||||
* @returns {Promise<object>} The created shipment manifest.
|
||||
* @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 }]
|
||||
* });
|
||||
*/
|
||||
return async (googleAuthId, input = {}, tx) => {
|
||||
const orderId = requireId(input.orderId, 'Order');
|
||||
|
||||
if (!Array.isArray(input.lines) || input.lines.length === 0) {
|
||||
throw new Error('Invalid lines');
|
||||
}
|
||||
|
||||
const shipmentDate = parseDate(input.date) || new Date();
|
||||
const externalNumber = input.externalNumber?.trim?.()
|
||||
? input.externalNumber.trim()
|
||||
: null;
|
||||
|
||||
const run = async (runner, innerTx) => {
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
// 1. Retrieve parent order header
|
||||
const orderRes = await runner.query(q.GET_ORDER_HEADER, {
|
||||
orderId,
|
||||
companyId,
|
||||
});
|
||||
const order = orderRes.rows[0];
|
||||
if (!order) {
|
||||
throw new Error('Order not found');
|
||||
}
|
||||
|
||||
// 2. Retrieve parent order lines
|
||||
const orderLinesRes = await runner.query(q.GET_ORDER_LINES, {
|
||||
orderId,
|
||||
});
|
||||
const orderLines = orderLinesRes.rows ?? [];
|
||||
const orderAmountBySku = new Map();
|
||||
const orderLineBySku = new Map();
|
||||
|
||||
for (const ol of orderLines) {
|
||||
const sku = String(ol.sku ?? '').trim();
|
||||
if (!sku) continue;
|
||||
orderAmountBySku.set(sku, (orderAmountBySku.get(sku) || 0) + Number(ol.amount || 0));
|
||||
if (!orderLineBySku.has(sku)) {
|
||||
orderLineBySku.set(sku, ol);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Validate proposed lines SKUs and amounts
|
||||
const proposedBySku = new Map();
|
||||
for (const line of input.lines) {
|
||||
const sku = String(line?.sku ?? '').trim();
|
||||
const amount = Number(line?.amount);
|
||||
|
||||
if (!sku || !orderAmountBySku.has(sku)) {
|
||||
throw new Error(`Article (${sku}) is not part of order (${order.number})`);
|
||||
}
|
||||
if (!Number.isFinite(amount) || amount <= 0) {
|
||||
throw new Error('Invalid lines');
|
||||
}
|
||||
|
||||
proposedBySku.set(sku, (proposedBySku.get(sku) || 0) + amount);
|
||||
}
|
||||
|
||||
// 4. Retrieve shipment prefix from numbers table
|
||||
const prefixRes = await runner.query(q.GET_SHIPMENT_PREFIX, { companyId });
|
||||
const shipmentPrefix = prefixRes.rows[0]?.prefix?.trim?.() || '-L-';
|
||||
|
||||
// 5. Retrieve already shipped amounts across existing shipment manifests of this order
|
||||
const pattern = `${order.number}${shipmentPrefix}%`;
|
||||
const shippedRes = await runner.query(q.GET_SHIPPED_AMOUNTS_BY_ORDER_PATTERN, {
|
||||
companyId,
|
||||
pattern,
|
||||
excludeShipmentId: null,
|
||||
});
|
||||
const shippedAmountBySku = new Map();
|
||||
for (const row of shippedRes.rows ?? []) {
|
||||
const sku = String(row.sku ?? '').trim();
|
||||
shippedAmountBySku.set(sku, Number(row.shippedAmount || 0));
|
||||
}
|
||||
|
||||
// 6. Quantity ceiling check
|
||||
for (const [sku, proposedAmount] of proposedBySku.entries()) {
|
||||
const alreadyShipped = shippedAmountBySku.get(sku) || 0;
|
||||
const ordered = orderAmountBySku.get(sku) || 0;
|
||||
if (alreadyShipped + proposedAmount > ordered) {
|
||||
throw new Error(`Shipment amount exceeds ordered amount for article (${sku})`);
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Resolve next index <y>
|
||||
const existingShipmentsRes = await runner.query(q.LIST_SHIPMENTS_BY_ORDER_NUMBER_PATTERN, {
|
||||
companyId,
|
||||
pattern,
|
||||
});
|
||||
const existingShipments = existingShipmentsRes.rows ?? [];
|
||||
|
||||
let maxY = 0;
|
||||
const prefixExact = `${order.number}${shipmentPrefix}`;
|
||||
for (const s of existingShipments) {
|
||||
const num = String(s.number || '');
|
||||
if (num.startsWith(prefixExact)) {
|
||||
const suffix = parseInt(num.slice(prefixExact.length), 10);
|
||||
if (Number.isInteger(suffix) && suffix > maxY) {
|
||||
maxY = suffix;
|
||||
}
|
||||
}
|
||||
}
|
||||
const nextY = Math.max(existingShipments.length + 1, maxY + 1);
|
||||
const shipmentNumber = `${order.number}${shipmentPrefix}${nextY}`;
|
||||
|
||||
// 8. Create shipment manifest header
|
||||
const createdRes = await runner.query(q.CREATE_MANIFEST, {
|
||||
companyId,
|
||||
number: shipmentNumber,
|
||||
type: 'shipment',
|
||||
entityId: order.entityId ?? null,
|
||||
externalNumber,
|
||||
date: shipmentDate,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
const manifestId = createdRes.rows[0]?.id ?? createdRes.insertId;
|
||||
|
||||
// 9. Prepare lines copying defaults from order lines
|
||||
const linesToInsert = input.lines.map((line) => {
|
||||
const sku = String(line.sku).trim();
|
||||
const ol = orderLineBySku.get(sku);
|
||||
return {
|
||||
sku,
|
||||
name: line.name ?? ol?.name ?? sku,
|
||||
pu: line.pu !== undefined ? line.pu : (ol?.pu ?? 1),
|
||||
amount: Number(line.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),
|
||||
};
|
||||
});
|
||||
|
||||
await insertLines(runner, {
|
||||
manifestId,
|
||||
lines: linesToInsert,
|
||||
ensureTax,
|
||||
});
|
||||
|
||||
return loadShipment(runner, q, companyId, manifestId);
|
||||
};
|
||||
|
||||
if (tx) {
|
||||
return run(makeRunner(provider, tx), tx);
|
||||
}
|
||||
if (typeof provider?.transaction === 'function') {
|
||||
return provider.transaction((runner, innerTx) => run(runner, innerTx));
|
||||
}
|
||||
return run(makeRunner(provider));
|
||||
};
|
||||
}
|
||||
60
src/store/shipment/delete.js
Normal file
60
src/store/shipment/delete.js
Normal file
@@ -0,0 +1,60 @@
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
import { queriesFor } from './helpers.js';
|
||||
|
||||
function requireId(val, name) {
|
||||
const n = Number(val);
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
throw new Error(`${name} is required`);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a shipment manifest of the selected company.
|
||||
* Shipped shipments (with packages in 'shipped' state) cannot be deleted.
|
||||
*
|
||||
* @param {import('../../providers/provider.js').DatabaseProvider} provider
|
||||
*/
|
||||
export default function del(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const q = queriesFor(provider);
|
||||
|
||||
/**
|
||||
* Deletes a shipment manifest.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {number} id - The shipment manifest ID.
|
||||
* @param {object} [tx] - Optional transaction.
|
||||
* @returns {Promise<void>}
|
||||
* @throws {Error} If shipment not found or already has shipped packages.
|
||||
*
|
||||
* @example
|
||||
* await store.shipment.delete(googleAuthId, 42);
|
||||
*/
|
||||
return async (googleAuthId, id, tx) => {
|
||||
const shipmentId = requireId(id, 'Shipment');
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
const check = await runner.query(q.GET_SHIPMENT_HEADER, {
|
||||
id: shipmentId,
|
||||
companyId,
|
||||
});
|
||||
if (!check.rows[0]) {
|
||||
throw new Error('Shipment not found');
|
||||
}
|
||||
|
||||
const shippedCheck = await runner.query(q.CHECK_SHIPMENT_PACKAGES_SHIPPED, {
|
||||
id: shipmentId,
|
||||
});
|
||||
if (shippedCheck.rows[0]) {
|
||||
throw new Error('Shipped shipment cannot be deleted');
|
||||
}
|
||||
|
||||
await runner.query(q.DELETE_SHIPMENT, {
|
||||
id: shipmentId,
|
||||
companyId,
|
||||
});
|
||||
};
|
||||
}
|
||||
46
src/store/shipment/getById.js
Normal file
46
src/store/shipment/getById.js
Normal file
@@ -0,0 +1,46 @@
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
import { loadShipment, queriesFor } from './helpers.js';
|
||||
|
||||
function requireId(val, name) {
|
||||
const n = Number(val);
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
throw new Error(`${name} is required`);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a shipment manifest by ID for the selected company, including lines and packages.
|
||||
*
|
||||
* @param {import('../../providers/provider.js').DatabaseProvider} provider
|
||||
*/
|
||||
export default function getById(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const q = queriesFor(provider);
|
||||
|
||||
/**
|
||||
* Retrieves a shipment manifest by ID.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {number} id - The shipment manifest ID.
|
||||
* @param {object} [tx] - Optional transaction.
|
||||
* @returns {Promise<object>} The shipment manifest.
|
||||
* @throws {Error} If shipment not found.
|
||||
*
|
||||
* @example
|
||||
* const shipment = await store.shipment.getById(googleAuthId, 42);
|
||||
*/
|
||||
return async (googleAuthId, id, tx) => {
|
||||
const shipmentId = requireId(id, 'Shipment');
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
const shipment = await loadShipment(runner, q, companyId, shipmentId);
|
||||
if (!shipment) {
|
||||
throw new Error('Shipment not found');
|
||||
}
|
||||
|
||||
return shipment;
|
||||
};
|
||||
}
|
||||
63
src/store/shipment/helpers.js
Normal file
63
src/store/shipment/helpers.js
Normal file
@@ -0,0 +1,63 @@
|
||||
import * as mssqlShipmentQueries from '../../providers/mssql/queries/shipment.js';
|
||||
import * as sqliteShipmentQueries from '../../providers/sqlite3/queries/shipment.js';
|
||||
import * as mssqlDocQueries from '../../providers/mssql/queries/manifestDoc.js';
|
||||
import * as sqliteDocQueries from '../../providers/sqlite3/queries/manifestDoc.js';
|
||||
import * as mssqlLogisticsQueries from '../../providers/mssql/queries/logistics.js';
|
||||
import * as sqliteLogisticsQueries from '../../providers/sqlite3/queries/logistics.js';
|
||||
import { shapeLine } from '../manifestLines.js';
|
||||
|
||||
export function queriesFor(provider) {
|
||||
const isSqlite = provider?.dialect === 'sqlite3';
|
||||
return {
|
||||
...(isSqlite ? sqliteShipmentQueries : mssqlShipmentQueries),
|
||||
CREATE_MANIFEST: isSqlite
|
||||
? sqliteDocQueries.CREATE_MANIFEST
|
||||
: mssqlDocQueries.CREATE_MANIFEST,
|
||||
GET_MANIFEST_LINES: isSqlite
|
||||
? sqliteDocQueries.GET_MANIFEST_LINES
|
||||
: mssqlDocQueries.GET_MANIFEST_LINES,
|
||||
SHIPPING_LIST_BY_MANIFEST: isSqlite
|
||||
? sqliteLogisticsQueries.SHIPPING_LIST_BY_MANIFEST
|
||||
: mssqlLogisticsQueries.SHIPPING_LIST_BY_MANIFEST,
|
||||
};
|
||||
}
|
||||
|
||||
export function shapeShipping(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
manifestId: row.manifest_id ?? row.manifestId,
|
||||
number: row.number,
|
||||
trackingCode: row.tracking_code ?? row.trackingCode ?? null,
|
||||
carrier: row.carrier ?? null,
|
||||
type: row.type,
|
||||
state: row.state,
|
||||
};
|
||||
}
|
||||
|
||||
export async function loadShipment(runner, q, companyId, id) {
|
||||
const headerRes = await runner.query(q.GET_SHIPMENT_HEADER, { id, companyId });
|
||||
const row = headerRes.rows[0];
|
||||
if (!row) return null;
|
||||
|
||||
const [linesRes, shippingsRes] = await Promise.all([
|
||||
runner.query(q.GET_MANIFEST_LINES, { manifestId: id }),
|
||||
runner.query(q.SHIPPING_LIST_BY_MANIFEST, { manifestId: id }),
|
||||
]);
|
||||
|
||||
const lines = linesRes.rows.map(shapeLine);
|
||||
const shippings = shippingsRes.rows.map(shapeShipping);
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
number: row.number,
|
||||
type: 'shipment',
|
||||
entityId: row.entityId ?? null,
|
||||
externalNumber: row.externalNumber ?? null,
|
||||
date: row.date,
|
||||
createdAt: row.createdAt ?? null,
|
||||
lineCount: lines.length,
|
||||
packageCount: shippings.length,
|
||||
lines,
|
||||
shippings,
|
||||
};
|
||||
}
|
||||
64
src/store/shipment/listByOrderId.js
Normal file
64
src/store/shipment/listByOrderId.js
Normal file
@@ -0,0 +1,64 @@
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import makeRunner from '../runner.js';
|
||||
import { loadShipment, queriesFor } from './helpers.js';
|
||||
|
||||
function requireId(val, name) {
|
||||
const n = Number(val);
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
throw new Error(`${name} is required`);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists all shipment manifests belonging to an order.
|
||||
*
|
||||
* @param {import('../../providers/provider.js').DatabaseProvider} provider
|
||||
*/
|
||||
export default function listByOrderId(provider) {
|
||||
const access = resolveSelectedCompanyAccess(provider);
|
||||
const q = queriesFor(provider);
|
||||
|
||||
/**
|
||||
* Lists shipments of an order.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {number} orderId - The parent order manifest id.
|
||||
* @param {object} [tx] - Optional transaction.
|
||||
* @returns {Promise<Array<object>>} The shipment manifests with lines and packages.
|
||||
* @throws {Error} If order not found.
|
||||
*
|
||||
* @example
|
||||
* const shipments = await store.shipment.listByOrderId(googleAuthId, 10);
|
||||
*/
|
||||
return async (googleAuthId, orderIdInput, tx) => {
|
||||
const orderId = requireId(orderIdInput, 'Order');
|
||||
const runner = makeRunner(provider, tx);
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
|
||||
const orderRes = await runner.query(q.GET_ORDER_HEADER, {
|
||||
orderId,
|
||||
companyId,
|
||||
});
|
||||
const order = orderRes.rows[0];
|
||||
if (!order) {
|
||||
throw new Error('Order not found');
|
||||
}
|
||||
|
||||
const prefixRes = await runner.query(q.GET_SHIPMENT_PREFIX, { companyId });
|
||||
const shipmentPrefix = prefixRes.rows[0]?.prefix?.trim?.() || '-L-';
|
||||
|
||||
const pattern = `${order.number}${shipmentPrefix}%`;
|
||||
const shipmentsRes = await runner.query(q.LIST_SHIPMENTS_BY_ORDER_NUMBER_PATTERN, {
|
||||
companyId,
|
||||
pattern,
|
||||
});
|
||||
|
||||
const rows = shipmentsRes.rows ?? [];
|
||||
const shipments = await Promise.all(
|
||||
rows.map((row) => loadShipment(runner, q, companyId, row.id))
|
||||
);
|
||||
|
||||
return shipments.filter(Boolean);
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user