import { DELIVERY_TYPE, LIST_DELIVERIES, LIST_DELIVERY_FILES } from '../../providers/mssql/queries/delivery.js'; import request from '../request.js'; import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js'; import { shapeSummary } from './helpers.js'; import { shapeAttachmentMeta } from './attachments.js'; export default function list(pool) { const access = resolveSelectedCompanyAccess(pool); /** * Lists the deliveries of the user's selected company. * * @param {number} googleAuthId - The id of the Google auth user. * @returns {Promise>} The deliveries. * * @example * const deliveries = await store.delivery.list(42); * // => [{ id, number, type, entityId, externalNumber, date }] */ return async (googleAuthId) => { const { companyId } = await access(googleAuthId); const result = await pool .request() .input('companyId', companyId) .input('type', DELIVERY_TYPE) .query(LIST_DELIVERIES); const filesResult = await pool .request() .input('companyId', companyId) .input('type', DELIVERY_TYPE) .query(LIST_DELIVERY_FILES); const filesByManifest = new Map(); for (const row of filesResult.recordset) { const list = filesByManifest.get(row.manifestId) ?? []; list.push(shapeAttachmentMeta(row)); filesByManifest.set(row.manifestId, list); } return result.recordset.map((row) => ({ ...shapeSummary(row), files: filesByManifest.get(row.id) ?? [], })); }; }