Compare commits

..

2 Commits

Author SHA1 Message Date
seb
5cb38874ca u 2026-10-20 02:22:58 +02:00
seb
4b34902b92 u 2026-10-19 23:56:56 +02:00
13 changed files with 166 additions and 47 deletions

View File

@@ -181,12 +181,10 @@ Returns the full detail of an article by its SKU, including unit, brand, categor
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `sku` | `string` | The article SKU. |
| `[tx]` | `object` | Optional transaction. |
**Returns**
`Promise<{article: {id: number, sku: string, name: string, slug: string, desc: string|null, seo: string|null, unitamount: number|null, weight: number|null, track_stock: boolean, unit: {si: string|null, basesi: string|null, basesifactor: number|null, symbol: string|null, name: string|null}, brand: {id: number|null, name: string, fullHash: string|null, thumbW: number|null, thumbH: number|null, thumbHash: string|null}|null, categoryIds: number[], photos: Array<{sort: number, fullHash: string, fullW: number, fullH: number, fullSize: number, thumbW: number, thumbH: number, thumbHash: string}>, eans: string[], prices: Array<{minmultiplier: number, net: number, taxRate: number, customergroupId: number}>, suppliers: Array<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, sort: number, price: {net: number, taxId: number, taxRate?: number}|null, incoming: Array<{date: string, amount: number}>}>, optionsCount: number, articleListCount: number, childCount: number, parentArticleId: number|null, parentSku: string|null}}>` — The full article detail.
`Promise<{article: {id: number, sku: string, name: string, slug: string, desc: string|null, seo: string|null, unitamount: number|null, weight: number|null, track_stock: boolean, unit: {si: string|null, basesi: string|null, basesifactor: number|null, symbol: string|null, name: string|null}, brand: {id: number|null, name: string, fullHash: string|null, thumbW: number|null, thumbH: number|null, thumbHash: string|null}|null, categoryIds: number[], photos: Array<{sort: number, fullHash: string, fullW: number, fullH: number, fullSize: number, thumbW: number, thumbH: number, thumbHash: string}>, eans: string[], prices: Array<{minmultiplier: number, net: number, taxRate: number, customergroupId: number}>, suppliers: Array<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, sort: number, price: {net: number, taxId: number, taxRate?: number}|null, incoming: Array<{date: string, amount: number}>}>, warehouses: Array<{id: number, name: string, sort: number, stock: number}>, undeliveredOrders: Array<{orderId: number, orderNumber: string, date: string, customerName: string|null, amount: number}>, optionsCount: number, articleListCount: number, childCount: number, parentArticleId: number|null, parentSku: string|null}}>` — The full article detail.
**Throws**

View File

