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

@@ -65,6 +65,8 @@ import deliveryGetById from './store/delivery/getById.js';
import deliveryCreate from './store/delivery/create.js';
import deliveryUpdate from './store/delivery/update.js';
import deliveryDelete from './store/delivery/delete.js';
import createQuoteStore from './store/quote/index.js';
import createOrderStore from './store/order/index.js';
import posterminalList from './store/posterminal/list.js';
import posterminalUpsert from './store/posterminal/upsert.js';
import posterminalDelete from './store/posterminal/delete.js';
@@ -219,6 +221,9 @@ export default class LibDashStore {
delete: deliveryDelete(pool),
};
this.quote = createQuoteStore(pool);
this.order = createOrderStore(pool);
this.posterminal = {
list: posterminalList(pool),
upsert: posterminalUpsert(pool),

View File

@@ -541,6 +541,7 @@ BEGIN
transaction_type NVARCHAR(100) NOT NULL,
amount FLOAT NOT NULL,
transaction_text NVARCHAR(MAX) NOT NULL,
hash_version INT NOT NULL,
prev_hash NVARCHAR(128) NULL,
CONSTRAINT FK_ledger_manifestarticle FOREIGN KEY (manifestarticle_id) REFERENCES manifestarticle(id) ON DELETE NO ACTION
) WITH (LEDGER = ON (APPEND_ONLY = ON));

View File

