Files
dashlibstorage/src/store/shipping/create.js
2026-10-15 22:49:14 +02:00

194 lines
7.0 KiB
JavaScript

import { queriesFor, requireId, requireText } from '../logistics/helpers.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import nextNumber from '../numbers/nextNumber.js';
import ledgerAdd from '../ledger/add.js';
import makeRunner from '../runner.js';
import { syncShipmentSummary } from '../shipment/syncSummary.js';
function shape(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 default function create(provider) {
const access = resolveSelectedCompanyAccess(provider);
const allocateNumber = nextNumber(provider);
const addLedger = ledgerAdd(provider);
const q = queriesFor(provider);
/**
* Creates a shipping (package) for a shipment manifest. The number is allocated from the
* `shipping` numbers sequence (own prefix + counter). If state is 'shipped',
* adjusts stock by appending negative ledger movements for tracked shipment lines,
* writes article history for all items, and ensures stock is deducted once.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {object} input - Shipping input.
* @param {number} input.manifestId - The shipment manifest id.
* @param {string} input.type - Shipping type.
* @param {string} input.state - Shipping state ('shipped' or other).
* @param {string} [input.trackingCode] - Carrier tracking code.
* @param {string} [input.carrier] - Carrier name.
* @param {number} [input.warehouseId] - Optional warehouse ID for stock deduction (defaults to company's first warehouse).
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, manifestId: number, number: string, trackingCode: string|null, carrier: string|null, type: string, state: string}>}
* @throws {Error} If manifest is not found, manifest is not a shipment, or input is invalid.
*
* @example
* await store.shipping.create(googleAuthId, { manifestId: 42, type: 'parcel', state: 'shipped', trackingCode: '1Z999', carrier: 'UPS' });
*/
return async (googleAuthId, input = {}, tx) => {
const manifestId = requireId(input.manifestId, 'Manifest');
const type = requireText(input.type, 'Shipping type');
const state = requireText(input.state, 'Shipping state');
const trackingCode = input.trackingCode ? String(input.trackingCode).trim() : null;
const carrier = input.carrier ? String(input.carrier).trim() : null;
const isShipped = state.trim().toLowerCase() === 'shipped';
const run = async (runner, innerTx) => {
const { companyId, companyuserId } = await access(googleAuthId, runner);
// Verify manifest exists, belongs to company, and is a shipment
const manifestRes = await runner.query(q.GET_MANIFEST_HEADER_BY_ID, {
manifestId,
companyId,
});
const manifest = manifestRes.rows[0];
if (!manifest) {
throw new Error('Manifest not found');
}
if (manifest.type !== 'shipment') {
throw new Error('Manifest is not a shipment');
}
let alreadyShipped = false;
if (isShipped) {
// Check if shipment was already marked shipped by an existing package
const shippedCheck = await runner.query(q.CHECK_ORDER_SHIPPED, {
manifestId,
});
alreadyShipped = Boolean(shippedCheck.rows[0]);
}
// Allocate shipping number and insert shipping record
const number = await allocateNumber(companyId, 'shipping', innerTx);
const result = await runner.query(q.SHIPPING_CREATE, {
manifestId,
number,
trackingCode,
carrier,
type,
state,
});
const row = result.rows[0] ?? {
id: result.insertId,
manifest_id: manifestId,
number,
tracking_code: trackingCode,
carrier,
type,
state,
};
if (isShipped && !alreadyShipped) {
// Load shipment manifest lines
const linesRes = await runner.query(q.GET_ORDER_LINES_FOR_SHIPPING, {
manifestId,
});
const lines = linesRes.rows ?? [];
// Check which lines need warehouse stock deduction vs untracked history
const trackedLines = [];
const untrackedLines = [];
for (const line of lines) {
const sku = line.sku ? String(line.sku).trim() : '';
const amount = Number(line.amount);
if (!sku || !Number.isFinite(amount) || amount <= 0) {
continue;
}
const trackRes = await runner.query(q.CHECK_ARTICLE_TRACK_STOCK, {
companyId,
sku,
});
const isUntracked = (trackRes.rows ?? []).some(
(r) => Number(r.track_stock ?? 1) === 0
);
if (isUntracked) {
untrackedLines.push({ ...line, amount });
} else if ((trackRes.rows ?? []).length > 0) {
trackedLines.push({ ...line, amount });
}
}
const manifestNumber = manifest.number || String(manifestId);
let customerName = null;
if (manifest.entityId) {
const entRes = await runner.query('SELECT name FROM entity WHERE id = @entityId', {
entityId: manifest.entityId,
});
customerName = entRes.rows[0]?.name ?? null;
}
// Book warehouse ledger movements for tracked lines
if (trackedLines.length > 0) {
let warehouseId = null;
if (input.warehouseId != null) {
const requestedWhId = requireId(input.warehouseId, 'Warehouse');
const whCheck = await runner.query(q.CHECK_WAREHOUSE, {
warehouseId: requestedWhId,
companyId,
});
if (!whCheck.rows[0]) {
throw new Error('Warehouse not found');
}
warehouseId = requestedWhId;
} else {
const defaultWh = await runner.query(q.GET_DEFAULT_WAREHOUSE, {
companyId,
});
if (!defaultWh.rows[0]) {
throw new Error('Warehouse not found');
}
warehouseId = defaultWh.rows[0].id;
}
for (const line of trackedLines) {
await addLedger(
googleAuthId,
{
manifestarticle_id: line.id,
warehouse_id: warehouseId,
transaction_type: 'SHIPPING',
amount: -line.amount,
transaction_text: `Versand Lieferschein ${manifestNumber}`,
},
innerTx,
);
}
}
}
await syncShipmentSummary(runner, { companyId, manifestId });
return shape(row);
};
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));
};
}