@@ -44,7 +44,7 @@ Creates a new company together with its root category, POS customer group, defau
| --- | --- | --- |
| `input` | `object` | The company creation input. |
| `input.iso639` | `string` | The ISO 639 language code for the company. |
| `input.name` | `string` | The company name (must be unique). |
| `input.name` | `string` | The company name. |
| `input.taxrate` | `number` | The standard tax rate in percent. |
| `input.reducedtaxrate` | `number` | The reduced tax rate in percent. |
| `input.googleAuthId` | `number` | The id of the Google auth user to link. |
@@ -54,10 +54,6 @@ Creates a new company together with its root category, POS customer group, defau
`Promise<{id: number, rootCategoryId: number, languageId: number, taxrateId: number, reducedtaxrateId: number, taxfreerateId: number, posCustomerGroupId: number}>` — The created company ids.
**Throws**
`Error` — If the company name is already taken.
**Example**
```js
@@ -208,7 +204,7 @@ Updates an existing company's name, language and tax rates.
| `id` | `number` | The id of the company to update. |
| `input` | `object` | The update input. |
| `input.iso639` | `string` | The ISO 639 language code. |
| `input.name` | `string` | The new company name (must be unique). |
| `input.name` | `string` | The new company name. |
| `input.taxrate` | `number` | The standard tax rate in percent. |
| `input.reducedtaxrate` | `number` | The reduced tax rate in percent. |
| `[tx]` | `object` | Optional transaction to run within. |
@@ -219,7 +215,7 @@ Updates an existing company's name, language and tax rates.
**Throws**
`Error` — If the company is not found or the name is taken.
`Error` — If the company is not found.
**Example**

4
API.md
View File

@@ -31,7 +31,7 @@ The store is exposed as a `LibDashStore` instance (see `src/index.js`). Each met
- **categorypic**: `id PK, category_id->category, pic_id->pic, sort:i=0, UQ(category_id, pic_id), UQ(category_id, sort)`
- **categoryproperty**: `id PK, category_id->category, property_id->propertyname, value:txt, sort:i=0`
- **categorytext**: `id PK, category_id->category, language_id->language, name:s(255), slug:s(255), seo?:txt, desc?:txt, UQ(category_id, language_id)`
- **company**: `id PK, name:s(255) UQ, root_category_id?->category, default_language_id?->language, taxrate?->tax, reducedtaxrate?->tax, taxfreerate?->tax, poscustomergroup_id->customergroup`
- **company**: `id PK, name:s(255), root_category_id?->category, default_language_id?->language, taxrate?->tax, reducedtaxrate?->tax, taxfreerate?->tax, poscustomergroup_id->customergroup`
- **companyhistory**: `id PK, company_id->company, companyuser_id?->companyuser, date:dt, text:txt`
- **companysetting**: `id PK, company_id->company, key:s(255), value:txt, frontend:b=0, writeonly:b=0, UQ(company_id, key)`
- **companyuser**: `id PK, google_auth_id->google_auth, company_id->company, UQ(google_auth_id, company_id)`
@@ -111,7 +111,7 @@ The store is exposed as a `LibDashStore` instance (see `src/index.js`). Each met
- `createUnderParent(input: {googleAuthId: number, parentId: number, name: string, desc?: string, seo?: string, track_stock?: boolean|number}, tx?: object): Promise<{id: number, parentId: number, name: string, sku: string, track_stock: boolean}>`
- `delete(googleAuthId: number, sku: string, optionsOrTx?: object|*, maybeTx?: object): Promise<void>`
- `deleteImage(googleAuthId: number, sku: string, fullHash: string, tx?: object): Promise<void>`
- `getBySku(googleAuthId: number, sku: string, tx?: object): Promise<{article: {id: number, sku: string, name: string, slug: string, desc: string|null, seo: string|null, unitamount: number|null, weight: number|null, track_stock: boolean, unit: {si: string|null, basesi: string|null, basesifactor: number|null, symbol: string|null, name: string|null}, brand: {id: number|null, name: string, fullHash: string|null, thumbW: number|null, thumbH: number|null, thumbHash: string|null}|null, categoryIds: number[], photos: Array<{sort: number, fullHash: string, fullW: number, fullH: number, fullSize: number, thumbW: number, thumbH: number, thumbHash: string}>, eans: string[], prices: Array<{minmultiplier: number, net: number, taxRate: number, customergroupId: number}>, suppliers: Array<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, sort: number, price: {net: number, taxId: number, taxRate?: number}|null, incoming: Array<{date: string, amount: number}>}>, optionsCount: number, articleListCount: number, childCount: number, parentArticleId: number|null, parentSku: string|null}}>`
- `getBySku(googleAuthId: number): Promise<{article: {id: number, sku: string, name: string, slug: string, desc: string|null, seo: string|null, unitamount: number|null, weight: number|null, track_stock: boolean, unit: {si: string|null, basesi: string|null, basesifactor: number|null, symbol: string|null, name: string|null}, brand: {id: number|null, name: string, fullHash: string|null, thumbW: number|null, thumbH: number|null, thumbHash: string|null}|null, categoryIds: number[], photos: Array<{sort: number, fullHash: string, fullW: number, fullH: number, fullSize: number, thumbW: number, thumbH: number, thumbHash: string}>, eans: string[], prices: Array<{minmultiplier: number, net: number, taxRate: number, customergroupId: number}>, suppliers: Array<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, sort: number, price: {net: number, taxId: number, taxRate?: number}|null, incoming: Array<{date: string, amount: number}>}>, warehouses: Array<{id: number, name: string, sort: number, stock: number}>, undeliveredOrders: Array<{orderId: number, orderNumber: string, date: string, customerName: string|null, amount: number}>, optionsCount: number, articleListCount: number, childCount: number, parentArticleId: number|null, parentSku: string|null}}>`
- `getHistoryBySku(googleAuthId: number, sku: string, opts?: {limit?: number}, tx?: object): Promise<Array<{id: number, companyuserId: number|null, date: string, text: string, meta: string|null}>>`
- `importRows(input: {googleAuthId: number, rows: Array<object>}, tx?: object): Promise<{imported: Array<object>, skipped: Array<object>, errors: Array<object>}>`
- `listChildren(googleAuthId: number, parentSku: string, tx?: object): Promise<Array<{id: number, sku: string, parentsort: number, trackStock: boolean, unitamount: number, weight: number, name: string|null, slug: string|null, attributeValueId: number|null, attributeValue: string|null}>>`

View File

@@ -42,12 +42,11 @@ Company-scoped methods take **no** `companyId` argument: they use `google_auth.s
For `POST /api/company`:
1. Fails if `name` is taken (`Company name not available`)
2. Ensures language by `iso639` (get or create)
3. Ensures tax rows for `taxrate`, `reducedtaxrate`, and `0` → `taxfreerateId`
4. Creates root category (`parentId = null`)
5. Creates POS `customergroup` (name `POS`), then inserts company with `poscustomergroup_id` (**NOT NULL**), then links the group via `customergroup.company_id`
6. Links creator as `companyuser` (`googleAuthId` → `company_id`)
1. Ensures language by `iso639` (get or create)
2. Ensures tax rows for `taxrate`, `reducedtaxrate`, and `0` → `taxfreerateId`
3. Creates root category (`parentId = null`)
4. Creates POS `customergroup` (name `POS`), then inserts company with `poscustomergroup_id` (**NOT NULL**), then links the group via `customergroup.company_id`
5. Links creator as `companyuser` (`googleAuthId` → `company_id`)
`company.poscustomergroup_id` is required (POS pricing in `getTreeForCompany` / category articles). Circular FK with `customergroup.company_id`: the group is inserted first with `company_id` null, then linked after the company row exists.
@@ -59,7 +58,7 @@ Returns only companies where `googleAuthId` has a `companyuser` row.
For `PATCH /api/company/:id`:
1. Fails if company missing / name taken by another company
1. Fails if company missing
2. Ensures lang + tax rates
3. Updates `name`, `default_language_id`, `taxrate`, `reducedtaxrate`
(`taxfreerateId` / root category unchanged)

