import { queriesFor, requireId, requireText } from '../logistics/helpers.js'; import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.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, }; } /** * Updates a shipping record for the user's selected company. * If transitioned to 'shipped', books ledger movements and adjusts stock. * Once shipped, shipping cannot be undone (state cannot be changed away from 'shipped'). * * @param {import('../../providers/provider.js').DatabaseProvider} provider */ export default function update(provider) { const access = resolveSelectedCompanyAccess(provider); const addLedger = ledgerAdd(provider); const q = queriesFor(provider); /** * Updates a shipping record. * * @param {number} googleAuthId - The id of the Google auth user. * @param {number} id - Shipping ID. * @param {object} patch - Shipping patch fields. * @param {string} [patch.type] - Shipping type. * @param {string} [patch.state] - Shipping state. * @param {string} [patch.trackingCode] - Carrier tracking code. * @param {string} [patch.carrier] - Carrier name. * @param {number} [patch.warehouseId] - Warehouse ID if transitioning to 'shipped'. * @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 shipping is not found, cannot be undone, or manifest not found. */ return async (googleAuthId, id, patch = {}, tx) => { const shippingId = requireId(id, 'Shipping'); const run = async (runner, innerTx) => { const { companyId, companyuserId } = await access(googleAuthId, runner); const check = await runner.query(q.GET_SHIPPING_BY_ID, { id: shippingId, companyId, }); const current = check.rows[0]; if (!current) { throw new Error('Shipping not found'); } const isCurrentlyShipped = String(current.state || '').trim().toLowerCase() === 'shipped'; const hasState = Object.prototype.hasOwnProperty.call(patch, 'state'); const hasType = Object.prototype.hasOwnProperty.call(patch, 'type'); const hasTrackingCode = Object.prototype.hasOwnProperty.call(patch, 'trackingCode'); const hasCarrier = Object.prototype.hasOwnProperty.call(patch, 'carrier'); if (isCurrentlyShipped) { if ( hasState && String(patch.state || '').trim().toLowerCase() !== 'shipped' ) { throw new Error('Shipped shipping cannot be undone'); } } const nextType = hasType ? requireText(patch.type, 'Shipping type') : current.type; const nextState = hasState ? requireText(patch.state, 'Shipping state') : current.state; const nextTrackingCode = hasTrackingCode ? (patch.trackingCode ? String(patch.trackingCode).trim() : null) : (current.tracking_code ?? current.trackingCode ?? null); const nextCarrier = hasCarrier ? (patch.carrier ? String(patch.carrier).trim() : null) : (current.carrier ?? null); const willBeShipped = !isCurrentlyShipped && String(nextState).trim().toLowerCase() === 'shipped'; if (willBeShipped) { const manifestId = current.manifestId; const shippedCheck = await runner.query(q.CHECK_ORDER_SHIPPED, { manifestId, }); const alreadyShipped = Boolean(shippedCheck.rows[0]); if (!alreadyShipped) { const manifestRes = await runner.query(q.GET_MANIFEST_HEADER_BY_ID, { manifestId, companyId, }); const manifest = manifestRes.rows[0] ?? { number: String(manifestId) }; // Load lines & book ledger const linesRes = await runner.query(q.GET_ORDER_LINES_FOR_SHIPPING, { manifestId, }); const lines = linesRes.rows ?? []; 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; } if (trackedLines.length > 0) { let warehouseId = null; if (patch.warehouseId != null) { const requestedWhId = requireId(patch.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, ); } } } } const updateRes = await runner.query(q.SHIPPING_UPDATE, { id: shippingId, type: nextType, state: nextState, trackingCode: nextTrackingCode, carrier: nextCarrier, }); const updatedRow = updateRes.rows[0] ?? { id: shippingId, manifest_id: current.manifestId, number: current.number, tracking_code: nextTrackingCode, carrier: nextCarrier, type: nextType, state: nextState, }; await syncShipmentSummary(runner, { companyId, manifestId: current.manifestId }); return shape(updatedRow); }; 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)); }; }