This commit is contained in:
seb
2026-09-26 23:06:05 +02:00
parent e491ecfa47
commit e7f92ebef8
41 changed files with 3632 additions and 1751 deletions

View File

@@ -15,6 +15,7 @@ Appends a new append-only entry to the ledger table.
| `googleAuthId` | `number` | The id of the Google auth user. | | `googleAuthId` | `number` | The id of the Google auth user. |
| `input` | `object` | Ledger entry payload. | | `input` | `object` | Ledger entry payload. |
| `input.manifestarticle_id` | `number` | ID of the referenced manifest line (can also pass manifestarticleId). | | `input.manifestarticle_id` | `number` | ID of the referenced manifest line (can also pass manifestarticleId). |
| `[input.warehouse_id]` | `number|null` | Optional warehouse ID (can also pass warehouseId). |
| `input.transaction_type` | `string` | Transaction type (can also pass transactionType). | | `input.transaction_type` | `string` | Transaction type (can also pass transactionType). |
| `input.amount` | `number` | Movement amount. | | `input.amount` | `number` | Movement amount. |
| `input.transaction_text` | `string` | Transaction memo/details (can also pass transactionText). | | `input.transaction_text` | `string` | Transaction memo/details (can also pass transactionText). |
@@ -22,7 +23,7 @@ Appends a new append-only entry to the ledger table.
**Returns** **Returns**
`Promise<{id: number, manifestarticle_id: number, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>` — The created ledger row. `Promise<{id: number, manifestarticle_id: number, warehouse_id: number|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>` — The created ledger row.
**Throws** **Throws**
@@ -33,7 +34,8 @@ Appends a new append-only entry to the ledger table.
```js ```js
const entry = await store.ledger.add(googleAuthId, { const entry = await store.ledger.add(googleAuthId, {
manifestarticle_id: 1, manifestarticle_id: 1,
transaction_type: 'PAYMENT', warehouse_id: 1,
transaction_type: 'DELIVERY',
amount: 100.5, amount: 100.5,
transaction_text: 'Invoice paid', transaction_text: 'Invoice paid',
}); });
@@ -43,7 +45,7 @@ const entry = await store.ledger.add(googleAuthId, {
*Source: `src/store/ledger/listByManifestarticleId.js`* *Source: `src/store/ledger/listByManifestarticleId.js`*
Lists ledger entries for a specific manifest article line, optionally filtered by transaction type. Lists ledger entries for a specific manifest article line, optionally filtered by transaction type and/or warehouse.
**Parameters** **Parameters**
@@ -51,12 +53,12 @@ Lists ledger entries for a specific manifest article line, optionally filtered b
| --- | --- | --- | | --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. | | `googleAuthId` | `number` | The id of the Google auth user. |
| `manifestarticleId` | `number` | The id of the manifest article line. | | `manifestarticleId` | `number` | The id of the manifest article line. |
| `[optionsOrType]` | `string|object` | Transaction type string or options object { transaction_type?: string, transactionType?: string }. | | `[optionsOrType]` | `string|object` | Transaction type string or options object { transaction_type?: string, transactionType?: string, warehouse_id?: number, warehouseId?: number }. |
| `[tx]` | `object` | Optional transaction to run within. | | `[tx]` | `object` | Optional transaction to run within. |
**Returns** **Returns**
`Promise<Array<{id: number, manifestarticle_id: number, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>` `Promise<Array<{id: number, manifestarticle_id: number, warehouse_id: number|null, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>`
**Throws** **Throws**
@@ -65,15 +67,15 @@ Lists ledger entries for a specific manifest article line, optionally filtered b
**Example** **Example**
```js ```js
const entries = await store.ledger.listByManifestarticleId(googleAuthId, 42, 'PAYMENT'); const entries = await store.ledger.listByManifestarticleId(googleAuthId, 42, 'DELIVERY');
// => [{ id, manifestarticle_id, sku, transaction_type, amount, transaction_text, hash_version, prev_hash, created_at }] // => [{ id, manifestarticle_id, warehouse_id, sku, transaction_type, amount, transaction_text, hash_version, prev_hash, created_at }]
``` ```
## `ledger.listBySku` ## `ledger.listBySku`
*Source: `src/store/ledger/listBySku.js`* *Source: `src/store/ledger/listBySku.js`*
Lists ledger entries for a given article SKU, optionally filtered by transaction type. Lists ledger entries for a given article SKU, optionally filtered by transaction type and/or warehouse.
**Parameters** **Parameters**
@@ -81,12 +83,12 @@ Lists ledger entries for a given article SKU, optionally filtered by transaction
| --- | --- | --- | | --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. | | `googleAuthId` | `number` | The id of the Google auth user. |
| `sku` | `string` | The article SKU. | | `sku` | `string` | The article SKU. |
| `[optionsOrType]` | `string|object` | Transaction type string or options object { transaction_type?: string, transactionType?: string }. | | `[optionsOrType]` | `string|object` | Transaction type string or options object { transaction_type?: string, transactionType?: string, warehouse_id?: number, warehouseId?: number }. |
| `[tx]` | `object` | Optional transaction to run within. | | `[tx]` | `object` | Optional transaction to run within. |
**Returns** **Returns**
`Promise<Array<{id: number, manifestarticle_id: number, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>` `Promise<Array<{id: number, manifestarticle_id: number, warehouse_id: number|null, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>`
**Throws** **Throws**
@@ -96,5 +98,5 @@ Lists ledger entries for a given article SKU, optionally filtered by transaction
```js ```js
const entries = await store.ledger.listBySku(googleAuthId, 'SKU-001', 'DELIVERY'); const entries = await store.ledger.listBySku(googleAuthId, 'SKU-001', 'DELIVERY');
// => [{ id, manifestarticle_id, sku, transaction_type, amount, transaction_text, hash_version, prev_hash, created_at }] // => [{ id, manifestarticle_id, warehouse_id, sku, transaction_type, amount, transaction_text, hash_version, prev_hash, created_at }]
``` ```

24
API.md
View File

@@ -33,7 +33,7 @@ The store is exposed as a `LibDashStore` instance (see `src/index.js`). Each met
- **file**: `id PK, hash:s(64), mimetype:s(255), name:s(255), size:bi, created:dt, modified:dt, content:bin, thumbavif?:bin, thumbx?:i, thumby?:i, meta?:txt` - **file**: `id PK, hash:s(64), mimetype:s(255), name:s(255), size:bi, created:dt, modified:dt, content:bin, thumbavif?:bin, thumbx?:i, thumby?:i, meta?:txt`
- **google_auth**: `id PK, email:s(320) UQ, picture?:s(2048), picturebinary?:bin, sub?:s(255) UQ, created_at:dt, selected_company?->company` - **google_auth**: `id PK, email:s(320) UQ, picture?:s(2048), picturebinary?:bin, sub?:s(255) UQ, created_at:dt, selected_company?->company`
- **language**: `id PK, iso639:s(10) UQ` - **language**: `id PK, iso639:s(10) UQ`
- **ledger**: `id PK, manifestarticle_id->manifestarticle, transaction_type:s(100), amount:f, transaction_text:txt, hash_version:i, prev_hash?:s(128) [append-only]` - **ledger**: `id PK, manifestarticle_id->manifestarticle, warehouse_id?->warehouse, transaction_type:s(100), amount:f, transaction_text:txt, hash_version:i, prev_hash?:s(128) [append-only]`
- **manifest**: `id PK, company_id->company, number:s(100), type:s(100), entity_id?->entity, external_number?:s(100), date:dt, created_at:dt` - **manifest**: `id PK, company_id->company, number:s(100), type:s(100), entity_id?->entity, external_number?:s(100), date:dt, created_at:dt`
- **manifestarticle**: `id PK, manifest_id->manifest, sku?:s(100), name?:s(255), pu:f=1, amount:f, net:f, comment?:txt, rebate:f=0, taxrate:f=0` - **manifestarticle**: `id PK, manifest_id->manifest, sku?:s(100), name?:s(255), pu:f=1, amount:f, net:f, comment?:txt, rebate:f=0, taxrate:f=0`
- **manifestattachment**: `id PK, manifest_id->manifest, file_id->file, sort:i=0, UQ(manifest_id, sort)` - **manifestattachment**: `id PK, manifest_id->manifest, file_id->file, sort:i=0, UQ(manifest_id, sort)`
@@ -49,6 +49,7 @@ The store is exposed as a `LibDashStore` instance (see `src/index.js`). Each met
- **tax**: `id PK, rate:d(18,4) UQ` - **tax**: `id PK, rate:d(18,4) UQ`
- **unit**: `id PK, company_id->company, si:s(50), basesi:s(50), basesifactor:f, UQ(company_id, si)` - **unit**: `id PK, company_id->company, si:s(50), basesi:s(50), basesifactor:f, UQ(company_id, si)`
- **unittext**: `id PK, unit_id->unit, language_id->language, symbol:s(50), name:s(255), UQ(unit_id, language_id)` - **unittext**: `id PK, unit_id->unit, language_id->language, symbol:s(50), name:s(255), UQ(unit_id, language_id)`
- **warehouse**: `id PK, company_id->company, name:s(255), UQ(company_id, name)`
## Table of Contents ## Table of Contents
@@ -171,9 +172,17 @@ The store is exposed as a `LibDashStore` instance (see `src/index.js`). Each met
- `order(googleAuthId: number, manifestId: number, input: {ids?: Array<number>}, tx?: object): Promise<{ids: Array<number>}>` - `order(googleAuthId: number, manifestId: number, input: {ids?: Array<number>}, tx?: object): Promise<{ids: Array<number>}>`
- `remove(googleAuthId: number, manifestId: number, id: number, tx?: object): Promise<void>` - `remove(googleAuthId: number, manifestId: number, id: number, tx?: object): Promise<void>`
- [ledger](API.ledger.md) - [ledger](API.ledger.md)
- `add(googleAuthId: number, input: {manifestarticle_id: number, transaction_type: string, amount: number, transaction_text: string}, tx?: object): Promise<{id: number, manifestarticle_id: number, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>` - `add(googleAuthId: number, input: {manifestarticle_id: number, warehouse_id?: number|null, transaction_type: string, amount: number, transaction_text: string}, tx?: object): Promise<{id: number, manifestarticle_id: number, warehouse_id: number|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>`
- `listByManifestarticleId(googleAuthId: number, manifestarticleId: number, optionsOrType?: string|object, tx?: object): Promise<Array<{id: number, manifestarticle_id: number, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>` - `listByManifestarticleId(googleAuthId: number, manifestarticleId: number, optionsOrType?: string|object, tx?: object): Promise<Array<{id: number, manifestarticle_id: number, warehouse_id: number|null, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>`
- `listBySku(googleAuthId: number, sku: string, optionsOrType?: string|object, tx?: object): Promise<Array<{id: number, manifestarticle_id: number, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>` - `listBySku(googleAuthId: number, sku: string, optionsOrType?: string|object, tx?: object): Promise<Array<{id: number, manifestarticle_id: number, warehouse_id: number|null, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>`
- [warehouse](API.warehouse.md)
- `create(googleAuthId: number, input: {name: string}, tx?: object): Promise<{id: number, name: string}>`
- `delete(googleAuthId: number, id: number, tx?: object): Promise<void>`
- `getById(googleAuthId: number, id: number, tx?: object): Promise<{id: number, name: string}|undefined>`
- `list(googleAuthId: number, tx?: object): Promise<Array<{id: number, name: string}>>`
- `update(googleAuthId: number, id: number, input: {name: string}, tx?: object): Promise<{id: number, name: string}>`
- [stock](API.stock.md)
- `adjust(googleAuthId: number, input: {sku?: string, warehouseId?: number, amount?: number, text?: string, externalNumber?: string, date?: string|Date, lines?: Array<object>}, tx?: object): Promise<{manifest: {id: number, number: string, type: string, date: string, createdAt: string}, lines: Array<object>, ledger: Array<object>}>`
- [posterminal](API.posterminal.md) - [posterminal](API.posterminal.md)
- `delete(googleAuthId: number, id: number, tx?: object): Promise<void>` - `delete(googleAuthId: number, id: number, tx?: object): Promise<void>`
- `list(googleAuthId: number, tx?: object): Promise<Array<{id: number, name: string, token: string, pairingpin: string}>>` - `list(googleAuthId: number, tx?: object): Promise<Array<{id: number, name: string, token: string, pairingpin: string}>>`
@@ -182,6 +191,13 @@ The store is exposed as a `LibDashStore` instance (see `src/index.js`). Each met
- `setOn(googleAuthId: number, posterminalId: number, categoryId: number, tx?: object): Promise<{id: number, categoryIds: Array<number>}>` - `setOn(googleAuthId: number, posterminalId: number, categoryId: number, tx?: object): Promise<{id: number, categoryIds: Array<number>}>`
- `setOnAll(googleAuthId: number, posterminalId: number, tx?: object): Promise<{id: number, categoryIds: Array<number>}>` - `setOnAll(googleAuthId: number, posterminalId: number, tx?: object): Promise<{id: number, categoryIds: Array<number>}>`
- `upsert(googleAuthId: number, input: {name: string, pairingpin: string, token?: string, id?: number}, tx?: object): Promise<{id: number, name: string, token: string, pairingpin: string}>` - `upsert(googleAuthId: number, input: {name: string, pairingpin: string, token?: string, id?: number}, tx?: object): Promise<{id: number, name: string, token: string, pairingpin: string}>`
- [printer](API.printer.md)
- `create(googleAuthId: number, input: {address: string, type: string, model?: string, serial?: string, sort?: number, desc?: string}, tx?: object): Promise<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}>`
- `delete(googleAuthId: number, id: number, tx?: object): Promise<void>`
- `getById(googleAuthId: number, id: number, tx?: object): Promise<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}|undefined>`
- `list(googleAuthId: number, tx?: object): Promise<Array<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}>>`
- `order(googleAuthId: number, input: {printerIds: Array<number>}, tx?: object): Promise<{printerIds: Array<number>}>`
- `update(googleAuthId: number, id: number, input: {address?: string, type?: string, model?: string|null, serial?: string|null, sort?: number, desc?: string|null}, tx?: object): Promise<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}>`
- [google_auth](API.google_auth.md) - [google_auth](API.google_auth.md)
- `add(email: string): Promise<number>` - `add(email: string): Promise<number>`
- `getByEmail(email: string): Promise<object|undefined>` - `getByEmail(email: string): Promise<object|undefined>`

165
API.printer.md Normal file
View File

@@ -0,0 +1,165 @@
# printer
This document is auto-generated from the JSDoc comments in `src/store` by running `npm run api-doc`.
## `printer.create`
*Source: `src/store/printer/create.js`*
Creates a new printer for the user's selected company.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `input` | `object` | Printer input. |
| `input.address` | `string` | Printer address (network IP/host/path). |
| `input.type` | `string` | Printer type ("esc/pos" or "zpl"). |
| `[input.model]` | `string` | Optional printer model name. |
| `[input.serial]` | `string` | Optional printer serial number. |
| `[input.sort]` | `number` | Optional sort order (auto-increments if omitted). |
| `[input.desc]` | `string` | Optional description. |
| `[tx]` | `object` | Optional transaction to run within. |
**Returns**
`Promise<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}>`
**Throws**
`Error` — If address is missing, type is invalid, or sort is invalid.
**Example**
```js
const printer = await store.printer.create(googleAuthId, {
address: '192.168.1.200',
type: 'esc/pos',
model: 'TM-T88VI',
desc: 'Bar receipt printer',
});
```
## `printer.delete`
*Source: `src/store/printer/delete.js`*
Deletes a printer for the user's selected company.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `id` | `number` | The printer ID to delete. |
| `[tx]` | `object` | Optional transaction to run within. |
**Returns**
`Promise<void>`
**Throws**
`Error` — If printer is not found.
## `printer.getById`
*Source: `src/store/printer/getById.js`*
Retrieves a printer by its ID for the user's selected company.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `id` | `number` | The printer ID. |
| `[tx]` | `object` | Optional transaction to run within. |
**Returns**
`Promise<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}|undefined>`
**Example**
```js
const printer = await store.printer.getById(googleAuthId, 1);
// => { id: 1, company_id: 1, address: '192.168.1.100', type: 'esc/pos', ... }
```
## `printer.list`
*Source: `src/store/printer/list.js`*
Lists all printers for the user's selected company.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `[tx]` | `object` | Optional transaction to run within. |
**Returns**
`Promise<Array<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}>>`
**Example**
```js
const printers = await store.printer.list(42);
// => [{ id: 1, company_id: 1, address: '192.168.1.100', type: 'esc/pos', ... }]
```
## `printer.order`
*Source: `src/store/printer/order.js`*
Reorders the printers of the user's selected company.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `input` | `object` | The reorder input. |
| `input.printerIds` | `Array<number>` | The printer ids in their new order. |
| `[tx]` | `object` | Optional transaction to run within. |
**Returns**
`Promise<{printerIds: Array<number>}>` — The applied order.
**Throws**
`Error` — If the order is invalid.
## `printer.update`
*Source: `src/store/printer/update.js`*
Updates a printer for the user's selected company.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `id` | `number` | The printer ID to update. |
| `input` | `object` | Update payload. |
| `[input.address]` | `string` | The printer address. |
| `[input.type]` | `string` | The printer type ("esc/pos" or "zpl"). |
| `[input.model]` | `string|null` | The printer model. |
| `[input.serial]` | `string|null` | The printer serial. |
| `[input.sort]` | `number` | The sort order. |
| `[input.desc]` | `string|null` | The description. |
| `[tx]` | `object` | Optional transaction to run within. |
**Returns**
`Promise<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}>`
**Throws**
`Error` — If printer not found, address is empty, type is invalid, or sort is invalid.

28
API.stock.md Normal file
View File

@@ -0,0 +1,28 @@
# stock
This document is auto-generated from the JSDoc comments in `src/store` by running `npm run api-doc`.
## `stock.adjust`
*Source: `src/store/stock/adjust.js`*
Adjusts article stock manually by creating an implicit manifest of type "adjustment", allocating a number from the "adjustment" number scheme, and appending to the ledger.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `input` | `object` | Adjustment payload. |
| `[input.sku]` | `string` | Article SKU (if single-item adjustment). |
| `[input.warehouseId]` | `number` | Warehouse ID (can also pass warehouse_id). |
| `[input.amount]` | `number` | Signed adjustment amount (+ to add, - to remove). |
| `[input.text]` | `string` | Optional adjustment reason/memo. |
| `[input.externalNumber]` | `string` | Optional external reference. |
| `[input.date]` | `string|Date` | Optional date (defaults to now). |
| `[input.lines]` | `Array<object>` | Optional array of items to adjust in one manifest. |
| `[tx]` | `object` | Optional transaction to run within. |
**Returns**
`Promise<{manifest: {id: number, number: string, type: string, date: string, createdAt: string}, lines: Array<object>, ledger: Array<object>}>`

141
API.warehouse.md Normal file
View File

@@ -0,0 +1,141 @@
# warehouse
This document is auto-generated from the JSDoc comments in `src/store` by running `npm run api-doc`.
## `warehouse.create`
*Source: `src/store/warehouse/create.js`*
Creates a new warehouse for the user's selected company.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `input` | `object` | Warehouse input. |
| `input.name` | `string` | The warehouse name. |
| `[tx]` | `object` | Optional transaction to run within. |
**Returns**
`Promise<{id: number, name: string}>` — The created warehouse.
**Throws**
`Error` — If name is missing or already exists.
**Example**
```js
const wh = await store.warehouse.create(googleAuthId, { name: 'Hauptlager' });
// => { id: 1, name: 'Hauptlager' }
```
## `warehouse.delete`
*Source: `src/store/warehouse/delete.js`*
Deletes a warehouse for the user's selected company, unless referenced in the ledger.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `id` | `number` | The warehouse ID to delete. |
| `[tx]` | `object` | Optional transaction to run within. |
**Returns**
`Promise<void>`
**Throws**
`Error` — If warehouse not found or is in use in the ledger.
**Example**
```js
await store.warehouse.delete(googleAuthId, 1);
```
## `warehouse.getById`
*Source: `src/store/warehouse/getById.js`*
Retrieves a warehouse by its ID for the user's selected company.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `id` | `number` | The warehouse ID. |
| `[tx]` | `object` | Optional transaction to run within. |
**Returns**
`Promise<{id: number, name: string}|undefined>` — The warehouse or undefined.
**Example**
```js
const wh = await store.warehouse.getById(googleAuthId, 1);
// => { id: 1, name: 'Hauptlager' }
```
## `warehouse.list`
*Source: `src/store/warehouse/list.js`*
Lists all warehouses for the user's selected company.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `[tx]` | `object` | Optional transaction to run within. |
**Returns**
`Promise<Array<{id: number, name: string}>>` — List of warehouses.
**Example**
```js
const warehouses = await store.warehouse.list(googleAuthId);
// => [{ id: 1, name: 'Hauptlager' }]
```
## `warehouse.update`
*Source: `src/store/warehouse/update.js`*
Updates a warehouse name for the user's selected company.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| `googleAuthId` | `number` | The id of the Google auth user. |
| `id` | `number` | The warehouse ID to update. |
| `input` | `object` | Update payload. |
| `input.name` | `string` | The new warehouse name. |
| `[tx]` | `object` | Optional transaction to run within. |
**Returns**
`Promise<{id: number, name: string}>` — The updated warehouse.
**Throws**
`Error` — If warehouse not found, name is missing, or name already exists.
**Example**
```js
const updated = await store.warehouse.update(googleAuthId, 1, { name: 'Zentrallager' });
// => { id: 1, name: 'Zentrallager' }
```

View File

@@ -29,7 +29,10 @@ const MODULE_ORDER = [
'order', 'order',
'manifestattachment', 'manifestattachment',
'ledger', 'ledger',
'warehouse',
'stock',
'posterminal', 'posterminal',
'printer',
'google_auth', 'google_auth',
'pic', 'pic',
'numbers', 'numbers',
@@ -335,7 +338,7 @@ const SCHEMA_TABLES = [
['file', 'id PK, hash:s(64), mimetype:s(255), name:s(255), size:bi, created:dt, modified:dt, content:bin, thumbavif?:bin, thumbx?:i, thumby?:i, meta?:txt'], ['file', 'id PK, hash:s(64), mimetype:s(255), name:s(255), size:bi, created:dt, modified:dt, content:bin, thumbavif?:bin, thumbx?:i, thumby?:i, meta?:txt'],
['google_auth', 'id PK, email:s(320) UQ, picture?:s(2048), picturebinary?:bin, sub?:s(255) UQ, created_at:dt, selected_company?->company'], ['google_auth', 'id PK, email:s(320) UQ, picture?:s(2048), picturebinary?:bin, sub?:s(255) UQ, created_at:dt, selected_company?->company'],
['language', 'id PK, iso639:s(10) UQ'], ['language', 'id PK, iso639:s(10) UQ'],
['ledger', 'id PK, manifestarticle_id->manifestarticle, transaction_type:s(100), amount:f, transaction_text:txt, hash_version:i, prev_hash?:s(128) [append-only]'], ['ledger', 'id PK, manifestarticle_id->manifestarticle, warehouse_id?->warehouse, transaction_type:s(100), amount:f, transaction_text:txt, hash_version:i, prev_hash?:s(128) [append-only]'],
['manifest', 'id PK, company_id->company, number:s(100), type:s(100), entity_id?->entity, external_number?:s(100), date:dt, created_at:dt'], ['manifest', 'id PK, company_id->company, number:s(100), type:s(100), entity_id?->entity, external_number?:s(100), date:dt, created_at:dt'],
['manifestarticle', 'id PK, manifest_id->manifest, sku?:s(100), name?:s(255), pu:f=1, amount:f, net:f, comment?:txt, rebate:f=0, taxrate:f=0'], ['manifestarticle', 'id PK, manifest_id->manifest, sku?:s(100), name?:s(255), pu:f=1, amount:f, net:f, comment?:txt, rebate:f=0, taxrate:f=0'],
['manifestattachment', 'id PK, manifest_id->manifest, file_id->file, sort:i=0, UQ(manifest_id, sort)'], ['manifestattachment', 'id PK, manifest_id->manifest, file_id->file, sort:i=0, UQ(manifest_id, sort)'],
@@ -351,6 +354,7 @@ const SCHEMA_TABLES = [
['tax', 'id PK, rate:d(18,4) UQ'], ['tax', 'id PK, rate:d(18,4) UQ'],
['unit', 'id PK, company_id->company, si:s(50), basesi:s(50), basesifactor:f, UQ(company_id, si)'], ['unit', 'id PK, company_id->company, si:s(50), basesi:s(50), basesifactor:f, UQ(company_id, si)'],
['unittext', 'id PK, unit_id->unit, language_id->language, symbol:s(50), name:s(255), UQ(unit_id, language_id)'], ['unittext', 'id PK, unit_id->unit, language_id->language, symbol:s(50), name:s(255), UQ(unit_id, language_id)'],
['warehouse', 'id PK, company_id->company, name:s(255), UQ(company_id, name)'],
]; ];
// Write the index API.md linking to each section file. // Write the index API.md linking to each section file.

View File

@@ -366,7 +366,7 @@ const CLUSTERS = [
{ {
id: 'manifests', id: 'manifests',
label: 'Documents', label: 'Documents',
tables: ['manifest', 'manifestarticle', 'manifestattachment', 'ledger'], tables: ['manifest', 'manifestarticle', 'manifestattachment', 'ledger', 'warehouse'],
}, },
{ {
id: 'commerce', id: 'commerce',
@@ -374,7 +374,7 @@ const CLUSTERS = [
tables: ['tax', 'price'], tables: ['tax', 'price'],
}, },
{ id: 'units', label: 'Units', tables: ['unit'] }, { id: 'units', label: 'Units', tables: ['unit'] },
{ id: 'pos', label: 'POS', tables: ['posterminal', 'posterminalcategory'] }, { id: 'pos', label: 'POS', tables: ['posterminal', 'posterminalcategory', 'printer'] },
]; ];
const COLORS = { const COLORS = {

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 211 KiB

After

Width:  |  Height:  |  Size: 222 KiB

View File

@@ -112,6 +112,7 @@ async function run() {
JSON.stringify({ JSON.stringify({
id: 1, id: 1,
manifestarticle_id: manifestarticleId1, manifestarticle_id: manifestarticleId1,
warehouse_id: null,
transaction_type: 'GOODS_RECEIPT', transaction_type: 'GOODS_RECEIPT',
amount: 5, amount: 5,
transaction_text: 'Initial delivery movement', transaction_text: 'Initial delivery movement',
@@ -228,6 +229,68 @@ async function run() {
'History should include second line goods receipt with details', 'History should include second line goods receipt with details',
); );
// 9. Test warehouse CRUD and linking with ledger
console.log('8. Testing warehouse CRUD and ledger association...');
const wh1 = await store.warehouse.create(googleAuthId, { name: 'Hauptlager' });
assert.equal(wh1.name, 'Hauptlager');
assert(wh1.id > 0);
const wh2 = await store.warehouse.create(googleAuthId, { name: 'Filiale Nord' });
assert.equal(wh2.name, 'Filiale Nord');
const whList = await store.warehouse.list(googleAuthId);
assert.equal(whList.length, 2);
assert(whList.some((w) => w.name === 'Hauptlager'));
assert(whList.some((w) => w.name === 'Filiale Nord'));
const whGet = await store.warehouse.getById(googleAuthId, wh1.id);
assert.equal(whGet.name, 'Hauptlager');
const whUpdated = await store.warehouse.update(googleAuthId, wh2.id, { name: 'Filiale Süd' });
assert.equal(whUpdated.name, 'Filiale Süd');
// Add ledger row with warehouse
const rowWithWh = await store.ledger.add(googleAuthId, {
manifestarticle_id: manifestarticleId1,
warehouse_id: wh1.id,
transaction_type: 'DELIVERY',
amount: 25,
transaction_text: 'Delivered directly to Hauptlager',
});
assert.equal(rowWithWh.warehouse_id, wh1.id);
assert.equal(rowWithWh.amount, 25);
// Filter by warehouse in listBySku and listByManifestarticleId
const whRowsBySku = await store.ledger.listBySku(googleAuthId, 'SKU-ABC', { warehouse_id: wh1.id });
assert.equal(whRowsBySku.length, 1);
assert.equal(whRowsBySku[0].id, rowWithWh.id);
assert.equal(whRowsBySku[0].warehouse_id, wh1.id);
const whRowsByLine = await store.ledger.listByManifestarticleId(googleAuthId, manifestarticleId1, { warehouse_id: wh1.id });
assert.equal(whRowsByLine.length, 1);
assert.equal(whRowsByLine[0].id, rowWithWh.id);
// Verify warehouse is recorded in article history
const historyWithWh = await store.article.getHistoryBySku(googleAuthId, article.sku);
assert(
historyWithWh.some((h) => h.text.includes('Lager: "Hauptlager"') && h.text.includes('Lieferant: "Supplier X"')),
'History should include warehouse name (Lager: "Hauptlager")',
);
// Trying to delete wh1 (used in ledger) must fail
await assert.rejects(
async () => store.warehouse.delete(googleAuthId, wh1.id),
/Warehouse in use in ledger/,
'Should reject deleting warehouse referenced in ledger',
);
// Deleting wh2 (not used in ledger) must succeed
await store.warehouse.delete(googleAuthId, wh2.id);
const whListAfterDelete = await store.warehouse.list(googleAuthId);
assert.equal(whListAfterDelete.length, 1);
assert.equal(whListAfterDelete[0].id, wh1.id);
console.log('✓ Warehouse CRUD and ledger enforcement passed');
console.log('✓ All ledger tests passed successfully!'); console.log('✓ All ledger tests passed successfully!');
} finally { } finally {
try { try {

View File

@@ -124,6 +124,18 @@ import manifestattachmentOrder from './store/manifestattachment/order.js';
import ledgerAdd from './store/ledger/add.js'; import ledgerAdd from './store/ledger/add.js';
import ledgerListByManifestarticleId from './store/ledger/listByManifestarticleId.js'; import ledgerListByManifestarticleId from './store/ledger/listByManifestarticleId.js';
import ledgerListBySku from './store/ledger/listBySku.js'; import ledgerListBySku from './store/ledger/listBySku.js';
import warehouseCreate from './store/warehouse/create.js';
import warehouseGetById from './store/warehouse/getById.js';
import warehouseList from './store/warehouse/list.js';
import warehouseUpdate from './store/warehouse/update.js';
import warehouseDelete from './store/warehouse/delete.js';
import printerCreate from './store/printer/create.js';
import printerGetById from './store/printer/getById.js';
import printerList from './store/printer/list.js';
import printerUpdate from './store/printer/update.js';
import printerDelete from './store/printer/delete.js';
import printerOrder from './store/printer/order.js';
import stockAdjust from './store/stock/adjust.js';
export default class LibDashStore { export default class LibDashStore {
/** /**
@@ -340,6 +352,28 @@ export default class LibDashStore {
listBySku: ledgerListBySku(provider), listBySku: ledgerListBySku(provider),
}; };
this.warehouse = {
create: warehouseCreate(provider),
getById: warehouseGetById(provider),
list: warehouseList(provider),
update: warehouseUpdate(provider),
delete: warehouseDelete(provider),
};
this.printer = {
create: printerCreate(provider),
getById: printerGetById(provider),
list: printerList(provider),
update: printerUpdate(provider),
delete: printerDelete(provider),
order: printerOrder(provider),
};
this.stock = {
adjust: stockAdjust(provider),
};
this.adjustment = this.stock;
this.purge = storePurge(provider); this.purge = storePurge(provider);
this.initialize = storeInitialize(provider); this.initialize = storeInitialize(provider);

View File

@@ -159,6 +159,18 @@ export class MssqlProvider {
await pool.request().query(script); await pool.request().query(script);
} }
} }
try {
await pool.request().query(`
IF OBJECT_ID(N'dbo.ledger', N'U') IS NOT NULL AND COL_LENGTH('ledger', 'warehouse_id') IS NULL
BEGIN
ALTER TABLE ledger ADD warehouse_id INT NULL;
ALTER TABLE ledger ADD CONSTRAINT FK_ledger_warehouse FOREIGN KEY (warehouse_id) REFERENCES warehouse(id) ON DELETE NO ACTION;
END
`);
} catch {
// ignore
}
} }
async purge() { async purge() {

View File

@@ -7,8 +7,10 @@ export const TABLES = [
'companysetting', 'companysetting',
'posterminalcategory', 'posterminalcategory',
'posterminal', 'posterminal',
'printer',
'numbers', 'numbers',
'ledger', 'ledger',
'warehouse',
'articlesupplier', 'articlesupplier',
'manifestarticle', 'manifestarticle',
'manifest', 'manifest',

View File

@@ -446,7 +446,29 @@ SELECT
WHERE asup.article_id = a.id WHERE asup.article_id = a.id
ORDER BY asup.sort ASC, asup.id ASC ORDER BY asup.sort ASC, asup.id ASC
FOR JSON PATH FOR JSON PATH
) AS suppliersJson ) AS suppliersJson,
(
SELECT
w.id,
w.name,
COALESCE(stock_calc.stock, 0) AS stock
FROM warehouse w
LEFT JOIN (
SELECT l.warehouse_id, SUM(l.amount) AS stock
FROM ledger l
INNER JOIN manifestarticle ma ON ma.id = l.manifestarticle_id
INNER JOIN manifest m ON m.id = ma.manifest_id
WHERE m.company_id = a.company_id
AND (
ma.sku = a.sku
OR ma.sku IN (SELECT asup.sku FROM articlesupplier asup WHERE asup.article_id = a.id)
)
GROUP BY l.warehouse_id
) stock_calc ON stock_calc.warehouse_id = w.id
WHERE w.company_id = a.company_id
ORDER BY w.name ASC
FOR JSON PATH
) AS warehousesJson
FROM article a FROM article a
LEFT JOIN articletext at LEFT JOIN articletext at
ON at.article_id = a.id AND at.language_id = auth.languageId ON at.article_id = a.id AND at.language_id = auth.languageId

View File

@@ -17,6 +17,12 @@ LEFT JOIN entity e ON e.id = m.entity_id
WHERE ma.id = @manifestarticleId AND m.company_id = @companyId; WHERE ma.id = @manifestarticleId AND m.company_id = @companyId;
`; `;
export const CHECK_WAREHOUSE_ACCESS = `
SELECT id, name
FROM warehouse
WHERE id = @warehouseId AND company_id = @companyId;
`;
export const FIND_ARTICLES_FOR_HISTORY = ` export const FIND_ARTICLES_FOR_HISTORY = `
SELECT DISTINCT asup.article_id AS articleId SELECT DISTINCT asup.article_id AS articleId
FROM articlesupplier asup FROM articlesupplier asup
@@ -35,6 +41,7 @@ export const GET_LATEST_ROW = `
SELECT TOP 1 SELECT TOP 1
id, id,
manifestarticle_id, manifestarticle_id,
warehouse_id,
transaction_type, transaction_type,
amount, amount,
transaction_text, transaction_text,
@@ -48,6 +55,7 @@ ORDER BY id DESC;
export const INSERT_ROW = ` export const INSERT_ROW = `
INSERT INTO ledger ( INSERT INTO ledger (
manifestarticle_id, manifestarticle_id,
warehouse_id,
transaction_type, transaction_type,
amount, amount,
transaction_text, transaction_text,
@@ -57,6 +65,7 @@ INSERT INTO ledger (
OUTPUT OUTPUT
INSERTED.id, INSERTED.id,
INSERTED.manifestarticle_id, INSERTED.manifestarticle_id,
INSERTED.warehouse_id,
INSERTED.transaction_type, INSERTED.transaction_type,
INSERTED.amount, INSERTED.amount,
INSERTED.transaction_text, INSERTED.transaction_text,
@@ -65,6 +74,7 @@ OUTPUT
INSERTED.created_at INSERTED.created_at
VALUES ( VALUES (
@manifestarticleId, @manifestarticleId,
@warehouseId,
@transactionType, @transactionType,
@amount, @amount,
@transactionText, @transactionText,
@@ -77,6 +87,7 @@ export const LIST_BY_MANIFESTARTICLE = `
SELECT SELECT
l.id, l.id,
l.manifestarticle_id, l.manifestarticle_id,
l.warehouse_id,
ma.sku, ma.sku,
l.transaction_type, l.transaction_type,
l.amount, l.amount,
@@ -90,6 +101,7 @@ INNER JOIN manifest m ON ma.manifest_id = m.id
WHERE l.manifestarticle_id = @manifestarticleId WHERE l.manifestarticle_id = @manifestarticleId
AND m.company_id = @companyId AND m.company_id = @companyId
AND (@transactionType IS NULL OR l.transaction_type = @transactionType) AND (@transactionType IS NULL OR l.transaction_type = @transactionType)
AND (@warehouseId IS NULL OR l.warehouse_id = @warehouseId)
ORDER BY l.id ASC; ORDER BY l.id ASC;
`; `;
@@ -97,6 +109,7 @@ export const LIST_BY_SKU = `
SELECT SELECT
l.id, l.id,
l.manifestarticle_id, l.manifestarticle_id,
l.warehouse_id,
ma.sku, ma.sku,
l.transaction_type, l.transaction_type,
l.amount, l.amount,
@@ -110,5 +123,6 @@ INNER JOIN manifest m ON ma.manifest_id = m.id
WHERE ma.sku = @sku WHERE ma.sku = @sku
AND m.company_id = @companyId AND m.company_id = @companyId
AND (@transactionType IS NULL OR l.transaction_type = @transactionType) AND (@transactionType IS NULL OR l.transaction_type = @transactionType)
AND (@warehouseId IS NULL OR l.warehouse_id = @warehouseId)
ORDER BY l.id ASC; ORDER BY l.id ASC;
`; `;

View File

@@ -0,0 +1,99 @@
export const PRINTER_COLUMNS = `
id,
company_id,
address,
type,
model,
serial,
sort,
[desc]
`;
export const LIST_BY_COMPANY = `
SELECT
${PRINTER_COLUMNS}
FROM printer
WHERE company_id = @companyId
ORDER BY sort ASC, id ASC
`;
export const GET_BY_COMPANY_AND_ID = `
SELECT
${PRINTER_COLUMNS}
FROM printer
WHERE id = @id AND company_id = @companyId
`;
export const GET_NEXT_SORT = `
SELECT ISNULL(MAX(sort), -1) + 1 AS sort
FROM printer
WHERE company_id = @companyId
`;
export const LIST_IDS_BY_COMPANY = `
SELECT id
FROM printer
WHERE company_id = @companyId
`;
export const CREATE = `
INSERT INTO printer (
company_id,
address,
type,
model,
serial,
sort,
[desc]
)
OUTPUT
INSERTED.id,
INSERTED.company_id,
INSERTED.address,
INSERTED.type,
INSERTED.model,
INSERTED.serial,
INSERTED.sort,
INSERTED.[desc]
VALUES (
@companyId,
@address,
@type,
@model,
@serial,
@sort,
@desc
)
`;
export const UPDATE = `
UPDATE printer
SET
address = @address,
type = @type,
model = @model,
serial = @serial,
sort = @sort,
[desc] = @desc
OUTPUT
INSERTED.id,
INSERTED.company_id,
INSERTED.address,
INSERTED.type,
INSERTED.model,
INSERTED.serial,
INSERTED.sort,
INSERTED.[desc]
WHERE id = @id AND company_id = @companyId
`;
export const UPDATE_SORT = `
UPDATE printer
SET sort = @sort
WHERE id = @id AND company_id = @companyId
`;
export const DELETE_BY_COMPANY_AND_ID = `
DELETE FROM printer
WHERE id = @id AND company_id = @companyId
`;

View File

@@ -0,0 +1,48 @@
export const LIST_BY_COMPANY = `
SELECT
id,
company_id,
name
FROM warehouse
WHERE company_id = @companyId
ORDER BY name ASC;
`;
export const GET_BY_COMPANY_AND_ID = `
SELECT
id,
company_id,
name
FROM warehouse
WHERE id = @id AND company_id = @companyId;
`;
export const GET_BY_COMPANY_AND_NAME = `
SELECT
id,
company_id,
name
FROM warehouse
WHERE company_id = @companyId AND name = @name;
`;
export const CREATE = `
INSERT INTO warehouse (company_id, name)
OUTPUT INSERTED.id, INSERTED.company_id, INSERTED.name
VALUES (@companyId, @name);
`;
export const UPDATE_BY_ID = `
UPDATE warehouse
SET name = @name
WHERE id = @id AND company_id = @companyId;
`;
export const DELETE_BY_COMPANY_AND_ID = `
DELETE FROM warehouse
WHERE id = @id AND company_id = @companyId;
`;
export const CHECK_LEDGER_USAGE = `
SELECT TOP 1 id FROM ledger WHERE warehouse_id = @warehouseId;
`;

View File

@@ -592,19 +592,34 @@ END
`; `;
export const INIT_WAREHOUSE = `
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'warehouse')
BEGIN
CREATE TABLE warehouse (
id INT IDENTITY(1,1) PRIMARY KEY,
company_id INT NOT NULL,
name NVARCHAR(255) NOT NULL,
CONSTRAINT FK_warehouse_company FOREIGN KEY (company_id) REFERENCES company(id) ON DELETE CASCADE,
CONSTRAINT UQ_warehouse_company_name UNIQUE (company_id, name)
);
END
`;
export const INIT_LEDGER = ` export const INIT_LEDGER = `
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'ledger') IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'ledger')
BEGIN BEGIN
CREATE TABLE ledger ( CREATE TABLE ledger (
id INT IDENTITY(1,1) PRIMARY KEY, id INT IDENTITY(1,1) PRIMARY KEY,
manifestarticle_id INT NOT NULL, manifestarticle_id INT NOT NULL,
warehouse_id INT NULL,
transaction_type NVARCHAR(100) NOT NULL, transaction_type NVARCHAR(100) NOT NULL,
amount FLOAT NOT NULL, amount FLOAT NOT NULL,
transaction_text NVARCHAR(MAX) NOT NULL, transaction_text NVARCHAR(MAX) NOT NULL,
hash_version INT NOT NULL, hash_version INT NOT NULL,
prev_hash NVARCHAR(128) NULL, prev_hash NVARCHAR(128) NULL,
created_at DATETIME2 NOT NULL CONSTRAINT DF_ledger_created_at DEFAULT SYSUTCDATETIME(), created_at DATETIME2 NOT NULL CONSTRAINT DF_ledger_created_at DEFAULT SYSUTCDATETIME(),
CONSTRAINT FK_ledger_manifestarticle FOREIGN KEY (manifestarticle_id) REFERENCES manifestarticle(id) ON DELETE NO ACTION CONSTRAINT FK_ledger_manifestarticle FOREIGN KEY (manifestarticle_id) REFERENCES manifestarticle(id) ON DELETE NO ACTION,
CONSTRAINT FK_ledger_warehouse FOREIGN KEY (warehouse_id) REFERENCES warehouse(id) ON DELETE NO ACTION
) WITH (LEDGER = ON (APPEND_ONLY = ON)); ) WITH (LEDGER = ON (APPEND_ONLY = ON));
END END
`; `;
@@ -772,6 +787,25 @@ BEGIN
END END
`; `;
export const INIT_PRINTER = `
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'printer')
BEGIN
CREATE TABLE printer (
id INT IDENTITY(1,1) PRIMARY KEY,
company_id INT NOT NULL,
address NVARCHAR(255) NOT NULL,
type NVARCHAR(50) NOT NULL,
model NVARCHAR(255) NULL,
serial NVARCHAR(255) NULL,
sort INT NOT NULL CONSTRAINT DF_printer_sort DEFAULT 0,
[desc] NVARCHAR(MAX) NULL,
CONSTRAINT FK_printer_company FOREIGN KEY (company_id) REFERENCES company(id) ON DELETE CASCADE,
CONSTRAINT CK_printer_type CHECK (type IN ('esc/pos', 'zpl'))
);
END
`;
export const INIT_FILE = ` export const INIT_FILE = `
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'file') IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'file')
BEGIN BEGIN
@@ -862,6 +896,7 @@ export const SCHEMA_SCRIPTS = [
INIT_ARTICLE_SUPPLIER, INIT_ARTICLE_SUPPLIER,
INIT_MANIFEST, INIT_MANIFEST,
INIT_MANIFESTARTICLE, INIT_MANIFESTARTICLE,
INIT_WAREHOUSE,
INIT_LEDGER, INIT_LEDGER,
INIT_NUMBERS, INIT_NUMBERS,
INIT_GET_NEXT_NUMBER_WITH_PREFIX_AND_PADDING, INIT_GET_NEXT_NUMBER_WITH_PREFIX_AND_PADDING,
@@ -873,6 +908,7 @@ export const SCHEMA_SCRIPTS = [
INIT_COMPANYSETTING, INIT_COMPANYSETTING,
INIT_POSTERMINAL, INIT_POSTERMINAL,
INIT_POSTERMINALCATEGORY, INIT_POSTERMINALCATEGORY,
INIT_PRINTER,
INIT_FILE, INIT_FILE,
INIT_MANIFESTATTACHMENT, INIT_MANIFESTATTACHMENT,
INIT_MANIFESTATTACHMENT_TRIGGER, INIT_MANIFESTATTACHMENT_TRIGGER,

View File

@@ -386,7 +386,7 @@ export class BetterSqlite3Provider extends BetterSqlite3Executor {
} }
} }
// Ensure created_at exists on ledger table if created previously // Ensure created_at and warehouse_id exist on ledger table if created previously
try { try {
const ledgerCols = this.db.pragma('table_info("ledger")').map((c) => c.name); const ledgerCols = this.db.pragma('table_info("ledger")').map((c) => c.name);
if (ledgerCols.length > 0 && !ledgerCols.includes('created_at')) { if (ledgerCols.length > 0 && !ledgerCols.includes('created_at')) {
@@ -394,6 +394,11 @@ export class BetterSqlite3Provider extends BetterSqlite3Executor {
`ALTER TABLE ledger ADD COLUMN created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`, `ALTER TABLE ledger ADD COLUMN created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`,
); );
} }
if (ledgerCols.length > 0 && !ledgerCols.includes('warehouse_id')) {
this.db.exec(
`ALTER TABLE ledger ADD COLUMN warehouse_id INTEGER REFERENCES warehouse(id) ON DELETE NO ACTION`,
);
}
} catch { } catch {
// ignore // ignore
} }

View File

@@ -160,7 +160,24 @@ SELECT auth.*,
LEFT JOIN price pr ON pr.id = s.price_id LEFT JOIN price pr ON pr.id = s.price_id
LEFT JOIN tax t ON t.id = pr.tax_id LEFT JOIN tax t ON t.id = pr.tax_id
WHERE s.article_id = a.id ORDER BY s.sort, s.id WHERE s.article_id = a.id ORDER BY s.sort, s.id
))) ))),
'warehousesJson', json((SELECT COALESCE(json_group_array(json_object(
'id', w.id, 'name', w.name, 'stock', COALESCE(stock_calc.stock, 0)
)), '[]') FROM warehouse w
LEFT JOIN (
SELECT l.warehouse_id, SUM(l.amount) AS stock
FROM ledger l
INNER JOIN manifestarticle ma ON ma.id = l.manifestarticle_id
INNER JOIN manifest m ON m.id = ma.manifest_id
WHERE m.company_id = a.company_id
AND (
ma.sku = a.sku
OR ma.sku IN (SELECT asup.sku FROM articlesupplier asup WHERE asup.article_id = a.id)
)
GROUP BY l.warehouse_id
) stock_calc ON stock_calc.warehouse_id = w.id
WHERE w.company_id = a.company_id
ORDER BY w.name ASC))
) AS articleJson ) AS articleJson
FROM auth FROM auth
INNER JOIN article a ON a.id = auth.articleId INNER JOIN article a ON a.id = auth.articleId

View File

@@ -17,6 +17,12 @@ LEFT JOIN entity e ON e.id = m.entity_id
WHERE ma.id = @manifestarticleId AND m.company_id = @companyId; WHERE ma.id = @manifestarticleId AND m.company_id = @companyId;
`; `;
export const CHECK_WAREHOUSE_ACCESS = `
SELECT id, name
FROM warehouse
WHERE id = @warehouseId AND company_id = @companyId;
`;
export const FIND_ARTICLES_FOR_HISTORY = ` export const FIND_ARTICLES_FOR_HISTORY = `
SELECT DISTINCT asup.article_id AS articleId SELECT DISTINCT asup.article_id AS articleId
FROM articlesupplier asup FROM articlesupplier asup
@@ -35,6 +41,7 @@ export const GET_LATEST_ROW = `
SELECT SELECT
id, id,
manifestarticle_id, manifestarticle_id,
warehouse_id,
transaction_type, transaction_type,
amount, amount,
transaction_text, transaction_text,
@@ -49,6 +56,7 @@ LIMIT 1;
export const INSERT_ROW = ` export const INSERT_ROW = `
INSERT INTO ledger ( INSERT INTO ledger (
manifestarticle_id, manifestarticle_id,
warehouse_id,
transaction_type, transaction_type,
amount, amount,
transaction_text, transaction_text,
@@ -57,6 +65,7 @@ INSERT INTO ledger (
) )
VALUES ( VALUES (
@manifestarticleId, @manifestarticleId,
@warehouseId,
@transactionType, @transactionType,
@amount, @amount,
@transactionText, @transactionText,
@@ -66,6 +75,7 @@ VALUES (
RETURNING RETURNING
id, id,
manifestarticle_id, manifestarticle_id,
warehouse_id,
transaction_type, transaction_type,
amount, amount,
transaction_text, transaction_text,
@@ -78,6 +88,7 @@ export const LIST_BY_MANIFESTARTICLE = `
SELECT SELECT
l.id, l.id,
l.manifestarticle_id, l.manifestarticle_id,
l.warehouse_id,
ma.sku, ma.sku,
l.transaction_type, l.transaction_type,
l.amount, l.amount,
@@ -91,6 +102,7 @@ INNER JOIN manifest m ON ma.manifest_id = m.id
WHERE l.manifestarticle_id = @manifestarticleId WHERE l.manifestarticle_id = @manifestarticleId
AND m.company_id = @companyId AND m.company_id = @companyId
AND (@transactionType IS NULL OR l.transaction_type = @transactionType) AND (@transactionType IS NULL OR l.transaction_type = @transactionType)
AND (@warehouseId IS NULL OR l.warehouse_id = @warehouseId)
ORDER BY l.id ASC; ORDER BY l.id ASC;
`; `;
@@ -98,6 +110,7 @@ export const LIST_BY_SKU = `
SELECT SELECT
l.id, l.id,
l.manifestarticle_id, l.manifestarticle_id,
l.warehouse_id,
ma.sku, ma.sku,
l.transaction_type, l.transaction_type,
l.amount, l.amount,
@@ -111,5 +124,6 @@ INNER JOIN manifest m ON ma.manifest_id = m.id
WHERE ma.sku = @sku WHERE ma.sku = @sku
AND m.company_id = @companyId AND m.company_id = @companyId
AND (@transactionType IS NULL OR l.transaction_type = @transactionType) AND (@transactionType IS NULL OR l.transaction_type = @transactionType)
AND (@warehouseId IS NULL OR l.warehouse_id = @warehouseId)
ORDER BY l.id ASC; ORDER BY l.id ASC;
`; `;

View File

@@ -0,0 +1,15 @@
import * as source from '../../mssql/queries/printer.js';
import { translateQueries } from './translate.js';
const queries = translateQueries(source, 'printer');
export const {
CREATE,
DELETE_BY_COMPANY_AND_ID,
GET_BY_COMPANY_AND_ID,
GET_NEXT_SORT,
LIST_BY_COMPANY,
LIST_IDS_BY_COMPANY,
PRINTER_COLUMNS,
UPDATE,
UPDATE_SORT,
} = queries;

View File

@@ -0,0 +1,48 @@
export const LIST_BY_COMPANY = `
SELECT
id,
company_id,
name
FROM warehouse
WHERE company_id = @companyId
ORDER BY name ASC;
`;
export const GET_BY_COMPANY_AND_ID = `
SELECT
id,
company_id,
name
FROM warehouse
WHERE id = @id AND company_id = @companyId;
`;
export const GET_BY_COMPANY_AND_NAME = `
SELECT
id,
company_id,
name
FROM warehouse
WHERE company_id = @companyId AND name = @name;
`;
export const CREATE = `
INSERT INTO warehouse (company_id, name)
VALUES (@companyId, @name)
RETURNING id, company_id, name;
`;
export const UPDATE_BY_ID = `
UPDATE warehouse
SET name = @name
WHERE id = @id AND company_id = @companyId;
`;
export const DELETE_BY_COMPANY_AND_ID = `
DELETE FROM warehouse
WHERE id = @id AND company_id = @companyId;
`;
export const CHECK_LEDGER_USAGE = `
SELECT id FROM ledger WHERE warehouse_id = @warehouseId LIMIT 1;
`;

View File

@@ -426,18 +426,30 @@ CREATE TABLE IF NOT EXISTS manifestarticle (
); );
`; `;
export const INIT_WAREHOUSE = `
CREATE TABLE IF NOT EXISTS warehouse (
id INTEGER PRIMARY KEY,
company_id INTEGER NOT NULL,
name TEXT NOT NULL COLLATE NOCASE,
UNIQUE (company_id, name),
FOREIGN KEY (company_id) REFERENCES company(id) ON DELETE CASCADE
);
`;
/* SQLite has no SQL Server ledger tables; constraints preserve the base shape. */ /* SQLite has no SQL Server ledger tables; constraints preserve the base shape. */
export const INIT_LEDGER = ` export const INIT_LEDGER = `
CREATE TABLE IF NOT EXISTS ledger ( CREATE TABLE IF NOT EXISTS ledger (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
manifestarticle_id INTEGER NOT NULL, manifestarticle_id INTEGER NOT NULL,
warehouse_id INTEGER,
transaction_type TEXT NOT NULL, transaction_type TEXT NOT NULL,
amount REAL NOT NULL, amount REAL NOT NULL,
transaction_text TEXT NOT NULL, transaction_text TEXT NOT NULL,
hash_version INTEGER NOT NULL, hash_version INTEGER NOT NULL,
prev_hash TEXT, prev_hash TEXT,
created_at TEXT NOT NULL DEFAULT (${UTC_NOW}), created_at TEXT NOT NULL DEFAULT (${UTC_NOW}),
FOREIGN KEY (manifestarticle_id) REFERENCES manifestarticle(id) ON DELETE NO ACTION FOREIGN KEY (manifestarticle_id) REFERENCES manifestarticle(id) ON DELETE NO ACTION,
FOREIGN KEY (warehouse_id) REFERENCES warehouse(id) ON DELETE NO ACTION
); );
`; `;
@@ -536,6 +548,21 @@ CREATE TABLE IF NOT EXISTS posterminalcategory (
); );
`; `;
export const INIT_PRINTER = `
CREATE TABLE IF NOT EXISTS printer (
id INTEGER PRIMARY KEY,
company_id INTEGER NOT NULL,
address TEXT NOT NULL,
type TEXT NOT NULL CHECK (type IN ('esc/pos', 'zpl')),
model TEXT,
serial TEXT,
sort INTEGER NOT NULL DEFAULT 0,
"desc" TEXT,
FOREIGN KEY (company_id) REFERENCES company(id) ON DELETE CASCADE
);
`;
export const INIT_FILE = ` export const INIT_FILE = `
CREATE TABLE IF NOT EXISTS "file" ( CREATE TABLE IF NOT EXISTS "file" (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
@@ -608,6 +635,7 @@ export const SCHEMA_SCRIPTS = [
INIT_ARTICLE_SUPPLIER, INIT_ARTICLE_SUPPLIER,
INIT_MANIFEST, INIT_MANIFEST,
INIT_MANIFESTARTICLE, INIT_MANIFESTARTICLE,
INIT_WAREHOUSE,
INIT_LEDGER, INIT_LEDGER,
INIT_NUMBERS, INIT_NUMBERS,
INIT_COMPANYUSER, INIT_COMPANYUSER,
@@ -617,6 +645,7 @@ export const SCHEMA_SCRIPTS = [
INIT_COMPANYSETTING, INIT_COMPANYSETTING,
INIT_POSTERMINAL, INIT_POSTERMINAL,
INIT_POSTERMINALCATEGORY, INIT_POSTERMINALCATEGORY,
INIT_PRINTER,
INIT_FILE, INIT_FILE,
INIT_MANIFESTATTACHMENT, INIT_MANIFESTATTACHMENT,
INIT_MANIFESTATTACHMENT_TRIGGER, INIT_MANIFESTATTACHMENT_TRIGGER,

View File

@@ -87,6 +87,11 @@ export default function getBySku(provider) {
priceId: s.priceId ?? null, priceId: s.priceId ?? null,
price: s.priceId != null && s.price?.net != null ? s.price : null, price: s.priceId != null && s.price?.net != null ? s.price : null,
})), })),
warehouses: parseJsonArray(a.warehousesJson).map((w) => ({
id: w.id,
name: w.name,
stock: Number(w.stock ?? 0),
})),
optionsCount: a.optionsCount, optionsCount: a.optionsCount,
articleListCount: a.articleListCount, articleListCount: a.articleListCount,
childCount: a.childCount, childCount: a.childCount,

View File

@@ -10,6 +10,7 @@ export function shape(row) {
return { return {
id: row.id, id: row.id,
manifestarticle_id: row.manifestarticle_id, manifestarticle_id: row.manifestarticle_id,
warehouse_id: row.warehouse_id ?? null,
transaction_type: row.transaction_type, transaction_type: row.transaction_type,
amount: row.amount, amount: row.amount,
transaction_text: row.transaction_text, transaction_text: row.transaction_text,
@@ -36,6 +37,7 @@ export function computePrevHash(row) {
const payload = JSON.stringify({ const payload = JSON.stringify({
id: row.id, id: row.id,
manifestarticle_id: row.manifestarticle_id, manifestarticle_id: row.manifestarticle_id,
warehouse_id: row.warehouse_id ?? null,
transaction_type: row.transaction_type, transaction_type: row.transaction_type,
amount: row.amount, amount: row.amount,
transaction_text: row.transaction_text, transaction_text: row.transaction_text,
@@ -52,17 +54,19 @@ export function computePrevHash(row) {
* @param {number} googleAuthId - The id of the Google auth user. * @param {number} googleAuthId - The id of the Google auth user.
* @param {object} input - Ledger entry payload. * @param {object} input - Ledger entry payload.
* @param {number} input.manifestarticle_id - ID of the referenced manifest line (can also pass manifestarticleId). * @param {number} input.manifestarticle_id - ID of the referenced manifest line (can also pass manifestarticleId).
* @param {number|null} [input.warehouse_id] - Optional warehouse ID (can also pass warehouseId).
* @param {string} input.transaction_type - Transaction type (can also pass transactionType). * @param {string} input.transaction_type - Transaction type (can also pass transactionType).
* @param {number} input.amount - Movement amount. * @param {number} input.amount - Movement amount.
* @param {string} input.transaction_text - Transaction memo/details (can also pass transactionText). * @param {string} input.transaction_text - Transaction memo/details (can also pass transactionText).
* @param {object} [tx] - Optional transaction to run within. * @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, manifestarticle_id: number, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>} The created ledger row. * @returns {Promise<{id: number, manifestarticle_id: number, warehouse_id: number|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>} The created ledger row.
* @throws {Error} If user not authorized, company not selected, manifest article not found, or input invalid. * @throws {Error} If user not authorized, company not selected, manifest article not found, or input invalid.
* *
* @example * @example
* const entry = await store.ledger.add(googleAuthId, { * const entry = await store.ledger.add(googleAuthId, {
* manifestarticle_id: 1, * manifestarticle_id: 1,
* transaction_type: 'PAYMENT', * warehouse_id: 1,
* transaction_type: 'DELIVERY',
* amount: 100.5, * amount: 100.5,
* transaction_text: 'Invoice paid', * transaction_text: 'Invoice paid',
* }); * });
@@ -75,6 +79,8 @@ export default function add(provider) {
return async (googleAuthId, input = {}, tx) => { return async (googleAuthId, input = {}, tx) => {
const rawManifestarticleId = const rawManifestarticleId =
input.manifestarticle_id ?? input.manifestarticleId; input.manifestarticle_id ?? input.manifestarticleId;
const rawWarehouseId =
input.warehouse_id ?? input.warehouseId;
const rawTransactionType = const rawTransactionType =
input.transaction_type ?? input.transactionType; input.transaction_type ?? input.transactionType;
const rawAmount = input.amount; const rawAmount = input.amount;
@@ -86,6 +92,14 @@ export default function add(provider) {
throw new Error('Invalid ledger entry'); throw new Error('Invalid ledger entry');
} }
let warehouseId = null;
if (rawWarehouseId !== undefined && rawWarehouseId !== null) {
warehouseId = Number(rawWarehouseId);
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
throw new Error('Invalid ledger entry');
}
}
const transactionType = const transactionType =
typeof rawTransactionType === 'string' typeof rawTransactionType === 'string'
? rawTransactionType.trim() ? rawTransactionType.trim()
@@ -117,12 +131,25 @@ export default function add(provider) {
throw new Error('Manifest article not found'); throw new Error('Manifest article not found');
} }
let warehouseName = null;
if (warehouseId != null) {
const whCheck = await runner.query(queries.CHECK_WAREHOUSE_ACCESS, {
warehouseId,
companyId,
});
if (!whCheck.rows[0]) {
throw new Error('Warehouse not found');
}
warehouseName = whCheck.rows[0].name;
}
const latest = await runner.query(queries.GET_LATEST_ROW); const latest = await runner.query(queries.GET_LATEST_ROW);
const prevRow = latest.rows[0]; const prevRow = latest.rows[0];
const prevHash = computePrevHash(prevRow); const prevHash = computePrevHash(prevRow);
const inserted = await runner.query(queries.INSERT_ROW, { const inserted = await runner.query(queries.INSERT_ROW, {
manifestarticleId, manifestarticleId,
warehouseId,
transactionType, transactionType,
amount, amount,
transactionText, transactionText,
@@ -157,6 +184,9 @@ export default function add(provider) {
if (manifestArticle.supplierName) { if (manifestArticle.supplierName) {
details.push(`Lieferant: "${manifestArticle.supplierName}"`); details.push(`Lieferant: "${manifestArticle.supplierName}"`);
} }
if (warehouseName) {
details.push(`Lager: "${warehouseName}"`);
}
if (manifestArticle.net != null && Number.isFinite(Number(manifestArticle.net))) { if (manifestArticle.net != null && Number.isFinite(Number(manifestArticle.net))) {
const net = Number(manifestArticle.net); const net = Number(manifestArticle.net);
const rebate = Number(manifestArticle.rebate ?? 0); const rebate = Number(manifestArticle.rebate ?? 0);
@@ -174,6 +204,8 @@ export default function add(provider) {
transactionText?.trim() || transactionText?.trim() ||
(manifestArticle.manifestNumber ? `Lieferung ${manifestArticle.manifestNumber}` : 'Lieferung'); (manifestArticle.manifestNumber ? `Lieferung ${manifestArticle.manifestNumber}` : 'Lieferung');
historyText = `${base}${suffix}`; historyText = `${base}${suffix}`;
} else if (warehouseName && !transactionText.includes(warehouseName)) {
historyText = `${transactionText} (Lager: "${warehouseName}")`;
} }
for (const match of articleMatches.rows) { for (const match of articleMatches.rows) {

View File

@@ -7,6 +7,7 @@ function shape(row) {
return { return {
id: row.id, id: row.id,
manifestarticle_id: row.manifestarticle_id, manifestarticle_id: row.manifestarticle_id,
warehouse_id: row.warehouse_id ?? null,
sku: row.sku ?? null, sku: row.sku ?? null,
transaction_type: row.transaction_type, transaction_type: row.transaction_type,
amount: row.amount, amount: row.amount,
@@ -21,18 +22,18 @@ function shape(row) {
} }
/** /**
* Lists ledger entries for a specific manifest article line, optionally filtered by transaction type. * Lists ledger entries for a specific manifest article line, optionally filtered by transaction type and/or warehouse.
* *
* @param {number} googleAuthId - The id of the Google auth user. * @param {number} googleAuthId - The id of the Google auth user.
* @param {number} manifestarticleId - The id of the manifest article line. * @param {number} manifestarticleId - The id of the manifest article line.
* @param {string|object} [optionsOrType] - Transaction type string or options object { transaction_type?: string, transactionType?: string }. * @param {string|object} [optionsOrType] - Transaction type string or options object { transaction_type?: string, transactionType?: string, warehouse_id?: number, warehouseId?: number }.
* @param {object} [tx] - Optional transaction to run within. * @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<Array<{id: number, manifestarticle_id: number, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>} * @returns {Promise<Array<{id: number, manifestarticle_id: number, warehouse_id: number|null, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>}
* @throws {Error} If user not authorized, company not selected, or manifest article not found. * @throws {Error} If user not authorized, company not selected, or manifest article not found.
* *
* @example * @example
* const entries = await store.ledger.listByManifestarticleId(googleAuthId, 42, 'PAYMENT'); * const entries = await store.ledger.listByManifestarticleId(googleAuthId, 42, 'DELIVERY');
* // => [{ id, manifestarticle_id, sku, transaction_type, amount, transaction_text, hash_version, prev_hash, created_at }] * // => [{ id, manifestarticle_id, warehouse_id, sku, transaction_type, amount, transaction_text, hash_version, prev_hash, created_at }]
*/ */
export default function listByManifestarticleId(provider) { export default function listByManifestarticleId(provider) {
const access = resolveSelectedCompanyAccess(provider); const access = resolveSelectedCompanyAccess(provider);
@@ -41,6 +42,7 @@ export default function listByManifestarticleId(provider) {
return async (googleAuthId, manifestarticleId, optionsOrType, tx) => { return async (googleAuthId, manifestarticleId, optionsOrType, tx) => {
let transactionType = null; let transactionType = null;
let warehouseId = null;
let explicitTx = tx; let explicitTx = tx;
if (typeof optionsOrType === 'string') { if (typeof optionsOrType === 'string') {
@@ -54,6 +56,11 @@ export default function listByManifestarticleId(provider) {
if (typeof rawType === 'string') { if (typeof rawType === 'string') {
transactionType = rawType.trim() || null; transactionType = rawType.trim() || null;
} }
const rawWarehouse =
optionsOrType.warehouse_id ?? optionsOrType.warehouseId;
if (rawWarehouse != null) {
warehouseId = Number(rawWarehouse) || null;
}
} }
} }
@@ -78,6 +85,7 @@ export default function listByManifestarticleId(provider) {
manifestarticleId: id, manifestarticleId: id,
companyId, companyId,
transactionType: transactionType || null, transactionType: transactionType || null,
warehouseId: warehouseId || null,
}); });
return res.rows.map(shape); return res.rows.map(shape);

View File

@@ -7,6 +7,7 @@ function shape(row) {
return { return {
id: row.id, id: row.id,
manifestarticle_id: row.manifestarticle_id, manifestarticle_id: row.manifestarticle_id,
warehouse_id: row.warehouse_id ?? null,
sku: row.sku ?? null, sku: row.sku ?? null,
transaction_type: row.transaction_type, transaction_type: row.transaction_type,
amount: row.amount, amount: row.amount,
@@ -21,18 +22,18 @@ function shape(row) {
} }
/** /**
* Lists ledger entries for a given article SKU, optionally filtered by transaction type. * Lists ledger entries for a given article SKU, optionally filtered by transaction type and/or warehouse.
* *
* @param {number} googleAuthId - The id of the Google auth user. * @param {number} googleAuthId - The id of the Google auth user.
* @param {string} sku - The article SKU. * @param {string} sku - The article SKU.
* @param {string|object} [optionsOrType] - Transaction type string or options object { transaction_type?: string, transactionType?: string }. * @param {string|object} [optionsOrType] - Transaction type string or options object { transaction_type?: string, transactionType?: string, warehouse_id?: number, warehouseId?: number }.
* @param {object} [tx] - Optional transaction to run within. * @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<Array<{id: number, manifestarticle_id: number, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>} * @returns {Promise<Array<{id: number, manifestarticle_id: number, warehouse_id: number|null, sku: string|null, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>>}
* @throws {Error} If user not authorized, company not selected, or SKU invalid. * @throws {Error} If user not authorized, company not selected, or SKU invalid.
* *
* @example * @example
* const entries = await store.ledger.listBySku(googleAuthId, 'SKU-001', 'DELIVERY'); * const entries = await store.ledger.listBySku(googleAuthId, 'SKU-001', 'DELIVERY');
* // => [{ id, manifestarticle_id, sku, transaction_type, amount, transaction_text, hash_version, prev_hash, created_at }] * // => [{ id, manifestarticle_id, warehouse_id, sku, transaction_type, amount, transaction_text, hash_version, prev_hash, created_at }]
*/ */
export default function listBySku(provider) { export default function listBySku(provider) {
const access = resolveSelectedCompanyAccess(provider); const access = resolveSelectedCompanyAccess(provider);
@@ -41,6 +42,7 @@ export default function listBySku(provider) {
return async (googleAuthId, sku, optionsOrType, tx) => { return async (googleAuthId, sku, optionsOrType, tx) => {
let transactionType = null; let transactionType = null;
let warehouseId = null;
let explicitTx = tx; let explicitTx = tx;
if (typeof optionsOrType === 'string') { if (typeof optionsOrType === 'string') {
@@ -54,6 +56,11 @@ export default function listBySku(provider) {
if (typeof rawType === 'string') { if (typeof rawType === 'string') {
transactionType = rawType.trim() || null; transactionType = rawType.trim() || null;
} }
const rawWarehouse =
optionsOrType.warehouse_id ?? optionsOrType.warehouseId;
if (rawWarehouse != null) {
warehouseId = Number(rawWarehouse) || null;
}
} }
} }
@@ -69,6 +76,7 @@ export default function listBySku(provider) {
sku: trimmedSku, sku: trimmedSku,
companyId, companyId,
transactionType: transactionType || null, transactionType: transactionType || null,
warehouseId: warehouseId || null,
}); });
return res.rows.map(shape); return res.rows.map(shape);

View File

@@ -9,7 +9,7 @@ import {
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js'; import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js'; import makeRunner from '../runner.js';
const DEFAULT_TYPES = ['sku', 'entity', 'delivery']; const DEFAULT_TYPES = ['sku', 'entity', 'delivery', 'adjustment'];
function shape(row) { function shape(row) {
return { return {

111
src/store/printer/create.js Normal file
View File

@@ -0,0 +1,111 @@
import {
CREATE as MSSQL_CREATE,
GET_NEXT_SORT as MSSQL_GET_NEXT_SORT,
} from '../../providers/mssql/queries/printer.js';
import {
CREATE as SQLITE_CREATE,
GET_NEXT_SORT as SQLITE_GET_NEXT_SORT,
} from '../../providers/sqlite3/queries/printer.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
const VALID_TYPES = new Set(['esc/pos', 'zpl']);
function shape(row) {
return {
id: row.id,
company_id: row.company_id ?? row.companyId,
address: row.address,
type: row.type,
model: row.model ?? null,
serial: row.serial ?? null,
sort: row.sort,
desc: row.desc ?? null,
};
}
function optionalString(value) {
if (value == null || value === '') return null;
const s = String(value).trim();
return s || null;
}
export default function create(provider) {
const access = resolveSelectedCompanyAccess(provider);
const isSqlite = provider?.dialect === 'sqlite3';
const getSortSql = isSqlite ? SQLITE_GET_NEXT_SORT : MSSQL_GET_NEXT_SORT;
const createSql = isSqlite ? SQLITE_CREATE : MSSQL_CREATE;
/**
* Creates a new printer for the user's selected company.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {object} input - Printer input.
* @param {string} input.address - Printer address (network IP/host/path).
* @param {string} input.type - Printer type ("esc/pos" or "zpl").
* @param {string} [input.model] - Optional printer model name.
* @param {string} [input.serial] - Optional printer serial number.
* @param {number} [input.sort] - Optional sort order (auto-increments if omitted).
* @param {string} [input.desc] - Optional description.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}>}
* @throws {Error} If address is missing, type is invalid, or sort is invalid.
*
* @example
* const printer = await store.printer.create(googleAuthId, {
* address: '192.168.1.200',
* type: 'esc/pos',
* model: 'TM-T88VI',
* desc: 'Bar receipt printer',
* });
*/
return async (googleAuthId, input = {}, tx) => {
const address = typeof input.address === 'string' ? input.address.trim() : '';
if (!address) {
throw new Error('Address required');
}
const type = typeof input.type === 'string' ? input.type.trim() : '';
if (!type || !VALID_TYPES.has(type)) {
throw new Error('Invalid printer type: must be "esc/pos" or "zpl"');
}
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, runner);
let sort = input.sort;
if (sort === undefined || sort === null) {
const next = await runner.query(getSortSql, { companyId });
sort = next.rows[0].sort;
} else if (!Number.isFinite(sort)) {
throw new Error('Invalid sort');
}
const model = optionalString(input.model);
const serial = optionalString(input.serial);
const desc = optionalString(input.desc);
const result = await runner.query(createSql, {
companyId,
address,
type,
model,
serial,
sort,
desc,
});
const row = result.rows[0] ?? {
id: result.insertId,
company_id: companyId,
address,
type,
model,
serial,
sort,
desc,
};
return shape(row);
};
}

View File

@@ -0,0 +1,38 @@
import { DELETE_BY_COMPANY_AND_ID as MSSQL_DELETE } from '../../providers/mssql/queries/printer.js';
import { DELETE_BY_COMPANY_AND_ID as SQLITE_DELETE } from '../../providers/sqlite3/queries/printer.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
export default function del(provider) {
const access = resolveSelectedCompanyAccess(provider);
const sql =
provider?.dialect === 'sqlite3' ? SQLITE_DELETE : MSSQL_DELETE;
/**
* Deletes a printer for the user's selected company.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {number} id - The printer ID to delete.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<void>}
* @throws {Error} If printer is not found.
*/
return async (googleAuthId, id, tx) => {
const numericId = Number(id);
if (!Number.isInteger(numericId) || numericId <= 0) {
throw new Error('Printer not found');
}
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, runner);
const result = await runner.query(sql, {
id: numericId,
companyId,
});
if (!result.rowsAffected) {
throw new Error('Printer not found');
}
};
}

View File

@@ -0,0 +1,53 @@
import { GET_BY_COMPANY_AND_ID as MSSQL_GET_BY_ID } from '../../providers/mssql/queries/printer.js';
import { GET_BY_COMPANY_AND_ID as SQLITE_GET_BY_ID } from '../../providers/sqlite3/queries/printer.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
function shape(row) {
return {
id: row.id,
company_id: row.company_id ?? row.companyId,
address: row.address,
type: row.type,
model: row.model ?? null,
serial: row.serial ?? null,
sort: row.sort,
desc: row.desc ?? null,
};
}
export default function getById(provider) {
const access = resolveSelectedCompanyAccess(provider);
const sql =
provider?.dialect === 'sqlite3' ? SQLITE_GET_BY_ID : MSSQL_GET_BY_ID;
/**
* Retrieves a printer by its ID for the user's selected company.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {number} id - The printer ID.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}|undefined>}
*
* @example
* const printer = await store.printer.getById(googleAuthId, 1);
* // => { id: 1, company_id: 1, address: '192.168.1.100', type: 'esc/pos', ... }
*/
return async (googleAuthId, id, tx) => {
const numericId = Number(id);
if (!Number.isInteger(numericId) || numericId <= 0) {
return undefined;
}
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, runner);
const result = await runner.query(sql, {
id: numericId,
companyId,
});
const row = result.rows[0];
return row ? shape(row) : undefined;
};
}

44
src/store/printer/list.js Normal file
View File

@@ -0,0 +1,44 @@
import { LIST_BY_COMPANY as MSSQL_LIST_BY_COMPANY } from '../../providers/mssql/queries/printer.js';
import { LIST_BY_COMPANY as SQLITE_LIST_BY_COMPANY } from '../../providers/sqlite3/queries/printer.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
function shape(row) {
return {
id: row.id,
company_id: row.company_id ?? row.companyId,
address: row.address,
type: row.type,
model: row.model ?? null,
serial: row.serial ?? null,
sort: row.sort,
desc: row.desc ?? null,
};
}
export default function list(provider) {
const access = resolveSelectedCompanyAccess(provider);
const sql =
provider?.dialect === 'sqlite3'
? SQLITE_LIST_BY_COMPANY
: MSSQL_LIST_BY_COMPANY;
/**
* Lists all printers for the user's selected company.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<Array<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}>>}
*
* @example
* const printers = await store.printer.list(42);
* // => [{ id: 1, company_id: 1, address: '192.168.1.100', type: 'esc/pos', ... }]
*/
return async (googleAuthId, tx) => {
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, runner);
const result = await runner.query(sql, { companyId });
return result.rows.map(shape);
};
}

View File

@@ -0,0 +1,76 @@
import {
LIST_IDS_BY_COMPANY as MSSQL_LIST_IDS_BY_COMPANY,
UPDATE_SORT as MSSQL_UPDATE_SORT,
} from '../../providers/mssql/queries/printer.js';
import {
LIST_IDS_BY_COMPANY as SQLITE_LIST_IDS_BY_COMPANY,
UPDATE_SORT as SQLITE_UPDATE_SORT,
} from '../../providers/sqlite3/queries/printer.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
export default function order(provider) {
const access = resolveSelectedCompanyAccess(provider);
const isSqlite = provider?.dialect === 'sqlite3';
const listIdsSql = isSqlite
? SQLITE_LIST_IDS_BY_COMPANY
: MSSQL_LIST_IDS_BY_COMPANY;
const updateSortSql = isSqlite ? SQLITE_UPDATE_SORT : MSSQL_UPDATE_SORT;
/**
* Reorders the printers of the user's selected company.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {object} input - The reorder input.
* @param {Array<number>} input.printerIds - The printer ids in their new order.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{printerIds: Array<number>}>} The applied order.
* @throws {Error} If the order is invalid.
*/
return async (googleAuthId, { printerIds } = {}, tx) => {
if (!Array.isArray(printerIds)) {
throw new Error('Invalid printer order');
}
const runOrder = async (runner) => {
const { companyId } = await access(googleAuthId, runner);
const items = await runner.query(listIdsSql, { companyId });
const existing = new Set(items.rows.map((r) => r.id));
if (printerIds.length !== existing.size) {
throw new Error('Invalid printer order');
}
const seen = new Set();
for (const printerId of printerIds) {
if (
!Number.isFinite(printerId) ||
!existing.has(printerId) ||
seen.has(printerId)
) {
throw new Error('Invalid printer order');
}
seen.add(printerId);
}
for (let sort = 0; sort < printerIds.length; sort++) {
await runner.query(updateSortSql, {
id: printerIds[sort],
companyId,
sort,
});
}
return { printerIds };
};
if (tx) {
return runOrder(makeRunner(provider, tx));
}
if (typeof provider?.transaction === 'function') {
return provider.transaction(runOrder);
}
return runOrder(makeRunner(provider));
};
}

124
src/store/printer/update.js Normal file
View File

@@ -0,0 +1,124 @@
import {
GET_BY_COMPANY_AND_ID as MSSQL_GET_BY_ID,
UPDATE as MSSQL_UPDATE,
} from '../../providers/mssql/queries/printer.js';
import {
GET_BY_COMPANY_AND_ID as SQLITE_GET_BY_ID,
UPDATE as SQLITE_UPDATE,
} from '../../providers/sqlite3/queries/printer.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
const VALID_TYPES = new Set(['esc/pos', 'zpl']);
function shape(row) {
return {
id: row.id,
company_id: row.company_id ?? row.companyId,
address: row.address,
type: row.type,
model: row.model ?? null,
serial: row.serial ?? null,
sort: row.sort,
desc: row.desc ?? null,
};
}
function optionalString(value) {
if (value == null || value === '') return null;
const s = String(value).trim();
return s || null;
}
export default function update(provider) {
const access = resolveSelectedCompanyAccess(provider);
const isSqlite = provider?.dialect === 'sqlite3';
const getSql = isSqlite ? SQLITE_GET_BY_ID : MSSQL_GET_BY_ID;
const updateSql = isSqlite ? SQLITE_UPDATE : MSSQL_UPDATE;
/**
* Updates a printer for the user's selected company.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {number} id - The printer ID to update.
* @param {object} input - Update payload.
* @param {string} [input.address] - The printer address.
* @param {string} [input.type] - The printer type ("esc/pos" or "zpl").
* @param {string|null} [input.model] - The printer model.
* @param {string|null} [input.serial] - The printer serial.
* @param {number} [input.sort] - The sort order.
* @param {string|null} [input.desc] - The description.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, company_id: number, address: string, type: string, model: string|null, serial: string|null, sort: number, desc: string|null}>}
* @throws {Error} If printer not found, address is empty, type is invalid, or sort is invalid.
*/
return async (googleAuthId, id, input = {}, tx) => {
const numericId = Number(id);
if (!Number.isInteger(numericId) || numericId <= 0) {
throw new Error('Printer not found');
}
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, runner);
const existing = await runner.query(getSql, { id: numericId, companyId });
const current = existing.rows[0];
if (!current) {
throw new Error('Printer not found');
}
let address = current.address;
if (input.address !== undefined) {
const cleaned = typeof input.address === 'string' ? input.address.trim() : '';
if (!cleaned) {
throw new Error('Address required');
}
address = cleaned;
}
let type = current.type;
if (input.type !== undefined) {
const cleaned = typeof input.type === 'string' ? input.type.trim() : '';
if (!cleaned || !VALID_TYPES.has(cleaned)) {
throw new Error('Invalid printer type: must be "esc/pos" or "zpl"');
}
type = cleaned;
}
let sort = current.sort;
if (input.sort !== undefined) {
if (!Number.isFinite(input.sort)) {
throw new Error('Invalid sort');
}
sort = input.sort;
}
const model = input.model !== undefined ? optionalString(input.model) : (current.model ?? null);
const serial = input.serial !== undefined ? optionalString(input.serial) : (current.serial ?? null);
const desc = input.desc !== undefined ? optionalString(input.desc) : (current.desc ?? null);
const result = await runner.query(updateSql, {
id: numericId,
companyId,
address,
type,
model,
serial,
sort,
desc,
});
const row = result.rows[0] ?? {
id: numericId,
company_id: companyId,
address,
type,
model,
serial,
sort,
desc,
};
return shape(row);
};
}

190
src/store/stock/adjust.js Normal file
View File

@@ -0,0 +1,190 @@
import * as mssqlQueries from '../../providers/mssql/queries/manifestDoc.js';
import * as sqliteQueries from '../../providers/sqlite3/queries/manifestDoc.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import resolveArticleBySku from '../article/resolveArticleBySku.js';
import nextNumber from '../numbers/nextNumber.js';
import ledgerAdd from '../ledger/add.js';
import makeRunner from '../runner.js';
import { parseDate } from '../manifestLines.js';
const ADJUSTMENT_TYPE = 'adjustment';
const GET_ARTICLE_NAME_SQL = `
SELECT at.name
FROM article a
LEFT JOIN articletext at ON at.article_id = a.id AND at.language_id = @languageId
WHERE a.id = @articleId;
`;
export default function adjust(provider) {
const access = resolveSelectedCompanyAccess(provider);
const resolveArticle = resolveArticleBySku(provider);
const allocateNumber = nextNumber(provider);
const addLedger = ledgerAdd(provider);
const isSqlite = provider?.dialect === 'sqlite3';
const queries = isSqlite ? sqliteQueries : mssqlQueries;
/**
* Adjusts article stock manually by creating an implicit manifest of type "adjustment",
* allocating a number from the "adjustment" number scheme, and appending to the ledger.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {object} input - Adjustment payload.
* @param {string} [input.sku] - Article SKU (if single-item adjustment).
* @param {number} [input.warehouseId] - Warehouse ID (can also pass warehouse_id).
* @param {number} [input.amount] - Signed adjustment amount (+ to add, - to remove).
* @param {string} [input.text] - Optional adjustment reason/memo.
* @param {string} [input.externalNumber] - Optional external reference.
* @param {string|Date} [input.date] - Optional date (defaults to now).
* @param {Array<object>} [input.lines] - Optional array of items to adjust in one manifest.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{manifest: {id: number, number: string, type: string, date: string, createdAt: string}, lines: Array<object>, ledger: Array<object>}>}
*/
return async (googleAuthId, input = {}, tx) => {
const rawLines = Array.isArray(input.lines)
? input.lines
: [
{
sku: input.sku,
warehouseId: input.warehouseId ?? input.warehouse_id,
amount: input.amount,
text: input.text ?? input.transactionText ?? input.transaction_text,
},
];
if (rawLines.length === 0) {
throw new Error('No items to adjust');
}
const defaultWarehouseId = input.warehouseId ?? input.warehouse_id;
const defaultText = input.text ?? input.transactionText ?? input.transaction_text;
const externalNumber = input.externalNumber?.trim?.() ? input.externalNumber.trim() : null;
const date = input.date ? parseDate(input.date) ?? new Date() : new Date();
const createdAt = new Date();
const normalizedLines = rawLines.map((line, idx) => {
const sku = typeof line.sku === 'string' ? line.sku.trim() : '';
if (!sku) {
throw new Error(`SKU required for item ${idx + 1}`);
}
const rawWhId = line.warehouseId ?? line.warehouse_id ?? defaultWarehouseId;
const warehouseId = Number(rawWhId);
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
throw new Error(`Warehouse required for item ${idx + 1} (${sku})`);
}
const amount = Number(line.amount);
if (!Number.isFinite(amount) || amount === 0) {
throw new Error(`Invalid amount for item ${idx + 1} (${sku}): must be non-zero number`);
}
const text = (line.text ?? line.transactionText ?? line.transaction_text ?? defaultText)?.trim?.() ||
(amount > 0 ? `Manual stock addition (+${amount})` : `Manual stock removal (${amount})`);
return {
sku,
warehouseId,
amount,
text,
};
});
const run = async (runner, activeTx) => {
const { companyId } = await access(googleAuthId, runner);
// Validate all articles exist and belong to the user's company
const resolvedArticles = [];
for (const item of normalizedLines) {
const resolved = await resolveArticle(googleAuthId, item.sku, activeTx);
const nameRes = await runner.query(GET_ARTICLE_NAME_SQL, {
articleId: resolved.articleId,
languageId: resolved.languageId,
});
const articleName = nameRes.rows[0]?.name ?? item.sku;
resolvedArticles.push({ ...item, ...resolved, articleName });
}
// Allocate unique adjustment number using the dedicated adjustment number scheme
const number = await allocateNumber(companyId, ADJUSTMENT_TYPE, activeTx);
// Create the implicit adjustment manifest
const manifestRes = await runner.query(queries.CREATE_MANIFEST, {
companyId,
number,
type: ADJUSTMENT_TYPE,
entityId: null,
externalNumber,
date,
createdAt,
});
const manifestId = manifestRes.rows[0]?.id ?? manifestRes.insertId;
const createdLines = [];
const createdLedgerEntries = [];
for (const item of resolvedArticles) {
// Create manifestarticle row
const lineRes = await runner.query(queries.CREATE_LINE, {
manifestId,
sku: item.sku,
name: item.articleName,
pu: 1,
amount: Math.abs(item.amount),
net: 0,
comment: item.text,
rebate: 0,
taxrate: 0,
});
const manifestarticleId = lineRes.rows[0]?.id ?? lineRes.insertId;
// Append to ledger
const ledgerRow = await addLedger(
googleAuthId,
{
manifestarticle_id: manifestarticleId,
warehouse_id: item.warehouseId,
transaction_type: ADJUSTMENT_TYPE,
amount: item.amount,
transaction_text: item.text,
},
activeTx,
);
createdLines.push({
manifestarticle_id: manifestarticleId,
sku: item.sku,
name: item.articleName,
warehouse_id: item.warehouseId,
amount: item.amount,
text: item.text,
});
createdLedgerEntries.push(ledgerRow);
}
return {
manifest: {
id: manifestId,
number,
type: ADJUSTMENT_TYPE,
date: date.toISOString(),
createdAt: createdAt.toISOString(),
externalNumber,
},
lines: createdLines,
ledger: createdLedgerEntries,
};
};
if (tx) {
return run(makeRunner(provider, tx), tx);
}
if (typeof provider?.transaction === 'function') {
return provider.transaction((runner, activeTx) => run(runner, activeTx));
}
return run(makeRunner(provider));
};
}

View File

@@ -0,0 +1,59 @@
import { CREATE as MSSQL_CREATE } from '../../providers/mssql/queries/warehouse.js';
import { CREATE as SQLITE_CREATE } from '../../providers/sqlite3/queries/warehouse.js';
import { isUniqueConstraintError } from '../../providers/provider.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
function shape(row) {
return { id: row.id, name: row.name };
}
export default function create(provider) {
const access = resolveSelectedCompanyAccess(provider);
const sql =
provider?.dialect === 'sqlite3' ? SQLITE_CREATE : MSSQL_CREATE;
/**
* Creates a new warehouse for the user's selected company.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {object} input - Warehouse input.
* @param {string} input.name - The warehouse name.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, name: string}>} The created warehouse.
* @throws {Error} If name is missing or already exists.
*
* @example
* const wh = await store.warehouse.create(googleAuthId, { name: 'Hauptlager' });
* // => { id: 1, name: 'Hauptlager' }
*/
return async (googleAuthId, { name } = {}, tx) => {
const cleaned = typeof name === 'string' ? name.trim() : '';
if (!cleaned) {
throw new Error('Name required');
}
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, runner);
try {
const result = await runner.query(sql, {
companyId,
name: cleaned,
});
const row = result.rows[0] ?? { id: result.insertId, name: cleaned };
return shape(row);
} catch (err) {
if (
isUniqueConstraintError(err) ||
err?.number === 2627 ||
err?.number === 2601 ||
err?.code === 'SQLITE_CONSTRAINT_UNIQUE'
) {
throw new Error('Warehouse already exists');
}
throw err;
}
};
}

View File

@@ -0,0 +1,62 @@
import {
DELETE_BY_COMPANY_AND_ID as MSSQL_DELETE,
CHECK_LEDGER_USAGE as MSSQL_CHECK_USAGE,
} from '../../providers/mssql/queries/warehouse.js';
import {
DELETE_BY_COMPANY_AND_ID as SQLITE_DELETE,
CHECK_LEDGER_USAGE as SQLITE_CHECK_USAGE,
} from '../../providers/sqlite3/queries/warehouse.js';
import { isForeignKeyConstraintError } from '../../providers/provider.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
export default function del(provider) {
const access = resolveSelectedCompanyAccess(provider);
const isSqlite = provider?.dialect === 'sqlite3';
const deleteSql = isSqlite ? SQLITE_DELETE : MSSQL_DELETE;
const checkUsageSql = isSqlite ? SQLITE_CHECK_USAGE : MSSQL_CHECK_USAGE;
/**
* Deletes a warehouse for the user's selected company, unless referenced in the ledger.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {number} id - The warehouse ID to delete.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<void>}
* @throws {Error} If warehouse not found or is in use in the ledger.
*
* @example
* await store.warehouse.delete(googleAuthId, 1);
*/
return async (googleAuthId, id, tx) => {
const numericId = Number(id);
if (!Number.isInteger(numericId) || numericId <= 0) {
throw new Error('Warehouse not found');
}
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, runner);
// Pre-check if warehouse is referenced in the ledger
const usage = await runner.query(checkUsageSql, { warehouseId: numericId });
if (usage.rows && usage.rows.length > 0) {
throw new Error('Warehouse in use in ledger');
}
try {
const result = await runner.query(deleteSql, {
id: numericId,
companyId,
});
if (!result.rowsAffected) {
throw new Error('Warehouse not found');
}
} catch (err) {
if (isForeignKeyConstraintError(err)) {
throw new Error('Warehouse in use in ledger');
}
throw err;
}
};
}

View File

@@ -0,0 +1,44 @@
import { GET_BY_COMPANY_AND_ID as MSSQL_GET_BY_ID } from '../../providers/mssql/queries/warehouse.js';
import { GET_BY_COMPANY_AND_ID as SQLITE_GET_BY_ID } from '../../providers/sqlite3/queries/warehouse.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
function shape(row) {
return { id: row.id, name: row.name };
}
export default function getById(provider) {
const access = resolveSelectedCompanyAccess(provider);
const sql =
provider?.dialect === 'sqlite3' ? SQLITE_GET_BY_ID : MSSQL_GET_BY_ID;
/**
* Retrieves a warehouse by its ID for the user's selected company.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {number} id - The warehouse ID.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, name: string}|undefined>} The warehouse or undefined.
*
* @example
* const wh = await store.warehouse.getById(googleAuthId, 1);
* // => { id: 1, name: 'Hauptlager' }
*/
return async (googleAuthId, id, tx) => {
const numericId = Number(id);
if (!Number.isInteger(numericId) || numericId <= 0) {
return undefined;
}
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, runner);
const result = await runner.query(sql, {
id: numericId,
companyId,
});
const row = result.rows[0];
return row ? shape(row) : undefined;
};
}

View File

@@ -0,0 +1,33 @@
import { LIST_BY_COMPANY as MSSQL_LIST } from '../../providers/mssql/queries/warehouse.js';
import { LIST_BY_COMPANY as SQLITE_LIST } from '../../providers/sqlite3/queries/warehouse.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
function shape(row) {
return { id: row.id, name: row.name };
}
export default function list(provider) {
const access = resolveSelectedCompanyAccess(provider);
const sql =
provider?.dialect === 'sqlite3' ? SQLITE_LIST : MSSQL_LIST;
/**
* Lists all warehouses for the user's selected company.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<Array<{id: number, name: string}>>} List of warehouses.
*
* @example
* const warehouses = await store.warehouse.list(googleAuthId);
* // => [{ id: 1, name: 'Hauptlager' }]
*/
return async (googleAuthId, tx) => {
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, runner);
const result = await runner.query(sql, { companyId });
return result.rows.map(shape);
};
}

View File

@@ -0,0 +1,77 @@
import {
GET_BY_COMPANY_AND_ID as MSSQL_GET_BY_ID,
UPDATE_BY_ID as MSSQL_UPDATE,
} from '../../providers/mssql/queries/warehouse.js';
import {
GET_BY_COMPANY_AND_ID as SQLITE_GET_BY_ID,
UPDATE_BY_ID as SQLITE_UPDATE,
} from '../../providers/sqlite3/queries/warehouse.js';
import { isUniqueConstraintError } from '../../providers/provider.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
function shape(row) {
return { id: row.id, name: row.name };
}
export default function update(provider) {
const access = resolveSelectedCompanyAccess(provider);
const isSqlite = provider?.dialect === 'sqlite3';
const getSql = isSqlite ? SQLITE_GET_BY_ID : MSSQL_GET_BY_ID;
const updateSql = isSqlite ? SQLITE_UPDATE : MSSQL_UPDATE;
/**
* Updates a warehouse name for the user's selected company.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {number} id - The warehouse ID to update.
* @param {object} input - Update payload.
* @param {string} input.name - The new warehouse name.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, name: string}>} The updated warehouse.
* @throws {Error} If warehouse not found, name is missing, or name already exists.
*
* @example
* const updated = await store.warehouse.update(googleAuthId, 1, { name: 'Zentrallager' });
* // => { id: 1, name: 'Zentrallager' }
*/
return async (googleAuthId, id, { name } = {}, tx) => {
const numericId = Number(id);
if (!Number.isInteger(numericId) || numericId <= 0) {
throw new Error('Warehouse not found');
}
const cleaned = typeof name === 'string' ? name.trim() : '';
if (!cleaned) {
throw new Error('Name required');
}
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, runner);
const existing = await runner.query(getSql, { id: numericId, companyId });
if (!existing.rows[0]) {
throw new Error('Warehouse not found');
}
try {
await runner.query(updateSql, {
id: numericId,
companyId,
name: cleaned,
});
return shape({ id: numericId, name: cleaned });
} catch (err) {
if (
isUniqueConstraintError(err) ||
err?.number === 2627 ||
err?.number === 2601 ||
err?.code === 'SQLITE_CONSTRAINT_UNIQUE'
) {
throw new Error('Warehouse already exists');
}
throw err;
}
};
}