View File

@@ -347,7 +347,7 @@ const SCHEMA_TABLES = [
['categorypic', 'id PK, category_id->category, pic_id->pic, sort:i=0, UQ(category_id, pic_id), UQ(category_id, sort)'],
['categoryproperty', 'id PK, category_id->category, property_id->propertyname, value:txt, sort:i=0'],
['categorytext', 'id PK, category_id->category, language_id->language, name:s(255), slug:s(255), seo?:txt, desc?:txt, UQ(category_id, language_id)'],
['company', 'id PK, name:s(255) UQ, root_category_id?->category, default_language_id?->language, taxrate?->tax, reducedtaxrate?->tax, taxfreerate?->tax, poscustomergroup_id->customergroup'],
['company', 'id PK, name:s(255), root_category_id?->category, default_language_id?->language, taxrate?->tax, reducedtaxrate?->tax, taxfreerate?->tax, poscustomergroup_id->customergroup'],
['companyhistory', 'id PK, company_id->company, companyuser_id?->companyuser, date:dt, text:txt'],
['companysetting', 'id PK, company_id->company, key:s(255), value:txt, frontend:b=0, writeonly:b=0, UQ(company_id, key)'],
['companyuser', 'id PK, google_auth_id->google_auth, company_id->company, UQ(google_auth_id, company_id)'],

View File

@@ -653,7 +653,43 @@ SELECT
WHERE w.company_id = a.company_id
ORDER BY w.sort ASC, w.name ASC
FOR JSON PATH
) AS warehousesJson
) AS warehousesJson,
(
SELECT
m.id AS orderId,
m.[number] AS orderNumber,
m.[date] AS [date],
COALESCE(os.customer_name, LTRIM(RTRIM(ISNULL(e.first_name + ' ', '') + ISNULL(e.name, '')))) AS customerName,
ROUND(SUM(ma.amount) - COALESCE((
SELECT SUM(ma_s.amount)
FROM manifest m_s
INNER JOIN manifestarticle ma_s ON ma_s.manifest_id = m_s.id
WHERE m_s.company_id = m.company_id
AND m_s.[type] = 'shipment'
AND ma_s.sku = a.sku
AND m_s.[number] LIKE m.[number] + COALESCE((SELECT prefix FROM numbers WHERE company_id = m.company_id AND [type] = 'shipment'), '-L-') + '%'
), 0), 3) AS amount
FROM manifest m
INNER JOIN manifestarticle ma ON ma.manifest_id = m.id
LEFT JOIN ordersummary os ON os.manifest_id = m.id
LEFT JOIN entity e ON e.id = m.entity_id
WHERE m.company_id = a.company_id
AND m.[type] = 'order'
AND ma.sku = a.sku
AND COALESCE(os.is_shipped, 0) = 0
GROUP BY m.id, m.[number], m.[date], os.customer_name, e.first_name, e.name
HAVING (SUM(ma.amount) - COALESCE((
SELECT SUM(ma_s.amount)
FROM manifest m_s
INNER JOIN manifestarticle ma_s ON ma_s.manifest_id = m_s.id
WHERE m_s.company_id = m.company_id
AND m_s.[type] = 'shipment'
AND ma_s.sku = a.sku
AND m_s.[number] LIKE m.[number] + COALESCE((SELECT prefix FROM numbers WHERE company_id = m.company_id AND [type] = 'shipment'), '-L-') + '%'
), 0)) > 0
ORDER BY m.[date] ASC, m.id ASC
FOR JSON PATH
) AS undeliveredOrdersJson
FROM article a
LEFT JOIN articletext at
ON at.article_id = a.id AND at.language_id = auth.languageId

