import { CREATE_MANIFEST, DELIVERY_TYPE } from '../../sql/delivery.js'; import request from '../request.js'; import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js'; import taxEnsure from '../tax/ensure.js'; import { loadDelivery, normalizeLines, parseDeliveryDate, } from './helpers.js'; import { assertSupplier, insertLines } from './writeLines.js'; /** * Creates a new delivery for a company with its lines. * * @param {object} pool - The mssql connection pool. * @returns {Function} An async function that creates a delivery. * * @example * const fn = create(pool); * const delivery = await fn(42, { number: 'D-1', date: '2026-01-01', supplierId: 5, lines: [...] }); * // => { id, number, type, entityId, date, lines: [...] } */ export default function create(pool) { const access = resolveSelectedCompanyAccess(pool); const ensureTax = taxEnsure(pool); return async (googleAuthId, body = {}) => { const number = body.number?.trim?.() ? body.number.trim() : null; const date = parseDeliveryDate(body.date); if (!number || !date) { throw new Error('Invalid delivery'); } const lines = normalizeLines(body.lines ?? []); const { companyId, rootCategoryId } = await access(googleAuthId); const tx = pool.transaction(); await tx.begin(); try { const supplierId = await assertSupplier( pool, tx, companyId, body.supplierId ?? null, ); const created = await request(pool, tx) .input('companyId', companyId) .input('number', number) .input('type', DELIVERY_TYPE) .input('entityId', supplierId) .input('date', date) .query(CREATE_MANIFEST); const manifestId = created.recordset[0].id; await insertLines(pool, tx, { manifestId, rootCategoryId, lines, ensureTax, }); const delivery = await loadDelivery(pool, tx, companyId, manifestId); await tx.commit(); return delivery; } catch (err) { try { await tx.rollback(); } catch { // ignore } throw err; } }; }