Compare commits
3 Commits
f6b0ff7483
...
c730244902
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c730244902 | ||
|
|
9ed7e4ee3b | ||
|
|
8cc7d0eb0b |
26
API.healthcheck.md
Normal file
26
API.healthcheck.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# healthcheck
|
||||
|
||||
This document is auto-generated from the JSDoc comments in `src/store` by running `npm run api-doc`.
|
||||
|
||||
## `healthcheck.check`
|
||||
|
||||
*Source: `src/store/healthcheck/check.js`*
|
||||
|
||||
Executes a database health check: 1. Ensures the healthcheck table has one row (creates with sequence 0 if not). 2. Selects that row for update with minimal, reasonable locking within a transaction. 3. Updates the sequence by 1 in a separate statement within the transaction.
|
||||
|
||||
**Parameters**
|
||||
|
||||
| Name | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| `[tx]` | `object` | Optional transaction to run within. |
|
||||
|
||||
**Returns**
|
||||
|
||||
`Promise<{ok: boolean, sequence: number}>` — The health check result.
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
const result = await store.healthcheck.check();
|
||||
// => { ok: true, sequence: 1 }
|
||||
```
|
||||
4
API.md
4
API.md
@@ -207,7 +207,7 @@ The store is exposed as a `LibDashStore` instance (see `src/index.js`). Each met
|
||||
- `syncSummary(): void`
|
||||
- `update(googleAuthId: number, id: number, patch: {number?: string, date?: string, entityId?: number, externalNumber?: string, lines?: Array<{sku?: string, name?: string, pu?: number, amount: number, net: number, rebate?: number, taxrate: number, comment?: string|null}>}, tx?: object): Promise<{id: number, number: string, type: string, entityId: number|null, externalNumber: string|null, date: string, lines: Array<{id: number, sku: string|null, name: string|null, pu: number, amount: number, net: number, rebate: number, taxrate: number, comment: string|null}>}>`
|
||||
- [order](API.order.md)
|
||||
- `create(googleAuthId: number, body: {number: string, date: string, entityId?: number, externalNumber?: string, lines?: Array<{sku?: string, name?: string, pu?: number, amount: number, net: number, rebate?: number, taxrate: number, comment?: string|null}>}, tx?: object): Promise<{id: number, number: string, type: string, entityId: number|null, externalNumber: string|null, date: string, lines: Array<{id: number, sku: string|null, name: string|null, pu: number, amount: number, net: number, rebate: number, taxrate: number, comment: string|null}>}>`
|
||||
- `create(googleAuthId: number, body: {number: string, date: string, entityId: number, externalNumber?: string, lines?: Array<{sku?: string, name?: string, pu?: number, amount: number, net: number, rebate?: number, taxrate: number, comment?: string|null}>}, tx?: object): Promise<{id: number, number: string, type: string, entityId: number, externalNumber: string|null, date: string, lines: Array<{id: number, sku: string|null, name: string|null, pu: number, amount: number, net: number, rebate: number, taxrate: number, comment: string|null}>}>`
|
||||
- `createFromQuote(googleAuthId: number, quoteId: number, body?: {number?: string, date?: string, createdAt?: string, entityId?: number, externalNumber?: string, lines?: Array<{sku?: string, name?: string, pu?: number, amount: number, net: number, rebate?: number, taxrate: number, comment?: string|null}>}, tx?: object): Promise<{id: number, number: string, type: string, entityId: number|null, externalNumber: string|null, date: string, lines: Array<{id: number, sku: string|null, name: string|null, pu: number, amount: number, net: number, rebate: number, taxrate: number, comment: string|null}>}>`
|
||||
- `createShipment(googleAuthId: number, orderId: number, input?: {lines?: Array<{sku: string, amount?: number, name?: string, pu?: number, net?: number, rebate?: number, taxrate?: number, comment?: string}>, date?: string|Date, externalNumber?: string}, tx?: object): Promise<object>`
|
||||
- `delete(googleAuthId: number, id: number, tx?: object): Promise<void>`
|
||||
@@ -330,6 +330,8 @@ The store is exposed as a `LibDashStore` instance (see `src/index.js`). Each met
|
||||
- `getById(googleAuthId: number, id: number, tx?: object): Promise<{id: number, company_id: number, name: string, width: number, height: number, dpi: number, type: string, content: object, thumb: Buffer|null}|undefined>`
|
||||
- `list(googleAuthId: number, tx?: object): Promise<Array<{id: number, company_id: number, name: string, width: number, height: number, dpi: number, type: string, content: object, thumb: Buffer|null}>>`
|
||||
- `update(googleAuthId: number, id: number, input: {name?: string, width?: number, height?: number, dpi?: number, type?: string, content?: object, thumb?: Buffer|null}, tx?: object): Promise<{id: number, company_id: number, name: string, width: number, height: number, dpi: number, type: string, content: object, thumb: Buffer|null}>`
|
||||
- [healthcheck](API.healthcheck.md)
|
||||
- `check(tx?: object): Promise<{ok: boolean, sequence: number}>`
|
||||
- [account](API.account.md)
|
||||
- `create(googleAuthId: number, input: {type: string, name: string}, tx?: object): Promise<{id: number, companyId: number, type: string, name: string}>`
|
||||
- `delete(googleAuthId: number, id: number, tx?: object): Promise<void>`
|
||||
|
||||
@@ -16,18 +16,18 @@ Creates a new order for the user's selected company with its lines and records a
|
||||
| `body` | `object` | The order input. |
|
||||
| `body.number` | `string` | The order number. |
|
||||
| `body.date` | `string` | The order date. |
|
||||
| `[body.entityId]` | `number` | The id of the customer entity. |
|
||||
| `body.entityId` | `number` | The id of the customer entity. |
|
||||
| `[body.externalNumber]` | `string` | An external (customer) reference number. |
|
||||
| `[body.lines]` | `Array<{sku?: string, name?: string, pu?: number, amount: number, net: number, rebate?: number, taxrate: number, comment?: string|null}>` | The order lines. |
|
||||
| `[tx]` | `object` | Optional transaction to run within. |
|
||||
|
||||
**Returns**
|
||||
|
||||
`Promise<{id: number, number: string, type: string, entityId: number|null, externalNumber: string|null, date: string, lines: Array<{id: number, sku: string|null, name: string|null, pu: number, amount: number, net: number, rebate: number, taxrate: number, comment: string|null}>}>` — The created order.
|
||||
`Promise<{id: number, number: string, type: string, entityId: number, externalNumber: string|null, date: string, lines: Array<{id: number, sku: string|null, name: string|null, pu: number, amount: number, net: number, rebate: number, taxrate: number, comment: string|null}>}>` — The created order.
|
||||
|
||||
**Throws**
|
||||
|
||||
`Error` — If the order is invalid.
|
||||
`Error` — If the order is invalid, no entity is selected, or entity not found.
|
||||
|
||||
**Example**
|
||||
|
||||
|
||||
67
TODO.md
67
TODO.md
@@ -133,3 +133,70 @@ Conversion order (bottom-up by dependency):
|
||||
(queries/schema stay mssql-specific, so likely keep it)
|
||||
- [ ] Decide export for `SCHEMA_SCRIPTS` (currently re-exported from `index.js`
|
||||
from the moved schema file)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
I'll check how auth is applied across the routes.
|
||||
|
||||
Viewed index.js:1-305
|
||||
Searched for "app\.(post|put|patch|delete|get|use|all)\("
|
||||
Viewed auth.js:1-132
|
||||
|
||||
The middleware skips auth on several path prefixes. Next I'll check which of those can write.
|
||||
|
||||
Searched for "\.(post|put|patch|delete)\("
|
||||
Searched for "'/(api/)?(public|mcp|oauth|\.well-known)"
|
||||
|
||||
Next: the telemetry public route, the `/oauth/register` handler, and the v1 router.
|
||||
|
||||
Viewed telemetry.js:1-118
|
||||
Viewed mcp.js:360-460
|
||||
Searched for "(router|app)\.(post|put|patch|delete|use|all)\(|auth|token"
|
||||
Viewed index.js:1-27
|
||||
Searched for "registerClient|export (async )?function"
|
||||
Viewed mcp.js:455-540
|
||||
Searched for "db\.\w+|verifyIdToken|allow|jwt\.sign"
|
||||
|
||||
**No. With no JWT, an attacker can still write to the database.** The checks I did are static code review only, and I haven't run anything.
|
||||
|
||||
`authMiddleware` ([auth.js](file:///home/seb/src/dashback/src/api/middleware/auth.js#L49-L68)) lets several path groups through without a token. Most of them can't write to the SQL database, but two can.
|
||||
|
||||
### 1. Open OAuth registration: `POST /oauth/register`
|
||||
- This route is public, and it calls `mcpDb.registerClient` ([mcp.js:368](file:///home/seb/src/dashback/src/api/routes/mcp.js#L368)) to insert a client row.
|
||||
- Anyone can create unlimited rows with no auth and no rate limit.
|
||||
- `client_name`, `redirect_uris`, `grant_types` and `scope` all come straight from the request body.
|
||||
|
||||
### 2. Auth bypass: `POST /oauth/authorize`
|
||||
- The middleware calls `next()` on this route even with no token ([auth.js:70-79](file:///home/seb/src/dashback/src/api/middleware/auth.js#L70-L79)).
|
||||
- The handler ([mcp.js:455-503](file:///home/seb/src/dashback/src/api/routes/mcp.js#L455-L503)) takes an `email` from the body when there's no `req.user`.
|
||||
- If that email is on the allowlist, it writes an auth code (`createAuthCode`) for that user and redirects with it. **No password, Google token or JWT is checked.**
|
||||
- An attacker can chain this with the previous hole:
|
||||
1. Register a client with `/oauth/register`.
|
||||
2. Post to `/oauth/authorize` with the victim's allowlisted email and their own PKCE `code_challenge`.
|
||||
3. Exchange the code at `/oauth/token`, which I haven't read.
|
||||
4. Call `/mcp` as that user.
|
||||
- That would be a full impersonation if the MCP tools can write. Please confirm this by testing against a dev instance.
|
||||
- Also, `new URL(redirect_uri)` runs with no try/catch and no check that `redirect_uri` matches the registered URIs. A bad value throws, and a valid one is an open redirect that sends the code to the attacker.
|
||||
|
||||
### Not writing to the SQL database
|
||||
- `/api/public/telemetry/crash` ([telemetry.js](file:///home/seb/src/dashback/src/api/routes/telemetry.js#L87-L104)) is public and unauthenticated. It writes to a file on disk rather than SQL, but there's no size or rate limit beyond `bodyLimit`, so it can fill the disk.
|
||||
- `/v1` and `/api/v1` skip the middleware, but the routes I saw are all `GET`. The ones with data use `posAuthMiddleware`, and `/client`, `/pimage` and `/cimage` have no auth.
|
||||
- `/api/auth/login` verifies a Google ID token and checks the allowlist. If `IMPLICIT_CREATE=true`, any valid Google account gets added to the allowlist ([login.js:107](file:///home/seb/src/dashback/src/api/routes/auth/login.js#L107)). Make sure that's off in production.
|
||||
|
||||
### Suggested fixes
|
||||
- Make `/oauth/authorize` POST require `req.user`, and remove the `email` fallback.
|
||||
- Validate `redirect_uri` against the registered URIs for the client.
|
||||
- Rate-limit `/oauth/register`, or gate it.
|
||||
|
||||
Want me to implement these? I haven't changed any code.
|
||||
@@ -44,6 +44,7 @@ const MODULE_ORDER = [
|
||||
'attributevalue',
|
||||
'articleattributevalue',
|
||||
'labeltemplate',
|
||||
'healthcheck',
|
||||
];
|
||||
|
||||
// Files that are internal helpers and should not appear as public API entries.
|
||||
|
||||
45
scripts/test-healthcheck.js
Normal file
45
scripts/test-healthcheck.js
Normal file
@@ -0,0 +1,45 @@
|
||||
import assert from 'node:assert';
|
||||
import LibDashStore from '../src/index.js';
|
||||
import { BetterSqlite3Provider } from '../src/providers/sqlite3/index.js';
|
||||
|
||||
async function main() {
|
||||
console.log('Testing healthcheck store method on in-memory SQLite...');
|
||||
const provider = new BetterSqlite3Provider({ path: ':memory:' });
|
||||
await provider.initialize();
|
||||
const store = await new LibDashStore(provider);
|
||||
|
||||
assert(store.healthcheck, 'store.healthcheck should exist');
|
||||
assert.strictEqual(typeof store.healthcheck.check, 'function', 'store.healthcheck.check should be a function');
|
||||
|
||||
// First call: table is empty, should ensure row (0), select for update, increment to 1 and update
|
||||
const res1 = await store.healthcheck.check();
|
||||
console.log('Healthcheck call 1 result:', res1);
|
||||
assert.strictEqual(res1.ok, true, 'res1.ok should be true');
|
||||
assert.strictEqual(res1.sequence, 1, 'res1.sequence should be 1');
|
||||
|
||||
// Second call: row exists with 1, should increment to 2 and update
|
||||
const res2 = await store.healthcheck.check();
|
||||
console.log('Healthcheck call 2 result:', res2);
|
||||
assert.strictEqual(res2.ok, true, 'res2.ok should be true');
|
||||
assert.strictEqual(res2.sequence, 2, 'res2.sequence should be 2');
|
||||
|
||||
// Third call: row exists with 2, should increment to 3 and update
|
||||
const res3 = await store.healthcheck.check();
|
||||
console.log('Healthcheck call 3 result:', res3);
|
||||
assert.strictEqual(res3.ok, true, 'res3.ok should be true');
|
||||
assert.strictEqual(res3.sequence, 3, 'res3.sequence should be 3');
|
||||
|
||||
// Verify DB state directly
|
||||
const rows = await provider.query('SELECT * FROM healthcheck');
|
||||
console.log('Healthcheck DB rows:', rows.rows);
|
||||
assert.strictEqual(rows.rows.length, 1, 'healthcheck should have exactly 1 row');
|
||||
assert.strictEqual(Number(rows.rows[0].sequence), 3, 'sequence in DB should be 3');
|
||||
|
||||
await provider.close();
|
||||
console.log('✓ All healthcheck store tests passed successfully!');
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('Test failed:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -21,6 +21,15 @@ async function testProvider(name, provider) {
|
||||
});
|
||||
await store.google_auth.setSelectedCompany(googleAuthId, company.id);
|
||||
|
||||
const supplier = await store.supplier.create(googleAuthId, {
|
||||
name: 'Test Supplier',
|
||||
});
|
||||
const groups = await store.customergroup.list(googleAuthId);
|
||||
const customer = await store.entity.create(googleAuthId, {
|
||||
name: 'Test Customer',
|
||||
customergroupId: groups[0].id,
|
||||
});
|
||||
|
||||
// 2. Test delivery with both dates
|
||||
console.log('Testing delivery creation with date and createdAt...');
|
||||
const deliveryDate = '2026-10-15T12:00:00.000Z';
|
||||
@@ -28,6 +37,7 @@ async function testProvider(name, provider) {
|
||||
|
||||
const createdDelivery = await store.delivery.create(googleAuthId, {
|
||||
externalNumber: 'DEL-2DATES-1',
|
||||
supplierId: supplier.id,
|
||||
date: deliveryDate,
|
||||
createdAt: customCreatedAt,
|
||||
lines: [
|
||||
@@ -98,6 +108,7 @@ async function testProvider(name, provider) {
|
||||
const order = await store.order.create(googleAuthId, {
|
||||
number: `ORD-${Date.now()}`,
|
||||
date: '2026-12-15T00:00:00.000Z',
|
||||
entityId: customer.id,
|
||||
lines: [{ name: 'Order item', amount: 3, net: 25, taxrate: 19 }],
|
||||
});
|
||||
assert(order.createdAt, 'Order should have default createdAt populated');
|
||||
|
||||
@@ -269,6 +269,7 @@ import mcpGetRefreshToken from './store/mcp/getRefreshToken.js';
|
||||
import mcpRevokeRefreshToken from './store/mcp/revokeRefreshToken.js';
|
||||
import mcpListAuthorizations from './store/mcp/listAuthorizations.js';
|
||||
import mcpRevokeAuthorizations from './store/mcp/revokeAuthorizations.js';
|
||||
import healthcheckCheck from './store/healthcheck/check.js';
|
||||
|
||||
export default class LibDashStore {
|
||||
/**
|
||||
@@ -706,6 +707,10 @@ export default class LibDashStore {
|
||||
revokeAuthorizations: mcpRevokeAuthorizations(provider),
|
||||
};
|
||||
|
||||
this.healthcheck = {
|
||||
check: healthcheckCheck(provider),
|
||||
};
|
||||
|
||||
this.purge = storePurge(provider);
|
||||
this.initialize = storeInitialize(provider);
|
||||
this.transaction = (fn) => provider.transaction(fn);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Drop order = reverse of schema create dependency order. */
|
||||
export const TABLES = [
|
||||
|
||||
'healthcheck',
|
||||
'articlewarehousesummary',
|
||||
'deliverysummary',
|
||||
'shipmentsummary',
|
||||
|
||||
19
src/providers/mssql/queries/healthcheck.js
Normal file
19
src/providers/mssql/queries/healthcheck.js
Normal file
@@ -0,0 +1,19 @@
|
||||
export const ENSURE_ROW = `
|
||||
IF NOT EXISTS (SELECT 1 FROM healthcheck)
|
||||
BEGIN
|
||||
INSERT INTO healthcheck ([sequence]) VALUES (0);
|
||||
END
|
||||
`;
|
||||
|
||||
export const SELECT_FOR_UPDATE = `
|
||||
SELECT TOP 1 id, [sequence]
|
||||
FROM healthcheck WITH (UPDLOCK, ROWLOCK)
|
||||
ORDER BY id ASC;
|
||||
`;
|
||||
|
||||
export const UPDATE_SEQUENCE = `
|
||||
UPDATE healthcheck
|
||||
SET [sequence] = @sequence,
|
||||
updated_at = SYSUTCDATETIME()
|
||||
WHERE id = @id;
|
||||
`;
|
||||
@@ -646,6 +646,12 @@ BEGIN
|
||||
CONSTRAINT FK_manifest_entity FOREIGN KEY (entity_id) REFERENCES entity(id) ON DELETE NO ACTION
|
||||
);
|
||||
END
|
||||
|
||||
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'UQ_manifest_company_type_number' AND object_id = OBJECT_ID('manifest'))
|
||||
BEGIN
|
||||
CREATE UNIQUE NONCLUSTERED INDEX UQ_manifest_company_type_number
|
||||
ON manifest (company_id, [type], [number]);
|
||||
END
|
||||
`;
|
||||
|
||||
export const INIT_MANIFESTARTICLE = `
|
||||
@@ -1431,8 +1437,20 @@ BEGIN
|
||||
END
|
||||
`;
|
||||
|
||||
export const INIT_HEALTHCHECK = `
|
||||
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'healthcheck')
|
||||
BEGIN
|
||||
CREATE TABLE healthcheck (
|
||||
id INT IDENTITY(1,1) PRIMARY KEY,
|
||||
[sequence] BIGINT NOT NULL CONSTRAINT DF_healthcheck_sequence DEFAULT 0,
|
||||
updated_at DATETIME2 NOT NULL CONSTRAINT DF_healthcheck_updated_at DEFAULT SYSUTCDATETIME()
|
||||
);
|
||||
END
|
||||
`;
|
||||
|
||||
/** DDL scripts in dependency order for schema init. */
|
||||
export const SCHEMA_SCRIPTS = [
|
||||
INIT_HEALTHCHECK,
|
||||
INIT_META,
|
||||
INIT_LANGUAGE,
|
||||
INIT_TAX,
|
||||
|
||||
24
src/providers/sqlite3/queries/healthcheck.js
Normal file
24
src/providers/sqlite3/queries/healthcheck.js
Normal file
@@ -0,0 +1,24 @@
|
||||
import * as source from '../../mssql/queries/healthcheck.js';
|
||||
import { translateQueries } from './translate.js';
|
||||
|
||||
const queries = translateQueries(source, 'healthcheck');
|
||||
|
||||
export const ENSURE_ROW = `
|
||||
INSERT INTO healthcheck (id, "sequence")
|
||||
SELECT 1, 0
|
||||
WHERE NOT EXISTS (SELECT 1 FROM healthcheck);
|
||||
`;
|
||||
|
||||
export const SELECT_FOR_UPDATE = `
|
||||
SELECT id, "sequence"
|
||||
FROM healthcheck
|
||||
ORDER BY id ASC
|
||||
LIMIT 1;
|
||||
`;
|
||||
|
||||
export const UPDATE_SEQUENCE = `
|
||||
UPDATE healthcheck
|
||||
SET "sequence" = @sequence,
|
||||
updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
|
||||
WHERE id = @id;
|
||||
`;
|
||||
@@ -432,6 +432,8 @@ CREATE TABLE IF NOT EXISTS manifest (
|
||||
FOREIGN KEY (company_id) REFERENCES company(id) ON DELETE NO ACTION,
|
||||
FOREIGN KEY (entity_id) REFERENCES entity(id) ON DELETE NO ACTION
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS UQ_manifest_company_type_number
|
||||
ON manifest (company_id, "type", "number");
|
||||
`;
|
||||
|
||||
export const INIT_MANIFESTARTICLE = `
|
||||
@@ -1056,8 +1058,17 @@ CREATE TABLE IF NOT EXISTS subagentschedule (
|
||||
CREATE INDEX IF NOT EXISTS IX_subagentschedule_company ON subagentschedule (company_id);
|
||||
`;
|
||||
|
||||
export const INIT_HEALTHCHECK = `
|
||||
CREATE TABLE IF NOT EXISTS healthcheck (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
"sequence" INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at TEXT NOT NULL DEFAULT (${UTC_NOW})
|
||||
);
|
||||
`;
|
||||
|
||||
/** DDL scripts in dependency order for SQLite schema initialization. */
|
||||
export const SCHEMA_SCRIPTS = [
|
||||
INIT_HEALTHCHECK,
|
||||
INIT_META,
|
||||
INIT_LANGUAGE,
|
||||
INIT_TAX,
|
||||
|
||||
@@ -8,6 +8,7 @@ import { insertLines, normalizeLines, parseDate } from '../manifestLines.js';
|
||||
import { loadDelivery } from './helpers.js';
|
||||
import { insertAttachments } from './attachments.js';
|
||||
import { assertSupplier } from './writeLines.js';
|
||||
import { assertUniqueManifestNumber } from '../manifestDoc/helpers.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
export default function create(provider) {
|
||||
@@ -35,15 +36,27 @@ export default function create(provider) {
|
||||
const { companyId } = await access(googleAuthId);
|
||||
|
||||
const run = async (runner, tx) => {
|
||||
const targetSupplierId = body.supplierId !== undefined ? body.supplierId : body.entityId;
|
||||
if (targetSupplierId == null) {
|
||||
throw new Error('No supplier selected');
|
||||
}
|
||||
|
||||
const supplierId = await assertSupplier(
|
||||
provider,
|
||||
tx,
|
||||
companyId,
|
||||
body.supplierId ?? null,
|
||||
targetSupplierId,
|
||||
);
|
||||
|
||||
const number = await allocateNumber(companyId, queries.DELIVERY_TYPE, tx);
|
||||
|
||||
await assertUniqueManifestNumber(provider, tx, {
|
||||
companyId,
|
||||
type: queries.DELIVERY_TYPE,
|
||||
number,
|
||||
errorMessage: 'Delivery number already exists',
|
||||
});
|
||||
|
||||
const created = await runner(queries.CREATE_MANIFEST, {
|
||||
companyId,
|
||||
number,
|
||||
|
||||
@@ -8,6 +8,7 @@ import { insertLines, normalizeLines, parseDate } from '../manifestLines.js';
|
||||
import { loadDelivery, shapeSummary } from './helpers.js';
|
||||
import { insertAttachments } from './attachments.js';
|
||||
import { assertSupplier } from './writeLines.js';
|
||||
import { assertUniqueManifestNumber } from '../manifestDoc/helpers.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
export default function update(provider) {
|
||||
@@ -28,11 +29,15 @@ export default function update(provider) {
|
||||
patch,
|
||||
'supplierId',
|
||||
);
|
||||
const hasEntityId = Object.prototype.hasOwnProperty.call(
|
||||
patch,
|
||||
'entityId',
|
||||
);
|
||||
const hasExternalNumber = Object.prototype.hasOwnProperty.call(patch, 'externalNumber');
|
||||
const hasLines = Object.prototype.hasOwnProperty.call(patch, 'lines');
|
||||
const hasFiles = Object.prototype.hasOwnProperty.call(patch, 'files');
|
||||
|
||||
if (!hasNumber && !hasDate && !hasCreatedAt && !hasSupplierId && !hasExternalNumber && !hasLines && !hasFiles) {
|
||||
if (!hasNumber && !hasDate && !hasCreatedAt && !hasSupplierId && !hasEntityId && !hasExternalNumber && !hasLines && !hasFiles) {
|
||||
throw new Error('Invalid delivery');
|
||||
}
|
||||
|
||||
@@ -63,6 +68,13 @@ export default function update(provider) {
|
||||
if (!number) {
|
||||
throw new Error('Invalid delivery');
|
||||
}
|
||||
await assertUniqueManifestNumber(provider, tx, {
|
||||
companyId,
|
||||
type: queries.DELIVERY_TYPE,
|
||||
number,
|
||||
excludeId: id,
|
||||
errorMessage: 'Delivery number already exists',
|
||||
});
|
||||
}
|
||||
|
||||
let date = summary.date;
|
||||
@@ -82,12 +94,16 @@ export default function update(provider) {
|
||||
}
|
||||
|
||||
let supplierId = summary.supplierId;
|
||||
if (hasSupplierId) {
|
||||
if (hasSupplierId || hasEntityId) {
|
||||
const val = hasSupplierId ? patch.supplierId : patch.entityId;
|
||||
if (val == null) {
|
||||
throw new Error('No supplier selected');
|
||||
}
|
||||
supplierId = await assertSupplier(
|
||||
provider,
|
||||
tx,
|
||||
companyId,
|
||||
patch.supplierId ?? null,
|
||||
val,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
57
src/store/healthcheck/check.js
Normal file
57
src/store/healthcheck/check.js
Normal file
@@ -0,0 +1,57 @@
|
||||
import * as mssqlQueries from '../../providers/mssql/queries/healthcheck.js';
|
||||
import * as sqliteQueries from '../../providers/sqlite3/queries/healthcheck.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
export default function check(provider) {
|
||||
const isSqlite = provider?.dialect === 'sqlite3';
|
||||
const queries = isSqlite ? sqliteQueries : mssqlQueries;
|
||||
|
||||
/**
|
||||
* Executes a database health check:
|
||||
* 1. Ensures the healthcheck table has one row (creates with sequence 0 if not).
|
||||
* 2. Selects that row for update with minimal, reasonable locking within a transaction.
|
||||
* 3. Updates the sequence by 1 in a separate statement within the transaction.
|
||||
*
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<{ok: boolean, sequence: number}>} The health check result.
|
||||
*
|
||||
* @example
|
||||
* const result = await store.healthcheck.check();
|
||||
* // => { ok: true, sequence: 1 }
|
||||
*/
|
||||
return async (tx) => {
|
||||
const runTx = async (runner) => {
|
||||
// 1. Ensure table has one row, if not create that row with number 0
|
||||
await runner.query(queries.ENSURE_ROW);
|
||||
|
||||
// 2. Select for update on that row with minimal, reasonable locking
|
||||
const selected = await runner.query(queries.SELECT_FOR_UPDATE);
|
||||
const row = selected.rows[0];
|
||||
if (!row) {
|
||||
throw new Error('Healthcheck row not found');
|
||||
}
|
||||
|
||||
// 3. Updating the number by 1 and do an update (not in one statement, but in a tx)
|
||||
const currentSeq = Number(row.sequence ?? 0);
|
||||
const nextSeq = currentSeq + 1;
|
||||
|
||||
await runner.query(queries.UPDATE_SEQUENCE, {
|
||||
id: row.id,
|
||||
sequence: nextSeq,
|
||||
});
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
sequence: nextSeq,
|
||||
};
|
||||
};
|
||||
|
||||
if (tx) {
|
||||
return runTx(makeRunner(provider, tx));
|
||||
}
|
||||
if (typeof provider?.transaction === 'function') {
|
||||
return provider.transaction((runner) => runTx(makeRunner(provider, runner)));
|
||||
}
|
||||
return runTx(makeRunner(provider));
|
||||
};
|
||||
}
|
||||
@@ -104,3 +104,32 @@ export async function loadDoc(runnerOrPool, txOrParams, maybeParams) {
|
||||
lines: lines.rows.map(shapeLine),
|
||||
};
|
||||
}
|
||||
|
||||
export async function assertUniqueManifestNumber(runnerOrPool, txOrParams, maybeParams) {
|
||||
let runner;
|
||||
let params;
|
||||
|
||||
if (maybeParams !== undefined) {
|
||||
runner = makeRunner(runnerOrPool, txOrParams);
|
||||
params = maybeParams;
|
||||
} else {
|
||||
runner = makeRunner(runnerOrPool);
|
||||
params = txOrParams;
|
||||
}
|
||||
|
||||
const { companyId, type, number, excludeId, errorMessage } = params;
|
||||
if (!number) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isSqlite = runner?.dialect === 'sqlite3';
|
||||
const sql = isSqlite
|
||||
? 'SELECT id FROM manifest WHERE company_id = @companyId AND "type" = @type AND "number" = @number'
|
||||
: 'SELECT id FROM manifest WHERE company_id = @companyId AND [type] = @type AND [number] = @number';
|
||||
|
||||
const res = await runner.query(sql, { companyId, type, number });
|
||||
const row = res.rows[0];
|
||||
if (row && (!excludeId || row.id !== excludeId)) {
|
||||
throw new Error(errorMessage || `${type.charAt(0).toUpperCase() + type.slice(1)} number already exists`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import taxEnsure from '../tax/ensure.js';
|
||||
import { insertLines, normalizeLines, parseDate } from '../manifestLines.js';
|
||||
import { assertCustomerEntity, loadDoc } from '../manifestDoc/helpers.js';
|
||||
import { assertCustomerEntity, assertUniqueManifestNumber, loadDoc } from '../manifestDoc/helpers.js';
|
||||
import { recordOrderHistory } from '../articlehistory/record.js';
|
||||
import { syncOrderSummary } from './syncSummary.js';
|
||||
import makeRunner from '../runner.js';
|
||||
@@ -36,12 +36,12 @@ export default function create(provider) {
|
||||
* @param {object} body - The order input.
|
||||
* @param {string} body.number - The order number.
|
||||
* @param {string} body.date - The order date.
|
||||
* @param {number} [body.entityId] - The id of the customer entity.
|
||||
* @param {number} body.entityId - The id of the customer entity.
|
||||
* @param {string} [body.externalNumber] - An external (customer) reference number.
|
||||
* @param {Array<{sku?: string, name?: string, pu?: number, amount: number, net: number, rebate?: number, taxrate: number, comment?: string|null}>} [body.lines] - The order lines.
|
||||
* @param {object} [tx] - Optional transaction to run within.
|
||||
* @returns {Promise<{id: number, number: string, type: string, entityId: number|null, externalNumber: string|null, date: string, lines: Array<{id: number, sku: string|null, name: string|null, pu: number, amount: number, net: number, rebate: number, taxrate: number, comment: string|null}>}>} The created order.
|
||||
* @throws {Error} If the order is invalid.
|
||||
* @returns {Promise<{id: number, number: string, type: string, entityId: number, externalNumber: string|null, date: string, lines: Array<{id: number, sku: string|null, name: string|null, pu: number, amount: number, net: number, rebate: number, taxrate: number, comment: string|null}>}>} The created order.
|
||||
* @throws {Error} If the order is invalid, no entity is selected, or entity not found.
|
||||
*
|
||||
* @example
|
||||
* const order = await store.order.create(42, { number: 'B-2026-001', date: '2026-09-15', entityId: 12, lines: [...] });
|
||||
@@ -66,12 +66,23 @@ export default function create(provider) {
|
||||
const runCreate = async (runner) => {
|
||||
const { companyId, companyuserId } = await access(googleAuthId, runner);
|
||||
|
||||
if (body.entityId == null) {
|
||||
throw new Error('No entity selected');
|
||||
}
|
||||
|
||||
const entityId = await assertCustomerEntity(
|
||||
runner,
|
||||
companyId,
|
||||
body.entityId ?? null,
|
||||
body.entityId,
|
||||
);
|
||||
|
||||
await assertUniqueManifestNumber(runner, {
|
||||
companyId,
|
||||
type: orderType,
|
||||
number,
|
||||
errorMessage: 'Order number already exists',
|
||||
});
|
||||
|
||||
const created = await runner.query(createManifestSql, {
|
||||
companyId,
|
||||
number,
|
||||
|
||||
@@ -18,7 +18,7 @@ import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyA
|
||||
import nextNumber from '../numbers/nextNumber.js';
|
||||
import taxEnsure from '../tax/ensure.js';
|
||||
import { insertLines, normalizeLines, parseDate } from '../manifestLines.js';
|
||||
import { assertCustomerEntity, loadDoc } from '../manifestDoc/helpers.js';
|
||||
import { assertCustomerEntity, assertUniqueManifestNumber, loadDoc } from '../manifestDoc/helpers.js';
|
||||
import { recordOrderHistory } from '../articlehistory/record.js';
|
||||
import { syncOrderSummary } from './syncSummary.js';
|
||||
import makeRunner from '../runner.js';
|
||||
@@ -90,6 +90,13 @@ export default function createFromQuote(provider) {
|
||||
number = await allocateNumber(companyId, orderType, runner);
|
||||
}
|
||||
|
||||
await assertUniqueManifestNumber(runner, {
|
||||
companyId,
|
||||
type: orderType,
|
||||
number,
|
||||
errorMessage: 'Order number already exists',
|
||||
});
|
||||
|
||||
const targetEntityId = body.entityId !== undefined ? body.entityId : quoteDoc.entityId;
|
||||
if (targetEntityId == null) {
|
||||
throw new Error('No entity selected');
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import taxEnsure from '../tax/ensure.js';
|
||||
import { insertLines, normalizeLines, parseDate } from '../manifestLines.js';
|
||||
import { assertCustomerEntity, loadDoc, shapeSummary } from '../manifestDoc/helpers.js';
|
||||
import { assertCustomerEntity, assertUniqueManifestNumber, loadDoc, shapeSummary } from '../manifestDoc/helpers.js';
|
||||
import { syncOrderSummary } from './syncSummary.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
@@ -89,6 +89,13 @@ export default function update(provider) {
|
||||
if (!number) {
|
||||
throw new Error('Invalid order');
|
||||
}
|
||||
await assertUniqueManifestNumber(runner, {
|
||||
companyId,
|
||||
type: orderType,
|
||||
number,
|
||||
excludeId: id,
|
||||
errorMessage: 'Order number already exists',
|
||||
});
|
||||
}
|
||||
|
||||
let date = summary.date;
|
||||
@@ -109,10 +116,13 @@ export default function update(provider) {
|
||||
|
||||
let entityId = summary.entityId;
|
||||
if (hasEntityId) {
|
||||
if (patch.entityId == null) {
|
||||
throw new Error('No entity selected');
|
||||
}
|
||||
entityId = await assertCustomerEntity(
|
||||
runner,
|
||||
companyId,
|
||||
patch.entityId ?? null,
|
||||
patch.entityId,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import taxEnsure from '../tax/ensure.js';
|
||||
import { insertLines, normalizeLines, parseDate } from '../manifestLines.js';
|
||||
import { assertCustomerEntity, loadDoc } from '../manifestDoc/helpers.js';
|
||||
import { assertCustomerEntity, assertUniqueManifestNumber, loadDoc } from '../manifestDoc/helpers.js';
|
||||
import { syncQuoteSummary } from './syncSummary.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
@@ -64,6 +64,13 @@ export default function create(provider) {
|
||||
body.entityId ?? null,
|
||||
);
|
||||
|
||||
await assertUniqueManifestNumber(runner, {
|
||||
companyId,
|
||||
type: quoteType,
|
||||
number,
|
||||
errorMessage: 'Quote number already exists',
|
||||
});
|
||||
|
||||
const created = await runner.query(createManifestSql, {
|
||||
companyId,
|
||||
number,
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import taxEnsure from '../tax/ensure.js';
|
||||
import { insertLines, normalizeLines, parseDate } from '../manifestLines.js';
|
||||
import { assertCustomerEntity, loadDoc, shapeSummary } from '../manifestDoc/helpers.js';
|
||||
import { assertCustomerEntity, assertUniqueManifestNumber, loadDoc, shapeSummary } from '../manifestDoc/helpers.js';
|
||||
import { syncQuoteSummary } from './syncSummary.js';
|
||||
import makeRunner from '../runner.js';
|
||||
|
||||
@@ -89,6 +89,13 @@ export default function update(provider) {
|
||||
if (!number) {
|
||||
throw new Error('Invalid quote');
|
||||
}
|
||||
await assertUniqueManifestNumber(runner, {
|
||||
companyId,
|
||||
type: quoteType,
|
||||
number,
|
||||
excludeId: id,
|
||||
errorMessage: 'Quote number already exists',
|
||||
});
|
||||
}
|
||||
|
||||
let date = summary.date;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
||||
import taxEnsure from '../tax/ensure.js';
|
||||
import { insertLines, parseDate } from '../manifestLines.js';
|
||||
import { assertUniqueManifestNumber } from '../manifestDoc/helpers.js';
|
||||
import makeRunner from '../runner.js';
|
||||
import { loadShipment, queriesFor } from './helpers.js';
|
||||
import { syncOrderSummary } from '../order/syncSummary.js';
|
||||
@@ -212,6 +213,13 @@ export default function create(provider) {
|
||||
const nextY = Math.max(existingShipments.length + 1, maxY + 1);
|
||||
const shipmentNumber = `${order.number}${shipmentPrefix}${nextY}`;
|
||||
|
||||
await assertUniqueManifestNumber(runner, {
|
||||
companyId,
|
||||
type: 'shipment',
|
||||
number: shipmentNumber,
|
||||
errorMessage: 'Shipment number already exists',
|
||||
});
|
||||
|
||||
// 7. Create shipment manifest header
|
||||
const createdRes = await runner.query(q.CREATE_MANIFEST, {
|
||||
companyId,
|
||||
|
||||
@@ -65,14 +65,17 @@ describe('store.delivery', () => {
|
||||
assert.notEqual(a.number, b.number);
|
||||
});
|
||||
|
||||
it('allows a delivery without supplier', async () => {
|
||||
const d = await store.delivery.create(gid, { date: isoNow(), lines: [] });
|
||||
assert.equal(d.supplierId, null);
|
||||
it('rejects a delivery without supplier', async () => {
|
||||
await assert.rejects(
|
||||
() => store.delivery.create(gid, { date: isoNow(), lines: [] }),
|
||||
{ message: 'No supplier selected' },
|
||||
);
|
||||
});
|
||||
|
||||
it('validates input', async () => {
|
||||
await assert.rejects(() => create({ date: 'garbage' }), { message: 'Invalid delivery' });
|
||||
await assert.rejects(() => create({ createdAt: 'garbage' }), { message: 'Invalid delivery' });
|
||||
await assert.rejects(() => create({ supplierId: null }), { message: 'No supplier selected' });
|
||||
await assert.rejects(() => create({ supplierId: '1' }), { message: 'Invalid supplierId' });
|
||||
await assert.rejects(() => create({ supplierId: 999999 }), { message: 'Supplier not found' });
|
||||
await assert.rejects(() => create({ lines: 'x' }), { message: 'Invalid lines' });
|
||||
@@ -113,8 +116,10 @@ describe('store.delivery', () => {
|
||||
const cleared = await store.delivery.update(gid, d.id, { externalNumber: ' ' });
|
||||
assert.equal(cleared.externalNumber, null);
|
||||
|
||||
const noSupplier = await store.delivery.update(gid, d.id, { supplierId: null });
|
||||
assert.equal(noSupplier.supplierId, null);
|
||||
await assert.rejects(
|
||||
() => store.delivery.update(gid, d.id, { supplierId: null }),
|
||||
{ message: 'No supplier selected' },
|
||||
);
|
||||
});
|
||||
|
||||
it('replaces lines of an unbooked delivery', async () => {
|
||||
@@ -133,6 +138,15 @@ describe('store.delivery', () => {
|
||||
assert.equal((await store.delivery.getById(gid, d.id)).lines[0].amount, 4);
|
||||
});
|
||||
|
||||
it('refuses duplicate delivery numbers on update', async () => {
|
||||
const d1 = await create();
|
||||
const d2 = await create();
|
||||
await assert.rejects(
|
||||
() => store.delivery.update(gid, d2.id, { number: d1.number }),
|
||||
{ message: 'Delivery number already exists' },
|
||||
);
|
||||
});
|
||||
|
||||
it('validates input', async () => {
|
||||
const d = await create();
|
||||
await assert.rejects(() => store.delivery.update(gid, d.id, {}), { message: 'Invalid delivery' });
|
||||
@@ -287,7 +301,8 @@ describe('store.delivery', () => {
|
||||
const rt = await createTenant(store, { name: 'Delivery Rebuild GmbH' });
|
||||
await store.warehouse.create(rt.googleAuthId, { name: 'Rebuild WH' });
|
||||
await createArticle(store, rt, { sku: 'RB-1', track_stock: true });
|
||||
const d = await store.delivery.create(rt.googleAuthId, { date: isoNow(), lines: [line('RB-1', 3)] });
|
||||
const rs = await store.supplier.create(rt.googleAuthId, { name: 'Rebuild Supplier' });
|
||||
const d = await store.delivery.create(rt.googleAuthId, { supplierId: rs.id, date: isoNow(), lines: [line('RB-1', 3)] });
|
||||
await store.delivery.book(rt.googleAuthId, d.id);
|
||||
|
||||
const before = await store.delivery.list(rt.googleAuthId);
|
||||
|
||||
Reference in New Issue
Block a user