@@ -1,4 +1,5 @@
export const SUPPLIER_GROUP_NAME = 'Lieferanten';
export const POS_GROUP_NAME = 'POS';
export const ENTITY_COLUMNS = `
e.id,
@@ -28,6 +29,17 @@ WHERE cg.company_id = @companyId
ORDER BY e.name, e.id
`;
/** Entities whose group is not Lieferanten and not POS (customer picker). */
export const LIST_CUSTOMERS_BY_COMPANY = `
SELECT
${ENTITY_COLUMNS}
FROM entity e
INNER JOIN customergroup cg ON cg.id = e.customergroup_id
WHERE cg.company_id = @companyId
AND cg.name NOT IN (@supplierGroupName, @posGroupName)
ORDER BY e.name, e.id
`;
export const GET_BY_COMPANY_AND_ID = `
SELECT
${ENTITY_COLUMNS}
@@ -37,6 +49,17 @@ WHERE e.id = @id
AND cg.company_id = @companyId
`;
/** Customer entity: company-scoped and not Lieferanten/POS. */
export const GET_CUSTOMER_BY_ID = `
SELECT
${ENTITY_COLUMNS}
FROM entity e
INNER JOIN customergroup cg ON cg.id = e.customergroup_id
WHERE e.id = @id
AND cg.company_id = @companyId
AND cg.name NOT IN (@supplierGroupName, @posGroupName)
`;
export const LIST_SUPPLIERS_BY_COMPANY = `
SELECT
e.id,

125
src/sql/manifestDoc.js Normal file
View File

@@ -0,0 +1,125 @@
/**
* Shared SQL for typed manifest documents (quote / order).
* Delivery keeps its own SQL with supplierId naming.
*/
export const QUOTE_TYPE = 'quote';
export const ORDER_TYPE = 'order';
export const LIST_MANIFESTS = `
SELECT
m.id,
m.[number],
m.[type],
m.entity_id AS entityId,
m.[date]
FROM manifest m
WHERE m.company_id = @companyId
AND m.[type] = @type
ORDER BY m.[date] DESC, m.id DESC
`;
export const GET_MANIFEST_HEADER = `
SELECT
m.id,
m.[number],
m.[type],
m.entity_id AS entityId,
m.[date]
FROM manifest m
WHERE m.id = @id
AND m.company_id = @companyId
AND m.[type] = @type
`;
export const GET_MANIFEST_LINES = `
SELECT
ma.id,
ma.article_id AS articleId,
a.sku,
ma.amount,
ma.net,
ma.rebate,
t.rate AS tax,
ma.comment
FROM manifestarticle ma
LEFT JOIN article a ON a.id = ma.article_id
INNER JOIN tax t ON t.id = ma.tax_id
WHERE ma.manifest_id = @manifestId
ORDER BY ma.id
`;
export const CREATE_MANIFEST = `
INSERT INTO manifest (company_id, [number], [type], entity_id, [date])
OUTPUT INSERTED.id
VALUES (@companyId, @number, @type, @entityId, @date)
`;
export const UPDATE_MANIFEST = `
UPDATE manifest
SET
[number] = @number,
entity_id = @entityId,
[date] = @date
WHERE id = @id
AND company_id = @companyId
AND [type] = @type
`;
export const DELETE_MANIFEST = `
DELETE FROM manifest
WHERE id = @id
AND company_id = @companyId
AND [type] = @type
`;
export const DELETE_LINES_BY_MANIFEST = `
DELETE FROM manifestarticle
WHERE manifest_id = @manifestId
`;
export const CREATE_LINE = `
INSERT INTO manifestarticle (
manifest_id,
article_id,
amount,
net,
comment,
rebate,
tax_id
)
OUTPUT INSERTED.id
VALUES (
@manifestId,
@articleId,
@amount,
@net,
@comment,
@rebate,
@taxId
)
`;
/** Resolve SKU to article id if reachable via the company category tree. */
export const RESOLVE_ARTICLE_ID_BY_SKU = `
;WITH category_tree AS (
SELECT id
FROM category
WHERE id = @rootCategoryId
UNION ALL
SELECT c.id
FROM category c
INNER JOIN category_tree ct ON c.parent_id = ct.id
)
SELECT TOP 1 a.id
FROM article a
WHERE a.sku = @sku
AND EXISTS (
SELECT 1
FROM categoryarticle ca
INNER JOIN category_tree ct ON ct.id = ca.category_id
WHERE ca.article_id = a.id
)
`;

View File

@@ -1,6 +1,9 @@
import {
LIST_BY_COMPANY,
LIST_BY_COMPANY_AND_GROUP,
LIST_CUSTOMERS_BY_COMPANY,
POS_GROUP_NAME,
SUPPLIER_GROUP_NAME,
} from '../../sql/entity.js';
import resolveCompanyAccess from '../companyuser/resolveCompanyAccess.js';
import resolveCustomerGroupAccess from '../customergroup/resolveCustomerGroupAccess.js';
@@ -20,9 +23,27 @@ export default function list(pool) {
const access = resolveCompanyAccess(pool);
const groupAccess = resolveCustomerGroupAccess(pool);
return async (googleAuthId, companyId, { customergroupId } = {}) => {
return async (
googleAuthId,
companyId,
{ customergroupId, role } = {},
) => {
await access(googleAuthId, companyId);
if (role != null && role !== 'customer') {
throw new Error('Invalid role');
}
if (role === 'customer') {
const result = await pool
.request()
.input('companyId', companyId)
.input('supplierGroupName', SUPPLIER_GROUP_NAME)
.input('posGroupName', POS_GROUP_NAME)
.query(LIST_CUSTOMERS_BY_COMPANY);
return result.recordset.map(shape);
}
if (customergroupId != null) {
await groupAccess(companyId, customergroupId);
const result = await pool

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,
};
}

6
src/store/order/index.js Normal file
View File

@@ -0,0 +1,6 @@
import { ORDER_TYPE } from '../../sql/manifestDoc.js';
import createManifestDocStore from '../manifestDoc/createStore.js';
export default function createOrderStore(pool) {
return createManifestDocStore(pool, { type: ORDER_TYPE, label: 'Order' });
}

6
src/store/quote/index.js Normal file
View File

@@ -0,0 +1,6 @@
import { QUOTE_TYPE } from '../../sql/manifestDoc.js';
import createManifestDocStore from '../manifestDoc/createStore.js';
export default function createQuoteStore(pool) {
return createManifestDocStore(pool, { type: QUOTE_TYPE, label: 'Quote' });
}