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'; function shape(row) { return { id: row.id, manifestId: row.manifest_id, number: row.number, 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 for a manifest (order). 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 order lines, * writes article history, and ensures the order was not already shipped. * * @param {number} googleAuthId - The id of the Google auth user. * @param {object} input - Shipping input. * @param {number} input.manifestId - The manifest (order) id. * @param {string} input.type - Shipping type. * @param {string} input.state - Shipping state ('shipped' or other). * @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, type: string, state: string}>} * @throws {Error} If manifest is not found, order already shipped, or input is invalid. * * @example * await store.shipping.create(googleAuthId, { manifestId: 42, type: 'parcel', state: 'shipped' }); */ 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 isShipped = state.trim().toLowerCase() === 'shipped'; const run = async (runner, innerTx) => { const { companyId } = await access(googleAuthId, runner); // Verify manifest exists and belongs to company 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 (isShipped) { // Check if order was already shipped const shippedCheck = await runner.query(q.CHECK_ORDER_SHIPPED, { manifestId, }); if (shippedCheck.rows[0]) { throw new Error('Order already shipped'); } } // Allocate shipping number and insert shipping record const number = await allocateNumber(companyId, 'shipping', innerTx); const result = await runner.query(q.SHIPPING_CREATE, { manifestId, number, type, state, }); const row = result.rows[0] ?? { id: result.insertId, manifest_id: manifestId, number, type, state, }; if (isShipped) { // Load order lines const linesRes = await runner.query(q.GET_ORDER_LINES_FOR_SHIPPING, { manifestId, }); const lines = linesRes.rows ?? []; // Check which lines need warehouse stock deduction const trackedLines = []; 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 && (trackRes.rows ?? []).length > 0) { trackedLines.push({ ...line, amount }); } } 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; } const manifestNumber = manifest.number || String(manifestId); for (const line of trackedLines) { await addLedger( googleAuthId, { manifestarticle_id: line.id, warehouse_id: warehouseId, transaction_type: 'SHIPPING', amount: -line.amount, transaction_text: `Versand Auftrag ${manifestNumber}`, }, innerTx, ); } } } 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)); }; }