Add quote and order stores plus ledger hash_version.

Mirror delivery on manifest for quote/order with customer entityId (excluding Lieferanten/POS), and support entity.list role=customer for pickers.
This commit is contained in:
seb
2026-08-06 19:58:35 +02:00
parent ae549fd022
commit b095ab6199
12 changed files with 987 additions and 45 deletions

View File

@@ -0,0 +1,389 @@
import {
CREATE_LINE,
CREATE_MANIFEST,
DELETE_LINES_BY_MANIFEST,
DELETE_MANIFEST,
GET_MANIFEST_HEADER,
GET_MANIFEST_LINES,
LIST_MANIFESTS,
RESOLVE_ARTICLE_ID_BY_SKU,
UPDATE_MANIFEST,
} from '../../sql/manifestDoc.js';
import {
GET_CUSTOMER_BY_ID,
POS_GROUP_NAME,
SUPPLIER_GROUP_NAME,
} from '../../sql/entity.js';
import request from '../request.js';
import resolveCompanyAccess from '../companyuser/resolveCompanyAccess.js';
import taxEnsure from '../tax/ensure.js';
function shapeSummary(type, row) {
return {
id: row.id,
number: row.number,
type,
entityId: row.entityId ?? null,
date: row.date,
};
}
function shapeLine(row) {
return {
id: row.id,
articleId: row.articleId ?? null,
sku: row.sku ?? null,
amount: row.amount,
net: row.net,
rebate: row.rebate,
tax: row.tax,
comment: row.comment ?? null,
};
}
function parseDate(value) {
if (value instanceof Date && !Number.isNaN(value.getTime())) {
return value;
}
if (typeof value === 'string' && value.trim()) {
const d = new Date(value);
if (!Number.isNaN(d.getTime())) {
return d;
}
}
return null;
}
function normalizeLines(lines) {
if (!Array.isArray(lines)) {
throw new Error('Invalid lines');
}
return lines.map((entry) => {
const sku = entry?.sku?.trim?.() ? entry.sku.trim() : null;
if (!sku) {
throw new Error('Invalid lines');
}
const amount = entry?.amount;
const net = entry?.net;
const rebate =
entry?.rebate === undefined || entry?.rebate === null ? 0 : entry.rebate;
const tax = entry?.tax;
const comment =
entry?.comment === undefined || entry?.comment === null
? null
: String(entry.comment);
if (
!Number.isFinite(amount) ||
!Number.isFinite(net) ||
!Number.isFinite(rebate) ||
!Number.isFinite(tax)
) {
throw new Error('Invalid lines');
}
return { sku, amount, net, rebate, tax, comment };
});
}
async function assertCustomerEntity(pool, tx, companyId, entityId) {
if (entityId == null) {
return null;
}
if (!Number.isFinite(entityId)) {
throw new Error('Entity not found');
}
const result = await request(pool, tx)
.input('id', entityId)
.input('companyId', companyId)
.input('supplierGroupName', SUPPLIER_GROUP_NAME)
.input('posGroupName', POS_GROUP_NAME)
.query(GET_CUSTOMER_BY_ID);
if (!result.recordset[0]) {
throw new Error('Entity not found');
}
return entityId;
}
async function resolveArticleId(pool, tx, rootCategoryId, sku) {
const result = await request(pool, tx)
.input('rootCategoryId', rootCategoryId)
.input('sku', sku)
.query(RESOLVE_ARTICLE_ID_BY_SKU);
const articleId = result.recordset[0]?.id;
if (!articleId) {
throw new Error('Article not found');
}
return articleId;
}
async function insertLines(
pool,
tx,
{ manifestId, rootCategoryId, lines, ensureTax },
) {
for (const line of lines) {
const articleId = await resolveArticleId(
pool,
tx,
rootCategoryId,
line.sku,
);
const taxId = await ensureTax(line.tax, tx);
await request(pool, tx)
.input('manifestId', manifestId)
.input('articleId', articleId)
.input('amount', line.amount)
.input('net', line.net)
.input('comment', line.comment)
.input('rebate', line.rebate)
.input('taxId', taxId)
.query(CREATE_LINE);
}
}
async function loadDoc(pool, tx, { type, companyId, id }) {
const header = await request(pool, tx)
.input('id', id)
.input('companyId', companyId)
.input('type', type)
.query(GET_MANIFEST_HEADER);
const row = header.recordset[0];
if (!row) {
return null;
}
const lines = await request(pool, tx)
.input('manifestId', id)
.query(GET_MANIFEST_LINES);
return {
...shapeSummary(type, row),
lines: lines.recordset.map(shapeLine),
};
}
/**
* Factory for quote / order (and similar) stores on manifest / manifestarticle.
*
* @param {object} pool
* @param {{ type: string, label: string }} options
* `type` → manifest.type (`quote` / `order`)
* `label` → error prefix (`Quote` / `Order` → "Quote not found")
*/
export default function createManifestDocStore(pool, { type, label }) {
const access = resolveCompanyAccess(pool);
const ensureTax = taxEnsure(pool);
const notFound = `${label} not found`;
const invalid = `Invalid ${label.toLowerCase()}`;
async function list(googleAuthId, companyId) {
await access(googleAuthId, companyId);
const result = await pool
.request()
.input('companyId', companyId)
.input('type', type)
.query(LIST_MANIFESTS);
return result.recordset.map((row) => shapeSummary(type, row));
}
async function getById(googleAuthId, companyId, id) {
if (!Number.isFinite(id)) {
throw new Error(notFound);
}
await access(googleAuthId, companyId);
const doc = await loadDoc(pool, null, { type, companyId, id });
if (!doc) {
throw new Error(notFound);
}
return doc;
}
async function create(googleAuthId, companyId, body = {}) {
const number = body.number?.trim?.() ? body.number.trim() : null;
const date = parseDate(body.date);
if (!number || !date) {
throw new Error(invalid);
}
const lines = normalizeLines(body.lines ?? []);
const { rootCategoryId } = await access(googleAuthId, companyId);
const tx = pool.transaction();
await tx.begin();
try {
const entityId = await assertCustomerEntity(
pool,
tx,
companyId,
body.entityId ?? null,
);
const created = await request(pool, tx)
.input('companyId', companyId)
.input('number', number)
.input('type', type)
.input('entityId', entityId)
.input('date', date)
.query(CREATE_MANIFEST);
const manifestId = created.recordset[0].id;
await insertLines(pool, tx, {
manifestId,
rootCategoryId,
lines,
ensureTax,
});
const doc = await loadDoc(pool, tx, { type, companyId, id: manifestId });
await tx.commit();
return doc;
} catch (err) {
try {
await tx.rollback();
} catch {
// ignore
}
throw err;
}
}
async function update(googleAuthId, companyId, id, patch = {}) {
if (!Number.isFinite(id)) {
throw new Error(notFound);
}
const hasNumber = Object.prototype.hasOwnProperty.call(patch, 'number');
const hasDate = Object.prototype.hasOwnProperty.call(patch, 'date');
const hasEntityId = Object.prototype.hasOwnProperty.call(patch, 'entityId');
const hasLines = Object.prototype.hasOwnProperty.call(patch, 'lines');
if (!hasNumber && !hasDate && !hasEntityId && !hasLines) {
throw new Error(invalid);
}
let normalizedLines;
if (hasLines) {
normalizedLines = normalizeLines(patch.lines);
}
const { rootCategoryId } = await access(googleAuthId, companyId);
const tx = pool.transaction();
await tx.begin();
try {
const existing = await request(pool, tx)
.input('id', id)
.input('companyId', companyId)
.input('type', type)
.query(GET_MANIFEST_HEADER);
const current = existing.recordset[0];
if (!current) {
throw new Error(notFound);
}
const summary = shapeSummary(type, current);
let number = summary.number;
if (hasNumber) {
number = patch.number?.trim?.() ? patch.number.trim() : null;
if (!number) {
throw new Error(invalid);
}
}
let date = summary.date;
if (hasDate) {
date = parseDate(patch.date);
if (!date) {
throw new Error(invalid);
}
}
let entityId = summary.entityId;
if (hasEntityId) {
entityId = await assertCustomerEntity(
pool,
tx,
companyId,
patch.entityId ?? null,
);
}
await request(pool, tx)
.input('id', id)
.input('companyId', companyId)
.input('type', type)
.input('number', number)
.input('entityId', entityId)
.input('date', date)
.query(UPDATE_MANIFEST);
if (hasLines) {
await request(pool, tx)
.input('manifestId', id)
.query(DELETE_LINES_BY_MANIFEST);
await insertLines(pool, tx, {
manifestId: id,
rootCategoryId,
lines: normalizedLines,
ensureTax,
});
}
const doc = await loadDoc(pool, tx, { type, companyId, id });
await tx.commit();
return doc;
} catch (err) {
try {
await tx.rollback();
} catch {
// ignore
}
throw err;
}
}
async function del(googleAuthId, companyId, id) {
if (!Number.isFinite(id)) {
throw new Error(notFound);
}
await access(googleAuthId, companyId);
const result = await pool
.request()
.input('id', id)
.input('companyId', companyId)
.input('type', type)
.query(DELETE_MANIFEST);
if (!result.rowsAffected[0]) {
throw new Error(notFound);
}
}
return {
list,
getById,
create,
update,
delete: del,
};
}