Add company-scoped delivery store on manifest

This commit is contained in:
seb
2026-08-06 05:32:48 +02:00
parent 4f46967f28
commit 0b7e40ac9c
14 changed files with 2133 additions and 1375 deletions

View File

@@ -0,0 +1,67 @@
import { CREATE_MANIFEST, DELIVERY_TYPE } from '../../sql/delivery.js';
import request from '../request.js';
import resolveCompanyAccess from '../companyuser/resolveCompanyAccess.js';
import taxEnsure from '../tax/ensure.js';
import {
loadDelivery,
normalizeLines,
parseDeliveryDate,
} from './helpers.js';
import { assertSupplier, insertLines } from './writeLines.js';
export default function create(pool) {
const access = resolveCompanyAccess(pool);
const ensureTax = taxEnsure(pool);
return async (googleAuthId, companyId, 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 { rootCategoryId } = await access(googleAuthId, companyId);
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;
}
};
}