Compare commits
2 Commits
8a7500cb5a
...
c28b30d92a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c28b30d92a | ||
|
|
7383e13894 |
70
.agents/skills/project-overview/SKILL.md
Normal file
70
.agents/skills/project-overview/SKILL.md
Normal file
@@ -0,0 +1,70 @@
|
||||
---
|
||||
name: project-overview
|
||||
description: Architecture and conventions for the dashback + dashdbschema (libdashstore) monorepo. Use for any backend/store task: providers, store modules, routes, auth, ledger/stock, error mapping, testing.
|
||||
---
|
||||
|
||||
# Project Overview — dashback + dashdbschema
|
||||
|
||||
Multi-root workspace:
|
||||
|
||||
- `/home/seb/src/dashback` — Express backend (`dashback`, ESM, `type: module`). Depends on `libdashstore` via `file:../dashdbschema`.
|
||||
- `/home/seb/src/dashdbschema` — `libdashstore` library: MSSQL schema + domain store API. One class, methods mirror `src/store/<domain>/<action>.js`.
|
||||
- `/home/seb/src/dashback/quixpos2jtl/` — separate JTL/QuixPOS bridge (own `package.json`, Electron/CLI). Ignore unless task mentions JTL.
|
||||
|
||||
## libdashstore (`dashdbschema`)
|
||||
|
||||
Entry: `src/index.js` → `export default class LibDashStore`. Constructor requires a provider with `query/transaction/initialize/purge`. Namespaces are wired there, e.g. `this.stock = { adjust: stockAdjust(provider) }`, `this.ledger = { add, listByManifestarticleId, listBySku }`, plus `article, category, company, companyuser, delivery, order, quote, warehouse, ledger, stock, numbers, printer, labeltemplate, posterminal, supplier, articlesupplier, entity*, tax, unit, brand, lang, pic, manifestattachment, propertyname/articleproperty/categoryproperty, attributename/attributevalue/... , articlelist, optionslist`.
|
||||
|
||||
### Provider abstraction
|
||||
|
||||
- `src/providers/provider.js` — contract (`query(sql, params)`, `transaction(fn)`, `initialize()`, `purge()`).
|
||||
- `src/providers/mssql/` — production. Raw SQL in `queries/<domain>.js`, DDL in `schema.js` (`IF NOT EXISTS`, `SCHEMA_SCRIPTS`). Uses `OUTPUT INSERTED.*`, `TOP 1`, `WITH (UPDLOCK, HOLDLOCK)`.
|
||||
- `src/providers/sqlite3/` — dev/test (`BetterSqlite3Provider`, `better-sqlite3`). Mostly `import * as source from '../../mssql/queries/<x>.js'` + `translateQueries(source, '<domain>')`. DDL in `sqlite3/schema.js` (`RETURNING`, `LIMIT 1`). Auto-migrates `article.track_stock`, `ledger.created_at/warehouse_id` in `sqlite3/index.js`.
|
||||
- `bindParams` (sqlite): strips leading `@/:$`, maps `Date→ISO`, `boolean→1/0`, `null/undefined→null`. Both `@sku` and `sku` keys work.
|
||||
- `src/store/runner.js` (`makeRunner(provider, tx)`) — normalizes pool / tx / callable runner. Store code calls `runner.query(sql, params)` or `runner(sql, params)`. `runner.dialect === 'sqlite3'` selects query set. MSSQL legacy pool wrapped via `wrapMssql`.
|
||||
|
||||
### Store conventions
|
||||
|
||||
- Every store module: `export default function <action>(provider) { ...; return async (googleAuthId, input, tx) => {...} }`.
|
||||
- `googleAuthId` is always `google_auth.id`, never `companyuser.id`.
|
||||
- Company scoping: no `companyId` arg. `resolveSelectedCompanyAccess(provider)` reads `google_auth.selected_company` → `{ companyId, companyuserId, rootCategoryId }`. Missing → throw `No company selected`. Exceptions taking explicit `companyId`: `setSelectedCompany`, `companyuser.add`, `company.delete`, internals.
|
||||
- SKU resolution: `store/article/resolveArticleBySku.js` (`RESOLVE_ARTICLE_ACCESS_BY_SKU`) checks company + membership. Throws `Article not found` / `Parent not found` / `Not authorized`.
|
||||
- Errors are plain `Error` with exact message strings; HTTP mapping happens in `dashback` route `*ErrorStatus()` functions. Keep messages stable/greppable. Conflict → `409` (e.g. `EAN already in use`, `Warehouse in use in ledger`, `Stock tracking is disabled...`).
|
||||
- Manifest docs (`delivery/order/quote/adjustment`): header in `manifest`, lines in `manifestarticle`, helpers in `src/store/manifestLines.js` (`normalizeLines`, `insertLines`, `parseDate`, `shapeLine`) and `manifestDoc/helpers.js`. `insertLines` rejects father articles (`A father article cannot be booked on documents (SKU)`), resolves name/pu, ensures tax.
|
||||
- Numbers: `store/numbers/nextNumber.js`, types `sku, entity, delivery, adjustment`.
|
||||
|
||||
### Ledger + stock (important)
|
||||
|
||||
- `ledger` is append-only, tamper-chained: `hash_version=1`, `prev_hash = SHA-512(canonical JSON of prev row)` or `TODO_TSE_BASED_INITHASH` for genesis. See `store/ledger/add.js` (`shape`, `computePrevHash`, `INIT_HASH`).
|
||||
- Stock is **derived**: `SUM(ledger.amount) GROUP BY warehouse`, joined `ledger → manifestarticle → manifest`, matched on `ma.sku = article.sku OR ma.sku IN (SELECT sku FROM articlesupplier WHERE article_id = ...)`, filtered by `m.company_id`. See `providers/*/queries/article.js` (`warehousesJson`/`stock_calc`) and `posterminal.js` (`fBestand`). No `stock` column on article.
|
||||
- `store/stock/adjust.js` creates implicit manifest `type='adjustment'` (number from `adjustment` scheme) + one `manifestarticle` line per item (`amount: abs(amount)`) + one `ledger` row per item (`amount: signed`) + `articlehistory` (`Bestandskorrektur ±n (text)`). Validates: father → `A father article cannot have stock (SKU)`; Stückliste (`articlelist_id != null`) → `A Stückliste cannot have manual stock adjustments (SKU)`; **`track_stock==0` → `Stock tracking is disabled for article (SKU)`** (added as bugfix; checked before number allocation/manifest write, so batch is all-or-nothing).
|
||||
- `store/ledger/add.js` enforces the same guard for **any warehouse-scoped entry** (`warehouse_id != null` + line has SKU): looks up `article` by `sku` or `articlesupplier.sku` in same company, rejects if any match has `track_stock==0`. Non-warehouse entries (e.g. `PAYMENT`, memo `NOTE`) are still allowed. Guard runs before `GET_LATEST_ROW`/`INSERT_ROW`, inside the same runner/tx.
|
||||
- `POST /ledger` with `warehouse_id` is therefore also blocked for untracked articles; delivery receipts booked via ledger go through the same check.
|
||||
- `article.track_stock`: `BIT/INTEGER DEFAULT 1`. Managed via `article.createUnderParent({track_stock})`, `updateBySku`, `setTrackStockBySku`, `POST /article` (`track_stock`/`trackStock`, default true). `toggleFather` sets `track_stock=0` when becoming father. POS surfaces it as `use_stock '1'/'0'` (`store/posterminal/getProductList.js`).
|
||||
|
||||
## dashback (Express API)
|
||||
|
||||
- `src/index.js` → `src/api/index.js` (`startApi/stopApi`). Env in `src/config/env.js` (`.env`: `PORT` default 4208, `HTTPS_PORT`, `GOOGLE_CLIENT_ID`, `JWT_SECRET`, `CORS_ORIGINS`, `DB_PROVIDER=mssql|sqlite`, `SQLITE_PATH`, `MSSQL_*`).
|
||||
- Routes auto-loaded: `loadRoutes()` walks `src/api/routes/**/*.js`, calls `register(app, basePath)`. Each route file owns its `@openapi` JSDoc + `*ErrorStatus(error)` mapper + `requireSelectedCompany(req)`.
|
||||
- `src/db/store.js` — lazy singleton provider+store (`ensureConnection`), wraps every namespace method with timing logs (`libstore <ns>.<method> (Nms)` / `FAILED`). `src/db/<domain>.js` thin wrappers (`store.stock.adjust`, `store.ledger.add`, ...).
|
||||
- Auth: `src/api/middleware/auth.js` (Google SSO + JWT cookie/session, `req.user.{id, selectedCompanyId}`), `src/api/routes/auth/*`, `scripts/manageUsers.js` (allowlist). `src/api/middleware/logger.js` colors `>=400`.
|
||||
- Docs: `npm run docs:api` (`scripts/generateApiDocs.js` + `src/api/openapi.js` swagger) → `docs/api/routes.md` + `docs/api/routes/`. Per-route `x-markdown` hints.
|
||||
- SSE: `src/api/sse.js` (`emit`), `routes/events.js`. Stock adjust emits `stock`, `ledger`, `articles`, `article-<sku>`.
|
||||
- `src/v1/` — legacy POS compat (`/v1/...`, `posAuth`, static `use_stock: '0'` defaults in some stubs). `src/util/` — `cert.js` (self-signed), `errorLog.js`. `certs/`, `data/` (sqlite + `storage/content|fullbinary|thumbavif|thumbbinary`), `logs/errors/`.
|
||||
- HTTP status conventions per route file: `No company selected→400`, `Not authorized→403`, `*not found→404`, validation→400 (often via `includes()`), uniqueness/in-use→409, else 500 + `console.error`. Stock/ledger map `Stock tracking is disabled...→409` (fix for reported bug: `POST /stock/adjust` on `track_stock:false` returned `201` and wrote manifest+ledger; now `409` before any write).
|
||||
|
||||
## Tests / scripts
|
||||
|
||||
- Automated (sqlite temp DB, exit cleanly): `dashdbschema/scripts/test-ledger.js`, `test-stueckliste-stock.js`, `test-sqlite-storage.js`, `test-variant-flow.js`, `test-tombstone.js`, etc. Run with `cd /home/seb/src/dashdbschema && node scripts/test-ledger.js`.
|
||||
- **Do NOT run `scripts/test-api.js` for verification** — it is an interactive `@clack/prompts` menu (MSSQL) that hangs waiting for input.
|
||||
- `dashdbschema` scripts: `init-schema`, `purge-db`, `reset-db`, `benchmark`, `generate-api-doc.js`, `generate-schema-graph.js`. `dashback` scripts: `manageUsers.js`, `generateApiDocs.js`, `testImageCrop.js`. `dashback` has no `npm test`.
|
||||
- Quick regression pattern (sqlite in-memory/temp): create provider → `new LibDashStore(provider)` → `google_auth.add` → `company.create` → `setSelectedCompany` → `unit.upsert` → `warehouse.create` → `article.createUnderParent({track_stock:false})` → assert `stock.adjust` throws, `ledger.listBySku` empty, tracked article still adjusts.
|
||||
|
||||
## Agent tips
|
||||
|
||||
- Add stock invariants in `dashdbschema/src/store/` (not routes) so both `stock.adjust` and direct `ledger.add` are covered; mirror the error string in `dashback/src/api/routes/{stock,ledger,delivery}.js` mappers if a new status is needed.
|
||||
- When touching SQL, update **both** `mssql/queries/*` and check `sqlite3/queries/*` translation; watch `OUTPUT INSERTED` vs `RETURNING`, `TOP 1` vs `LIMIT 1`.
|
||||
- Prefer `runner.query('SELECT ..., track_stock FROM article WHERE id = @articleId', { articleId })` for per-article flags; for ledger-by-SKU use the `article OR articlesupplier.sku` lookup scoped by `company_id`.
|
||||
- Keep `API.*.md` in `dashdbschema/` (generated via `npm run api-doc`) in mind but edit JSDoc source, not the markdown.
|
||||
|
||||
|
||||
@@ -91,8 +91,13 @@ Generated from `@openapi` annotations in [`src/api/routes/`](../../src/api/route
|
||||
| [`routes/category/delete.md`](routes/category/delete.md) | `DELETE /category/{id}` |
|
||||
| [`routes/category/update.md`](routes/category/update.md) | `PATCH /category/{id}` |
|
||||
| [`routes/category/articles.md`](routes/category/articles.md) | `GET /category/{id}/articles` |
|
||||
| [`routes/category/_id/attributevalue.get.md`](routes/category/_id/attributevalue.get.md) | `GET /category/{id}/attributevalue` |
|
||||
| [`routes/category/_id/attributevalue.put.md`](routes/category/_id/attributevalue.put.md) | `PUT /category/{id}/attributevalue` |
|
||||
| [`routes/category/delete-image.md`](routes/category/delete-image.md) | `DELETE /category/{id}/image` |
|
||||
| [`routes/category/add-image.md`](routes/category/add-image.md) | `POST /category/{id}/image` |
|
||||
| [`routes/category/_id/property.get.md`](routes/category/_id/property.get.md) | `GET /category/{id}/property` |
|
||||
| [`routes/category/_id/property.put.md`](routes/category/_id/property.put.md) | `PUT /category/{id}/property` |
|
||||
| [`routes/category/_id/property/_propertyId.md`](routes/category/_id/property/_propertyId.md) | `DELETE /category/{id}/property/{propertyId}` |
|
||||
| [`routes/company/list.md`](routes/company/list.md) | `GET /company` |
|
||||
| [`routes/company/create.md`](routes/company/create.md) | `POST /company` |
|
||||
| [`routes/companysetting/list.md`](routes/companysetting/list.md) | `GET /company/setting` |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Dash API Routes Overview
|
||||
|
||||
Overview of all 136 API endpoints across all modules.
|
||||
Overview of all 141 API endpoints across all modules.
|
||||
|
||||
### Parameter Notation
|
||||
|
||||
@@ -66,7 +66,12 @@ Overview of all 136 API endpoints across all modules.
|
||||
| `DELETE` | `/category/{id}` | `id:integer` | `204 void` | Delete category |
|
||||
| `PATCH` | `/category/{id}` | `id:integer, body: { name?, parentId? }` | `200 { category: { id, name, slug, parentId, sort } }` | Update category (rename or move) |
|
||||
| `GET` | `/category/{id}/articles` | `id:integer` | `200 { articles: { id, sku, name, slug, net, taxRate, track_stock, optionsCount, articleListCount, childCount, fullHash, thumbW, thumbH, thumbHash, brand }[] }` | Articles in category |
|
||||
| `GET` | `/category/{id}/attributevalue` | `id:integer` | `200 { attributevalues: { id, categoryId, attributeId, attributeName, exclusive, attributeValueId, value, sort }[] }` | List category attribute values |
|
||||
| `PUT` | `/category/{id}/attributevalue` | `id:integer, body: { attributevalues: any[] }` | `200 { attributevalues: { id, categoryId, attributeId, attributeName, exclusive, attributeValueId, value, sort }[] }` | Bulk set category attribute values |
|
||||
| `DELETE` | `/category/{id}/image` | `id:integer` | `200 { category: { id, thumbW, thumbH, thumbHash } }` | Delete category image |
|
||||
| `GET` | `/category/{id}/property` | `id:integer` | `200 { properties: { id, categoryId, propertyId, name, exclusive, value, sort }[] }` | List category properties |
|
||||
| `PUT` | `/category/{id}/property` | `id:integer, body: { properties: { propertyId, value, sort? }[] }` | `200 { properties: { id, categoryId, propertyId, name, exclusive, value, sort }[] }` | Bulk set category properties |
|
||||
| `DELETE` | `/category/{id}/property/{propertyId}` | `id:integer, propertyId:integer` | `200` | Delete category property |
|
||||
| `GET` | `/company` | — | `200 { companies: { id, iso639, name, taxrate, reducedtaxrate }[] }` | List companies |
|
||||
| `GET` | `/company/setting` | — | `200 { settings: { key, value }[] }` | List company settings |
|
||||
| `GET` | `/company/setting/{key}` | `key:string` | `200 { setting: { key, value } }` | Get company setting by key |
|
||||
|
||||
38
docs/api/routes/category/_id/attributevalue.get.md
Normal file
38
docs/api/routes/category/_id/attributevalue.get.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# `GET /category/{id}/attributevalue`
|
||||
|
||||
Protected. Requires a valid session cookie (`credentials: 'include'`).
|
||||
|
||||
List category attribute values
|
||||
|
||||
Fetches all attribute values assigned to a category.
|
||||
|
||||
## Path parameters
|
||||
|
||||
| Param | Required | Type | Description |
|
||||
|-------|----------|------|-------------|
|
||||
| `id` | yes | integer | Category ID |
|
||||
|
||||
## Response `200`
|
||||
|
||||
List of attribute values assigned to this category
|
||||
|
||||
```json
|
||||
{
|
||||
"attributevalues": [
|
||||
{
|
||||
"id": 1,
|
||||
"categoryId": 1,
|
||||
"attributeId": 1,
|
||||
"attributeName": "…",
|
||||
"exclusive": true,
|
||||
"attributeValueId": 1,
|
||||
"value": "…",
|
||||
"sort": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
_Generated from `@openapi` JSDoc. Do not edit by hand — run `npm run docs:api`._
|
||||
52
docs/api/routes/category/_id/attributevalue.put.md
Normal file
52
docs/api/routes/category/_id/attributevalue.put.md
Normal file
@@ -0,0 +1,52 @@
|
||||
# `PUT /category/{id}/attributevalue`
|
||||
|
||||
Protected. Requires a valid session cookie (`credentials: 'include'`).
|
||||
|
||||
Bulk set category attribute values
|
||||
|
||||
Replaces all attribute values for a category. Enforces exclusive constraint (max one value per exclusive attribute).
|
||||
|
||||
## Path parameters
|
||||
|
||||
| Param | Required | Type | Description |
|
||||
|-------|----------|------|-------------|
|
||||
| `id` | yes | integer | Category ID |
|
||||
|
||||
## Body (JSON)
|
||||
|
||||
| Field | Required | Type | Description |
|
||||
|-------|----------|------|-------------|
|
||||
| `attributevalues` | yes | any[] | Array of attribute value IDs (numbers) or objects with id or attributeValueId |
|
||||
|
||||
```json
|
||||
{
|
||||
"attributevalues": [
|
||||
"…"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Response `200`
|
||||
|
||||
Updated category attribute values
|
||||
|
||||
```json
|
||||
{
|
||||
"attributevalues": [
|
||||
{
|
||||
"id": 1,
|
||||
"categoryId": 1,
|
||||
"attributeId": 1,
|
||||
"attributeName": "…",
|
||||
"exclusive": true,
|
||||
"attributeValueId": 1,
|
||||
"value": "…",
|
||||
"sort": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
_Generated from `@openapi` JSDoc. Do not edit by hand — run `npm run docs:api`._
|
||||
37
docs/api/routes/category/_id/property.get.md
Normal file
37
docs/api/routes/category/_id/property.get.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# `GET /category/{id}/property`
|
||||
|
||||
Protected. Requires a valid session cookie (`credentials: 'include'`).
|
||||
|
||||
List category properties
|
||||
|
||||
Fetches all free-form properties set on a category.
|
||||
|
||||
## Path parameters
|
||||
|
||||
| Param | Required | Type | Description |
|
||||
|-------|----------|------|-------------|
|
||||
| `id` | yes | integer | Category ID |
|
||||
|
||||
## Response `200`
|
||||
|
||||
List of properties for this category
|
||||
|
||||
```json
|
||||
{
|
||||
"properties": [
|
||||
{
|
||||
"id": 1,
|
||||
"categoryId": 1,
|
||||
"propertyId": 1,
|
||||
"name": "…",
|
||||
"exclusive": true,
|
||||
"value": "…",
|
||||
"sort": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
_Generated from `@openapi` JSDoc. Do not edit by hand — run `npm run docs:api`._
|
||||
58
docs/api/routes/category/_id/property.put.md
Normal file
58
docs/api/routes/category/_id/property.put.md
Normal file
@@ -0,0 +1,58 @@
|
||||
# `PUT /category/{id}/property`
|
||||
|
||||
Protected. Requires a valid session cookie (`credentials: 'include'`).
|
||||
|
||||
Bulk set category properties
|
||||
|
||||
Replaces all properties for a category.
|
||||
|
||||
## Path parameters
|
||||
|
||||
| Param | Required | Type | Description |
|
||||
|-------|----------|------|-------------|
|
||||
| `id` | yes | integer | Category ID |
|
||||
|
||||
## Body (JSON)
|
||||
|
||||
| Field | Required | Type | Description |
|
||||
|-------|----------|------|-------------|
|
||||
| `properties` | yes | object[] | |
|
||||
| `properties[].propertyId` | yes | integer | |
|
||||
| `properties[].value` | yes | string | |
|
||||
| `properties[].sort` | no | integer | |
|
||||
|
||||
```json
|
||||
{
|
||||
"properties": [
|
||||
{
|
||||
"propertyId": 1,
|
||||
"value": "…",
|
||||
"sort": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Response `200`
|
||||
|
||||
Updated category properties
|
||||
|
||||
```json
|
||||
{
|
||||
"properties": [
|
||||
{
|
||||
"id": 1,
|
||||
"categoryId": 1,
|
||||
"propertyId": 1,
|
||||
"name": "…",
|
||||
"exclusive": true,
|
||||
"value": "…",
|
||||
"sort": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
_Generated from `@openapi` JSDoc. Do not edit by hand — run `npm run docs:api`._
|
||||
22
docs/api/routes/category/_id/property/_propertyId.md
Normal file
22
docs/api/routes/category/_id/property/_propertyId.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# `DELETE /category/{id}/property/{propertyId}`
|
||||
|
||||
Protected. Requires a valid session cookie (`credentials: 'include'`).
|
||||
|
||||
Delete category property
|
||||
|
||||
Removes a single property from a category.
|
||||
|
||||
## Path parameters
|
||||
|
||||
| Param | Required | Type | Description |
|
||||
|-------|----------|------|-------------|
|
||||
| `id` | yes | integer | |
|
||||
| `propertyId` | yes | integer | |
|
||||
|
||||
## Response `200`
|
||||
|
||||
Deleted successfully
|
||||
|
||||
---
|
||||
|
||||
_Generated from `@openapi` JSDoc. Do not edit by hand — run `npm run docs:api`._
|
||||
@@ -1106,6 +1106,45 @@
|
||||
* type: string
|
||||
* sort:
|
||||
* type: integer
|
||||
* CategoryProperty:
|
||||
* type: object
|
||||
* required: [id, propertyId, name, exclusive, value, sort]
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* categoryId:
|
||||
* type: integer
|
||||
* propertyId:
|
||||
* type: integer
|
||||
* name:
|
||||
* type: string
|
||||
* exclusive:
|
||||
* type: boolean
|
||||
* value:
|
||||
* type: string
|
||||
* sort:
|
||||
* type: integer
|
||||
* CategoryAttributeValue:
|
||||
* type: object
|
||||
* required: [id, attributeId, attributeName, attributeValueId, value, sort]
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* categoryId:
|
||||
* type: integer
|
||||
* attributeId:
|
||||
* type: integer
|
||||
* attributeName:
|
||||
* type: string
|
||||
* exclusive:
|
||||
* type: boolean
|
||||
* attributeValueId:
|
||||
* type: integer
|
||||
* value:
|
||||
* type: string
|
||||
* sort:
|
||||
* type: integer
|
||||
*/
|
||||
|
||||
export {};
|
||||
|
||||
|
||||
164
src/api/routes/categoryattributevalue.js
Normal file
164
src/api/routes/categoryattributevalue.js
Normal file
@@ -0,0 +1,164 @@
|
||||
import * as db from '../../db/categoryattributevalue.js';
|
||||
import { emit } from '../sse.js';
|
||||
|
||||
function requireSelectedCompany(req) {
|
||||
const companyId = req.user?.selectedCompanyId;
|
||||
if (companyId == null) {
|
||||
return { error: 'No company selected' };
|
||||
}
|
||||
return { companyId };
|
||||
}
|
||||
|
||||
function parsePositiveInt(value, field) {
|
||||
const id = Number(value);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
return { error: `${field} is required` };
|
||||
}
|
||||
return { id };
|
||||
}
|
||||
|
||||
function emitCategorySignal(req) {
|
||||
const companyId = req.user?.selectedCompanyId;
|
||||
if (companyId == null) return;
|
||||
emit('category', { companyId });
|
||||
}
|
||||
|
||||
function categoryAttributeValueErrorStatus(error) {
|
||||
if (error.message === 'No company selected') return 400;
|
||||
if (error.message === 'Not authorized') return 403;
|
||||
if (error.message === 'Company not found' || error.message === 'Category not found' || error.message === 'Parent not found') return 404;
|
||||
if (error.message?.startsWith('Attribute value not found')) return 404;
|
||||
if (error.message?.includes('exclusive')) return 400;
|
||||
if (error.message === 'Invalid attribute values array' || error.message === 'Invalid attributeValueId' || error.message === 'Duplicate attributeValueId') return 400;
|
||||
return 500;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers categoryattributevalue routes under `/category/:id/attributevalue`.
|
||||
* @param {import('express').Application} app
|
||||
* @param {string} [basePath='']
|
||||
*/
|
||||
export function register(app, basePath = '') {
|
||||
/**
|
||||
* @openapi
|
||||
* /category/{id}/attributevalue:
|
||||
* get:
|
||||
* tags: [Category]
|
||||
* summary: List category attribute values
|
||||
* description: Fetches all attribute values assigned to a category.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Category ID
|
||||
* responses:
|
||||
* 200:
|
||||
* description: List of attribute values assigned to this category
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* attributevalues:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/CategoryAttributeValue'
|
||||
* put:
|
||||
* tags: [Category]
|
||||
* summary: Bulk set category attribute values
|
||||
* description: Replaces all attribute values for a category. Enforces exclusive constraint (max one value per exclusive attribute).
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Category ID
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [attributevalues]
|
||||
* properties:
|
||||
* attributevalues:
|
||||
* type: array
|
||||
* description: Array of attribute value IDs (numbers) or objects with id or attributeValueId
|
||||
* items:
|
||||
* oneOf:
|
||||
* - type: integer
|
||||
* description: Attribute value ID
|
||||
* - type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* description: Attribute value ID
|
||||
* attributeValueId:
|
||||
* type: integer
|
||||
* description: Attribute value ID
|
||||
* sort:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated category attribute values
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* attributevalues:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/CategoryAttributeValue'
|
||||
*/
|
||||
app.get(`${basePath}/category/:id/attributevalue`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const idParsed = parsePositiveInt(req.params.id, 'categoryId');
|
||||
if (idParsed.error) {
|
||||
return res.status(400).json({ error: idParsed.error });
|
||||
}
|
||||
|
||||
try {
|
||||
const attributevalues = await db.listByCategoryId(req.user.id, idParsed.id);
|
||||
res.json({ attributevalues });
|
||||
} catch (error) {
|
||||
res.status(categoryAttributeValueErrorStatus(error)).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.put(`${basePath}/category/:id/attributevalue`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const idParsed = parsePositiveInt(req.params.id, 'categoryId');
|
||||
if (idParsed.error) {
|
||||
return res.status(400).json({ error: idParsed.error });
|
||||
}
|
||||
|
||||
const valuesInput = req.body?.attributevalues ?? req.body?.attributeValues ?? req.body?.attribute_values ?? req.body?.values ?? req.body;
|
||||
if (!Array.isArray(valuesInput)) {
|
||||
return res.status(400).json({ error: 'attributevalues array required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const attributevalues = await db.setByCategoryId(req.user.id, idParsed.id, valuesInput);
|
||||
emitCategorySignal(req);
|
||||
res.json({ attributevalues });
|
||||
} catch (error) {
|
||||
res.status(categoryAttributeValueErrorStatus(error)).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
}
|
||||
204
src/api/routes/categoryproperty.js
Normal file
204
src/api/routes/categoryproperty.js
Normal file
@@ -0,0 +1,204 @@
|
||||
import * as db from '../../db/categoryproperty.js';
|
||||
import { emit } from '../sse.js';
|
||||
|
||||
function requireSelectedCompany(req) {
|
||||
const companyId = req.user?.selectedCompanyId;
|
||||
if (companyId == null) {
|
||||
return { error: 'No company selected' };
|
||||
}
|
||||
return { companyId };
|
||||
}
|
||||
|
||||
function parsePositiveInt(value, field) {
|
||||
const id = Number(value);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
return { error: `${field} is required` };
|
||||
}
|
||||
return { id };
|
||||
}
|
||||
|
||||
function emitCategorySignal(req) {
|
||||
const companyId = req.user?.selectedCompanyId;
|
||||
if (companyId == null) return;
|
||||
emit('category', { companyId });
|
||||
}
|
||||
|
||||
function categoryPropertyErrorStatus(error) {
|
||||
if (error.message === 'No company selected') return 400;
|
||||
if (error.message === 'Not authorized') return 403;
|
||||
if (error.message === 'Company not found' || error.message === 'Category not found' || error.message === 'Parent not found') return 404;
|
||||
if (error.message?.startsWith('Property not found')) return 404;
|
||||
if (error.message?.includes('exclusive')) return 400;
|
||||
if (error.message === 'Invalid properties array' || error.message === 'Invalid propertyId' || error.message === 'Duplicate propertyId') return 400;
|
||||
return 500;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers categoryproperty routes under `/category/:id/property`.
|
||||
* @param {import('express').Application} app
|
||||
* @param {string} [basePath='']
|
||||
*/
|
||||
export function register(app, basePath = '') {
|
||||
/**
|
||||
* @openapi
|
||||
* /category/{id}/property:
|
||||
* get:
|
||||
* tags: [Category]
|
||||
* summary: List category properties
|
||||
* description: Fetches all free-form properties set on a category.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Category ID
|
||||
* responses:
|
||||
* 200:
|
||||
* description: List of properties for this category
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* properties:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/CategoryProperty'
|
||||
* put:
|
||||
* tags: [Category]
|
||||
* summary: Bulk set category properties
|
||||
* description: Replaces all properties for a category.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Category ID
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [properties]
|
||||
* properties:
|
||||
* properties:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* required: [propertyId, value]
|
||||
* properties:
|
||||
* propertyId:
|
||||
* type: integer
|
||||
* value:
|
||||
* type: string
|
||||
* sort:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated category properties
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* properties:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/CategoryProperty'
|
||||
*/
|
||||
app.get(`${basePath}/category/:id/property`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const idParsed = parsePositiveInt(req.params.id, 'categoryId');
|
||||
if (idParsed.error) {
|
||||
return res.status(400).json({ error: idParsed.error });
|
||||
}
|
||||
|
||||
try {
|
||||
const properties = await db.listByCategoryId(req.user.id, idParsed.id);
|
||||
res.json({ properties });
|
||||
} catch (error) {
|
||||
res.status(categoryPropertyErrorStatus(error)).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.put(`${basePath}/category/:id/property`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const idParsed = parsePositiveInt(req.params.id, 'categoryId');
|
||||
if (idParsed.error) {
|
||||
return res.status(400).json({ error: idParsed.error });
|
||||
}
|
||||
|
||||
const propertiesInput = req.body?.properties ?? req.body;
|
||||
if (!Array.isArray(propertiesInput)) {
|
||||
return res.status(400).json({ error: 'properties array required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const properties = await db.setByCategoryId(req.user.id, idParsed.id, propertiesInput);
|
||||
emitCategorySignal(req);
|
||||
res.json({ properties });
|
||||
} catch (error) {
|
||||
res.status(categoryPropertyErrorStatus(error)).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /category/{id}/property/{propertyId}:
|
||||
* delete:
|
||||
* tags: [Category]
|
||||
* summary: Delete category property
|
||||
* description: Removes a single property from a category.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* - in: path
|
||||
* name: propertyId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Deleted successfully
|
||||
*/
|
||||
app.delete(`${basePath}/category/:id/property/:propertyId`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const idParsed = parsePositiveInt(req.params.id, 'categoryId');
|
||||
if (idParsed.error) {
|
||||
return res.status(400).json({ error: idParsed.error });
|
||||
}
|
||||
|
||||
try {
|
||||
const propertyId = Number(req.params.propertyId);
|
||||
await db.remove(req.user.id, idParsed.id, propertyId);
|
||||
emitCategorySignal(req);
|
||||
res.json({ ok: true });
|
||||
} catch (error) {
|
||||
res.status(categoryPropertyErrorStatus(error)).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -16,6 +16,7 @@ function ledgerErrorStatus(error) {
|
||||
if (error.message === 'Invalid ledger entry') return 400;
|
||||
if (error.message === 'Invalid manifest article id') return 400;
|
||||
if (error.message === 'Invalid SKU') return 400;
|
||||
if (error.message?.includes('Stock tracking is disabled')) return 409;
|
||||
return 500;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ function stockErrorStatus(error) {
|
||||
if (error.message?.includes('Invalid amount')) return 400;
|
||||
if (error.message === 'No items to adjust') return 400;
|
||||
if (error.message?.includes('cannot have stock') || error.message?.includes('A father article cannot have') || error.message?.includes('father article') || error.message?.includes('Stückliste')) return 400;
|
||||
if (error.message?.includes('Stock tracking is disabled')) return 409;
|
||||
return 500;
|
||||
}
|
||||
|
||||
|
||||
11
src/db/categoryattributevalue.js
Normal file
11
src/db/categoryattributevalue.js
Normal file
@@ -0,0 +1,11 @@
|
||||
import { getStore } from './store.js';
|
||||
|
||||
export async function listByCategoryId(googleAuthId, categoryId) {
|
||||
const store = await getStore();
|
||||
return store.categoryattributevalue.listByCategoryId(googleAuthId, categoryId);
|
||||
}
|
||||
|
||||
export async function setByCategoryId(googleAuthId, categoryId, values) {
|
||||
const store = await getStore();
|
||||
return store.categoryattributevalue.setByCategoryId(googleAuthId, categoryId, values);
|
||||
}
|
||||
16
src/db/categoryproperty.js
Normal file
16
src/db/categoryproperty.js
Normal file
@@ -0,0 +1,16 @@
|
||||
import { getStore } from './store.js';
|
||||
|
||||
export async function listByCategoryId(googleAuthId, categoryId) {
|
||||
const store = await getStore();
|
||||
return store.categoryproperty.listByCategoryId(googleAuthId, categoryId);
|
||||
}
|
||||
|
||||
export async function setByCategoryId(googleAuthId, categoryId, properties) {
|
||||
const store = await getStore();
|
||||
return store.categoryproperty.setByCategoryId(googleAuthId, categoryId, properties);
|
||||
}
|
||||
|
||||
export async function remove(googleAuthId, categoryId, propertyId) {
|
||||
const store = await getStore();
|
||||
return store.categoryproperty.delete(googleAuthId, categoryId, propertyId);
|
||||
}
|
||||
@@ -95,3 +95,9 @@ export async function getProductList(params) {
|
||||
return store.posterminal.getProductList(params);
|
||||
}
|
||||
|
||||
export async function setMaxKnownTombstoneId(id, maxknowntombstoneid) {
|
||||
const store = await getStore();
|
||||
return store.posterminal.setMaxKnownTombstoneId(id, maxknowntombstoneid);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -39,9 +39,11 @@ const STORE_NAMESPACES = [
|
||||
'stock',
|
||||
'propertyname',
|
||||
'articleproperty',
|
||||
'categoryproperty',
|
||||
'attributename',
|
||||
'attributevalue',
|
||||
'articleattributevalue',
|
||||
'categoryattributevalue',
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user