49 lines
1.7 KiB
JavaScript
49 lines
1.7 KiB
JavaScript
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
|
import stockAccept from '../stock/accept.js';
|
|
import { loadDelivery } from './helpers.js';
|
|
import makeRunner from '../runner.js';
|
|
|
|
/**
|
|
* Books all positions of an incoming delivery manifest to the ledger
|
|
* by delegating to store.stock.accept.
|
|
*
|
|
* @param {object} provider - Storage provider instance.
|
|
* @returns {Function} `(googleAuthId, input, tx) => Promise<object>`
|
|
*/
|
|
export default function book(provider) {
|
|
const access = resolveSelectedCompanyAccess(provider);
|
|
const accept = stockAccept(provider);
|
|
|
|
return async (googleAuthId, input = {}, tx) => {
|
|
const rawId = typeof input === 'number' ? input : (input?.id ?? input?.deliveryId);
|
|
const id = Number(rawId);
|
|
if (!Number.isInteger(id) || id <= 0) {
|
|
throw new Error('Delivery not found');
|
|
}
|
|
|
|
const warehouseId = input?.warehouseId ?? input?.warehouse_id ?? null;
|
|
|
|
const doBook = async (runner, activeTx) => {
|
|
const { companyId } = await access(googleAuthId, runner);
|
|
const delivery = await loadDelivery(provider, activeTx, companyId, id);
|
|
if (!delivery) {
|
|
throw new Error('Delivery not found');
|
|
}
|
|
if (!delivery.lines || delivery.lines.length === 0) {
|
|
throw new Error('Delivery has no lines');
|
|
}
|
|
|
|
await accept(googleAuthId, { deliveryId: id, warehouseId }, activeTx);
|
|
return loadDelivery(provider, activeTx, companyId, id);
|
|
};
|
|
|
|
if (tx) {
|
|
return doBook(makeRunner(provider, tx), tx);
|
|
}
|
|
if (typeof provider?.transaction === 'function') {
|
|
return provider.transaction(doBook);
|
|
}
|
|
return doBook(makeRunner(provider));
|
|
};
|
|
}
|