View File

@@ -118,7 +118,6 @@ BEGIN
reducedtaxrate INT NULL,
taxfreerate INT NULL,
poscustomergroup_id INT NOT NULL,
CONSTRAINT UQ_company_name UNIQUE (name),
CONSTRAINT FK_company_root_category FOREIGN KEY (root_category_id) REFERENCES category(id) ON DELETE SET NULL,
CONSTRAINT FK_company_default_language FOREIGN KEY (default_language_id) REFERENCES language(id) ON DELETE SET NULL,
CONSTRAINT FK_company_taxrate FOREIGN KEY (taxrate) REFERENCES tax(id) ON DELETE NO ACTION,

View File

@@ -288,7 +288,43 @@ SELECT auth.*,
GROUP BY l.warehouse_id
) stock_calc ON stock_calc.warehouse_id = w.id
WHERE w.company_id = a.company_id
ORDER BY w.sort ASC, w.name ASC))
ORDER BY w.sort ASC, w.name ASC)),
'undeliveredOrdersJson', json((
SELECT COALESCE(json_group_array(json_object(
'orderId', uo.orderId,
'orderNumber', uo.orderNumber,
'date', uo.date,
'customerName', uo.customerName,
'amount', uo.amount
)), '[]')
FROM (
SELECT
m.id AS orderId,
m."number" AS orderNumber,
m."date" AS date,
COALESCE(os.customer_name, TRIM(COALESCE(e.first_name || ' ', '') || COALESCE(e.name, ''))) AS customerName,
ROUND(SUM(ma.amount) - COALESCE((
SELECT SUM(ma_s.amount)
FROM manifest m_s
INNER JOIN manifestarticle ma_s ON ma_s.manifest_id = m_s.id
WHERE m_s.company_id = m.company_id
AND m_s."type" = 'shipment'
AND ma_s.sku = a.sku
AND m_s."number" LIKE m."number" || COALESCE((SELECT prefix FROM numbers WHERE company_id = m.company_id AND "type" = 'shipment'), '-L-') || '%'
), 0), 3) AS amount
FROM manifest m
INNER JOIN manifestarticle ma ON ma.manifest_id = m.id
LEFT JOIN ordersummary os ON os.manifest_id = m.id
LEFT JOIN entity e ON e.id = m.entity_id
WHERE m.company_id = a.company_id
AND m."type" = 'order'
AND ma.sku = a.sku
AND COALESCE(os.is_shipped, 0) = 0
GROUP BY m.id, m."number", m."date", os.customer_name, e.first_name, e.name
HAVING amount > 0
ORDER BY m."date" ASC, m.id ASC
) uo
))
) AS articleJson
FROM auth
INNER JOIN article a ON a.id = auth.articleId

