Add company-scoped delivery store on manifest
This commit is contained in:
67
src/store/delivery/create.js
Normal file
67
src/store/delivery/create.js
Normal 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;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user