u
This commit is contained in:
71
src/store/shipping/create.js
Normal file
71
src/store/shipping/create.js
Normal file
@@ -0,0 +1,71 @@
|
||||
import { queriesFor, requireId, requireText } from '../logistics/helpers.js';
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import resolveManifestAccess from '../manifestattachment/resolveManifestAccess.js';
|
||||
import nextNumber from '../numbers/nextNumber.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 manifestAccess = resolveManifestAccess(provider);
|
||||
const allocateNumber = nextNumber(provider);
|
||||
const q = queriesFor(provider);
|
||||
|
||||
/**
|
||||
* Creates a shipping for a manifest (order). The number is allocated from the
|
||||
* `shipping` numbers sequence (own prefix + counter).
|
||||
*
|
||||
* @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.
|
||||
* @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 or input is invalid.
|
||||
*
|
||||
* @example
|
||||
* await store.shipping.create(googleAuthId, { manifestId: 42, type: 'parcel', state: 'open' });
|
||||
*/
|
||||
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 run = async (runner, innerTx) => {
|
||||
const { companyId } = await access(googleAuthId, runner);
|
||||
await manifestAccess(companyId, manifestId, innerTx);
|
||||
|
||||
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,
|
||||
};
|
||||
return shape(row);
|
||||
};
|
||||
|
||||
if (typeof provider?.transaction === 'function') {
|
||||
return provider.transaction((runner, innerTx) => run(runner, innerTx));
|
||||
}
|
||||
return run(makeRunner(provider, tx));
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user