View File

@@ -53,7 +53,7 @@ CREATE TABLE IF NOT EXISTS pic (
export const INIT_COMPANY = `
CREATE TABLE IF NOT EXISTS company (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL COLLATE NOCASE UNIQUE,
name TEXT NOT NULL COLLATE NOCASE,
root_category_id INTEGER,
default_language_id INTEGER,
taxrate INTEGER,

View File

@@ -16,9 +16,7 @@ export default function getBySku(provider) {
* categories, photos, EANs and prices.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {string} sku - The article SKU.
* @param {object} [tx] - Optional transaction.
* @returns {Promise<{article: {id: number, sku: string, name: string, slug: string, desc: string|null, seo: string|null, unitamount: number|null, weight: number|null, track_stock: boolean, unit: {si: string|null, basesi: string|null, basesifactor: number|null, symbol: string|null, name: string|null}, brand: {id: number|null, name: string, fullHash: string|null, thumbW: number|null, thumbH: number|null, thumbHash: string|null}|null, categoryIds: number[], photos: Array<{sort: number, fullHash: string, fullW: number, fullH: number, fullSize: number, thumbW: number, thumbH: number, thumbHash: string}>, eans: string[], prices: Array<{minmultiplier: number, net: number, taxRate: number, customergroupId: number}>, suppliers: Array<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, sort: number, price: {net: number, taxId: number, taxRate?: number}|null, incoming: Array<{date: string, amount: number}>}>, optionsCount: number, articleListCount: number, childCount: number, parentArticleId: number|null, parentSku: string|null}}>} The full article detail.
* @returns {Promise<{article: {id: number, sku: string, name: string, slug: string, desc: string|null, seo: string|null, unitamount: number|null, weight: number|null, track_stock: boolean, unit: {si: string|null, basesi: string|null, basesifactor: number|null, symbol: string|null, name: string|null}, brand: {id: number|null, name: string, fullHash: string|null, thumbW: number|null, thumbH: number|null, thumbHash: string|null}|null, categoryIds: number[], photos: Array<{sort: number, fullHash: string, fullW: number, fullH: number, fullSize: number, thumbW: number, thumbH: number, thumbHash: string}>, eans: string[], prices: Array<{minmultiplier: number, net: number, taxRate: number, customergroupId: number}>, suppliers: Array<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, sort: number, price: {net: number, taxId: number, taxRate?: number}|null, incoming: Array<{date: string, amount: number}>}>, warehouses: Array<{id: number, name: string, sort: number, stock: number}>, undeliveredOrders: Array<{orderId: number, orderNumber: string, date: string, customerName: string|null, amount: number}>, optionsCount: number, articleListCount: number, childCount: number, parentArticleId: number|null, parentSku: string|null}}>} The full article detail.
* @throws {Error} If the article is not found or the user is not authorized.
*
* @example
@@ -98,6 +96,13 @@ export default function getBySku(provider) {
sort: Number(w.sort ?? 0),
stock: Number(w.stock ?? 0),
})),
undeliveredOrders: parseJsonArray(a.undeliveredOrdersJson).map((uo) => ({
orderId: uo.orderId,
orderNumber: uo.orderNumber,
date: uo.date,
customerName: uo.customerName ?? null,
amount: Math.round(Number(uo.amount ?? 0) * 1000) / 1000,
})),
optionsCount: a.optionsCount,
optionslistId: a.optionslistId ?? null,
options: parseJsonArray(a.optionslistItemsJson).map((o) => ({

View File

@@ -13,13 +13,11 @@ import {
} from '../../providers/sqlite3/queries/customergroup.js';
import { ADD as MSSQL_ADD_COMPANYUSER } from '../../providers/mssql/queries/companyuser.js';
import { ADD as SQLITE_ADD_COMPANYUSER } from '../../providers/sqlite3/queries/companyuser.js';
import getByName from './getByName.js';
import langEnsure from '../lang/ensure.js';
import taxEnsure from '../tax/ensure.js';
import makeRunner from '../runner.js';
export default function create(provider) {
const nameTaken = getByName(provider);
const ensureLang = langEnsure(provider);
const ensureTax = taxEnsure(provider);
@@ -36,13 +34,12 @@ export default function create(provider) {
*
* @param {object} input - The company creation input.
* @param {string} input.iso639 - The ISO 639 language code for the company.
* @param {string} input.name - The company name (must be unique).
* @param {string} input.name - The company name.
* @param {number} input.taxrate - The standard tax rate in percent.
* @param {number} input.reducedtaxrate - The reduced tax rate in percent.
* @param {number} input.googleAuthId - The id of the Google auth user to link.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, rootCategoryId: number, languageId: number, taxrateId: number, reducedtaxrateId: number, taxfreerateId: number, posCustomerGroupId: number}>} The created company ids.
* @throws {Error} If the company name is already taken.
*
* @example
* const company = await store.company.create({
@@ -56,10 +53,6 @@ export default function create(provider) {
*/
return async ({ iso639, name, taxrate, reducedtaxrate, googleAuthId }, tx) => {
const runCreate = async (runner) => {
const existing = await nameTaken(name, runner);
if (existing) {
throw new Error('Company name not available');
}
const languageId = await ensureLang(iso639, runner);
const taxrateId = await ensureTax(taxrate, runner);

View File

@@ -1,14 +1,12 @@
import { UPDATE as MSSQL_UPDATE } from '../../providers/mssql/queries/company.js';
import { UPDATE as SQLITE_UPDATE } from '../../providers/sqlite3/queries/company.js';
import getById from './getById.js';
import getByName from './getByName.js';
import langEnsure from '../lang/ensure.js';
import taxEnsure from '../tax/ensure.js';
import makeRunner from '../runner.js';
export default function update(provider) {
const byId = getById(provider);
const byName = getByName(provider);
const ensureLang = langEnsure(provider);
const ensureTax = taxEnsure(provider);
const isSqlite = provider?.dialect === 'sqlite3';
@@ -20,12 +18,12 @@ export default function update(provider) {
* @param {number} id - The id of the company to update.
* @param {object} input - The update input.
* @param {string} input.iso639 - The ISO 639 language code.
* @param {string} input.name - The new company name (must be unique).
* @param {string} input.name - The new company name.
* @param {number} input.taxrate - The standard tax rate in percent.
* @param {number} input.reducedtaxrate - The reduced tax rate in percent.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, rootCategoryId: number, languageId: number, taxrateId: number, reducedtaxrateId: number, taxfreerateId: number}>} The updated company ids.
* @throws {Error} If the company is not found or the name is taken.
* @throws {Error} If the company is not found.
*
* @example
* const result = await store.company.update(1, { iso639: 'de', name: 'Acme', taxrate: 19, reducedtaxrate: 7 });
@@ -38,13 +36,6 @@ export default function update(provider) {
throw new Error('Company not found');
}
if (name !== company.name) {
const taken = await byName(name, runner);
if (taken) {
throw new Error('Company name not available');
}
}
const languageId = await ensureLang(iso639, runner);
const taxrateId = await ensureTax(taxrate, runner);
const reducedtaxrateId = await ensureTax(reducedtaxrate, runner);

View File

@@ -1,6 +1,6 @@
import { describe, it, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { createTestStore, createTenant, createArticle, makePng } from './helpers.js';
import { createTestStore, createTenant, createArticle, createCustomer, makePng } from './helpers.js';
describe('store.article', () => {
let ctx;
@@ -694,4 +694,70 @@ describe('store.article', () => {
assert.equal(res.article.suppliers[0].incoming[0].date, '2026-11-15T00:00:00.000Z');
});
});
describe('undelivered customer orders', () => {
it('returns total remaining unshipped quantity across open orders', async () => {
const art = await createArticle(store, tenant, { name: 'Order Article', sku: 'ORD-TEST-1' });
const cust = await createCustomer(store, tenant, 'Order Customer');
let res = await store.article.getBySku(gid, art.sku);
assert.deepEqual(res.article.undeliveredOrders, []);
const o1 = await store.order.create(gid, {
number: 'ORD-1001',
date: '2026-10-20',
entityId: cust.id,
lines: [{ sku: art.sku, name: 'Item', amount: 10, net: 5, taxrate: 19 }],
});
res = await store.article.getBySku(gid, art.sku);
assert.equal(res.article.undeliveredOrders.length, 1);
assert.equal(res.article.undeliveredOrders[0].orderId, o1.id);
assert.equal(res.article.undeliveredOrders[0].orderNumber, 'ORD-1001');
assert.equal(res.article.undeliveredOrders[0].customerName, 'Order Customer');
assert.equal(res.article.undeliveredOrders[0].amount, 10);
const o2 = await store.order.create(gid, {
number: 'ORD-1002',
date: '2026-10-21',
entityId: cust.id,
lines: [{ sku: art.sku, name: 'Item', amount: 5, net: 5, taxrate: 19 }],
});
res = await store.article.getBySku(gid, art.sku);
assert.equal(res.article.undeliveredOrders.length, 2);
assert.equal(res.article.undeliveredOrders[0].orderNumber, 'ORD-1001');
assert.equal(res.article.undeliveredOrders[0].amount, 10);
assert.equal(res.article.undeliveredOrders[1].orderNumber, 'ORD-1002');
assert.equal(res.article.undeliveredOrders[1].amount, 5);
await store.shipment.create(gid, {
orderId: o1.id,
lines: [{ sku: art.sku, amount: 4 }],
});
res = await store.article.getBySku(gid, art.sku);
assert.equal(res.article.undeliveredOrders.length, 2);
assert.equal(res.article.undeliveredOrders[0].amount, 6);
assert.equal(res.article.undeliveredOrders[1].amount, 5);
await store.shipment.create(gid, {
orderId: o1.id,
lines: [{ sku: art.sku, amount: 6 }],
});
res = await store.article.getBySku(gid, art.sku);
assert.equal(res.article.undeliveredOrders.length, 1);
assert.equal(res.article.undeliveredOrders[0].orderNumber, 'ORD-1002');
assert.equal(res.article.undeliveredOrders[0].amount, 5);
await store.shipment.create(gid, {
orderId: o2.id,
});
res = await store.article.getBySku(gid, art.sku);
assert.deepEqual(res.article.undeliveredOrders, []);
});
});
});