u
This commit is contained in:
613
src/api/routes/article/attributes.js
Normal file
613
src/api/routes/article/attributes.js
Normal file
@@ -0,0 +1,613 @@
|
||||
import * as db from '../../../db/article.js';
|
||||
import {
|
||||
emitArticleSignal,
|
||||
parseSku,
|
||||
articleErrorStatus,
|
||||
} from './shared.js';
|
||||
|
||||
/**
|
||||
* Registers article attribute routes — prices, EANs, brand, weight, stock
|
||||
* tracking and category membership (requires auth middleware).
|
||||
* @param {import('express').Application} app - Express app
|
||||
* @param {string} [basePath=''] - Optional URL prefix for all routes in this module
|
||||
*/
|
||||
export function register(app, basePath = '') {
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/prices:
|
||||
* put:
|
||||
* tags: [Article]
|
||||
* summary: Replace POS prices by SKU (net > gross; price=net, tax=taxRate %)
|
||||
* description: |
|
||||
* Replace-all prices for the company POS customer group.
|
||||
* `net` takes precedence over `price` (legacy alias for net) and `gross`.
|
||||
* `tax` and `taxRate` both specify the tax rate percentage (e.g. 19 for 19%), not monetary tax.
|
||||
* When `gross` is provided, net price is computed as `gross / (1 + taxRate / 100)`.
|
||||
* Prices are strictly scoped to the company's designated POS customer group (customergroupId returned on GET).
|
||||
* Empty `prices` clears all POS prices. Returns the same shape as GET by SKU.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [article-<sku>]
|
||||
* x-markdown: article/set-prices.md
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [prices]
|
||||
* properties:
|
||||
* prices:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* net:
|
||||
* type: number
|
||||
* description: Net price (excl. VAT). Either `net`, `gross`, or legacy `price` is required.
|
||||
* gross:
|
||||
* type: number
|
||||
* description: Gross price (incl. VAT). Net is computed as `gross / (1 + taxRate / 100)`.
|
||||
* price:
|
||||
* type: number
|
||||
* description: Legacy alias for `net`.
|
||||
* taxRate:
|
||||
* type: number
|
||||
* description: Tax rate percentage (e.g. 19 for 19%, 7 for 7%, 0 for 0%).
|
||||
* tax:
|
||||
* type: number
|
||||
* description: Alias for `taxRate` percentage.
|
||||
* minmultiplier:
|
||||
* type: number
|
||||
* description: Defaults to 1; must be unique per request.
|
||||
* example:
|
||||
* prices:
|
||||
* - net: 10.5
|
||||
* taxRate: 19
|
||||
* - gross: 11.9
|
||||
* taxRate: 19
|
||||
* minmultiplier: 10
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated article detail
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* article:
|
||||
* $ref: '#/components/schemas/ArticleDetail'
|
||||
* 400:
|
||||
* description: Invalid prices, POS customer group required, or parent article cannot have prices
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region PUT /article/:sku/prices
|
||||
|
||||
app.put(`${basePath}/article/:sku/prices`, async (req, res) => {
|
||||
const skuParsed = parseSku(req.params.sku);
|
||||
if (skuParsed.error) {
|
||||
return res.status(400).json({ error: skuParsed.error });
|
||||
}
|
||||
|
||||
if (!Array.isArray(req.body?.prices)) {
|
||||
return res.status(400).json({ error: 'prices is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const article = await db.setPricesBySku(req.user.id, skuParsed.sku, req.body.prices);
|
||||
emitArticleSignal(req, skuParsed.sku);
|
||||
res.status(200).json({ article });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Set article prices failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/eans:
|
||||
* put:
|
||||
* tags: [Article]
|
||||
* summary: Replace article EANs by SKU
|
||||
* description: |
|
||||
* Replace-all EANs for the article. EANs must be non-empty unique strings;
|
||||
* empty array clears all EANs. Returns the same shape as GET by SKU.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [article-<sku>]
|
||||
* x-markdown: article/set-eans.md
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [eans]
|
||||
* properties:
|
||||
* eans:
|
||||
* type: array
|
||||
* items:
|
||||
* type: string
|
||||
* example:
|
||||
* eans: ["4001234567890"]
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated article detail
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* article:
|
||||
* $ref: '#/components/schemas/ArticleDetail'
|
||||
* 400:
|
||||
* description: Invalid eans
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 409:
|
||||
* description: EAN already in use
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region PUT /article/:sku/eans
|
||||
|
||||
app.put(`${basePath}/article/:sku/eans`, async (req, res) => {
|
||||
const skuParsed = parseSku(req.params.sku);
|
||||
if (skuParsed.error) {
|
||||
return res.status(400).json({ error: skuParsed.error });
|
||||
}
|
||||
|
||||
if (!Array.isArray(req.body?.eans)) {
|
||||
return res.status(400).json({ error: 'eans is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const article = await db.setEansBySku(req.user.id, skuParsed.sku, req.body.eans);
|
||||
emitArticleSignal(req, skuParsed.sku);
|
||||
res.status(200).json({ article });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Set article eans failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/brand:
|
||||
* put:
|
||||
* tags: [Article]
|
||||
* summary: Set or clear article brand by SKU (null to clear)
|
||||
* description: |
|
||||
* Sets the article's `brandId` (must belong to the article's company).
|
||||
* Pass `null` to clear the brand. Returns the same shape as GET by SKU.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [article-<sku>]
|
||||
* x-markdown: article/set-brand.md
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [brandId]
|
||||
* properties:
|
||||
* brandId:
|
||||
* type: integer
|
||||
* nullable: true
|
||||
* description: Brand ID to assign, or null to remove the brand
|
||||
* example:
|
||||
* brandId: 3
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated article detail
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* article:
|
||||
* $ref: '#/components/schemas/ArticleDetail'
|
||||
* 400:
|
||||
* description: Validation error
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article or brand not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region PUT /article/:sku/brand
|
||||
|
||||
app.put(`${basePath}/article/:sku/brand`, async (req, res) => {
|
||||
const skuParsed = parseSku(req.params.sku);
|
||||
if (skuParsed.error) {
|
||||
return res.status(400).json({ error: skuParsed.error });
|
||||
}
|
||||
|
||||
const brandId = req.body?.brandId ?? null;
|
||||
if (brandId !== null && (typeof brandId !== 'number' || !Number.isInteger(brandId) || brandId <= 0)) {
|
||||
return res.status(400).json({ error: 'Invalid brandId' });
|
||||
}
|
||||
|
||||
try {
|
||||
const article = await db.setBrandIdBySku(req.user.id, skuParsed.sku, brandId);
|
||||
emitArticleSignal(req, skuParsed.sku);
|
||||
res.status(200).json({ article });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Set article brand failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/weight:
|
||||
* put:
|
||||
* tags: [Article]
|
||||
* summary: Set article weight by SKU
|
||||
* description: |
|
||||
* Sets the article's `weight`. Must be finite and `>= 0`.
|
||||
* Returns the same shape as GET by SKU.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [article-<sku>]
|
||||
* x-markdown: article/set-weight.md
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [weight]
|
||||
* properties:
|
||||
* weight:
|
||||
* type: number
|
||||
* example:
|
||||
* weight: 1.5
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated article detail
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* article:
|
||||
* $ref: '#/components/schemas/ArticleDetail'
|
||||
* 400:
|
||||
* description: Invalid weight
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region PUT /article/:sku/weight
|
||||
|
||||
app.put(`${basePath}/article/:sku/weight`, async (req, res) => {
|
||||
const skuParsed = parseSku(req.params.sku);
|
||||
if (skuParsed.error) {
|
||||
return res.status(400).json({ error: skuParsed.error });
|
||||
}
|
||||
|
||||
const weight = req.body?.weight;
|
||||
|
||||
try {
|
||||
const article = await db.setWeightBySku(req.user.id, skuParsed.sku, weight);
|
||||
emitArticleSignal(req, skuParsed.sku);
|
||||
res.status(200).json({ article });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Set article weight failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/track_stock:
|
||||
* @openapi
|
||||
* /article/{sku}/track_stock:
|
||||
* put:
|
||||
* tags: [Article]
|
||||
* summary: Set article track_stock flag by SKU
|
||||
* description: |
|
||||
* Enables or disables inventory stock tracking for this article.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [article-<sku>]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Article SKU
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [track_stock]
|
||||
* properties:
|
||||
* track_stock:
|
||||
* type: boolean
|
||||
* description: Whether to track inventory stock for this article
|
||||
* example:
|
||||
* track_stock: true
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated article detail
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* article:
|
||||
* $ref: '#/components/schemas/ArticleDetail'
|
||||
* 400:
|
||||
* description: Invalid track_stock
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region PUT /article/:sku/track_stock
|
||||
|
||||
async function handleSetTrackStock(req, res) {
|
||||
const skuParsed = parseSku(req.params.sku);
|
||||
if (skuParsed.error) {
|
||||
return res.status(400).json({ error: skuParsed.error });
|
||||
}
|
||||
|
||||
const raw = req.body?.track_stock;
|
||||
if (raw === undefined || (typeof raw !== 'boolean' && raw !== 0 && raw !== 1)) {
|
||||
return res.status(400).json({ error: 'Invalid track_stock' });
|
||||
}
|
||||
|
||||
try {
|
||||
const article = await db.setTrackStockBySku(req.user.id, skuParsed.sku, Boolean(raw));
|
||||
emitArticleSignal(req, skuParsed.sku);
|
||||
res.status(200).json({ article });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Set article track_stock failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
app.put(`${basePath}/article/:sku/track_stock`, handleSetTrackStock);
|
||||
app.put(`${basePath}/article/:sku/track-stock`, handleSetTrackStock);
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/categories:
|
||||
* put:
|
||||
* tags: [Article]
|
||||
* summary: Replace article categories by SKU
|
||||
* description: |
|
||||
* Replace-all the article's category list. Each category must belong to
|
||||
* the article's company; ids must be unique. The article must belong to
|
||||
* at least one category (empty array is rejected). Returns the same shape as GET by SKU.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [article-<sku>]
|
||||
* x-markdown: article/set-categories.md
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [categoryIds]
|
||||
* properties:
|
||||
* categoryIds:
|
||||
* type: array
|
||||
* minItems: 1
|
||||
* items:
|
||||
* type: integer
|
||||
* example:
|
||||
* categoryIds: [4, 7]
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated article detail
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* article:
|
||||
* $ref: '#/components/schemas/ArticleDetail'
|
||||
* 400:
|
||||
* description: Invalid categoryIds or empty array
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region PUT /article/:sku/categories
|
||||
|
||||
app.put(`${basePath}/article/:sku/categories`, async (req, res) => {
|
||||
const skuParsed = parseSku(req.params.sku);
|
||||
if (skuParsed.error) {
|
||||
return res.status(400).json({ error: skuParsed.error });
|
||||
}
|
||||
|
||||
if (!Array.isArray(req.body?.categoryIds)) {
|
||||
return res.status(400).json({ error: 'categoryIds is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const article = await db.setCategoryIdsBySku(
|
||||
req.user.id,
|
||||
skuParsed.sku,
|
||||
req.body.categoryIds,
|
||||
);
|
||||
emitArticleSignal(req, skuParsed.sku);
|
||||
res.status(200).json({ article });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Set article categories failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
|
||||
// #endregion
|
||||
}
|
||||
});
|
||||
}
|
||||
643
src/api/routes/article/crud.js
Normal file
643
src/api/routes/article/crud.js
Normal file
@@ -0,0 +1,643 @@
|
||||
import JSZip from 'jszip';
|
||||
import * as db from '../../../db/article.js';
|
||||
import * as picDb from '../../../db/pic.js';
|
||||
import { buildArtikelCsv, toWindows1252 } from '../../../util/artikelCsv.js';
|
||||
import {
|
||||
emitArticlesSignal,
|
||||
emitArticleSignal,
|
||||
parsePositiveInt,
|
||||
parseSku,
|
||||
articleErrorStatus,
|
||||
} from './shared.js';
|
||||
|
||||
/**
|
||||
* Registers article CRUD routes (requires auth middleware).
|
||||
*
|
||||
* `GET /article/export.zip` is registered before `GET /article/:sku` so the
|
||||
* literal path is not swallowed by the `:sku` parameter route.
|
||||
*
|
||||
* @param {import('express').Application} app - Express app
|
||||
* @param {string} [basePath=''] - Optional URL prefix for all routes in this module
|
||||
*/
|
||||
export function register(app, basePath = '') {
|
||||
/**
|
||||
* @openapi
|
||||
* /article:
|
||||
* post:
|
||||
* tags: [Article]
|
||||
* summary: Create article in category
|
||||
* description: Creates an article under an authorized category (`parentId`).
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [articles]
|
||||
* x-markdown: article/create.md
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [categoryId, name]
|
||||
* properties:
|
||||
* categoryId:
|
||||
* type: integer
|
||||
* description: Category ID under which to create the article
|
||||
* name:
|
||||
* type: string
|
||||
* desc:
|
||||
* type: string
|
||||
* description: Article description text/HTML
|
||||
* seo:
|
||||
* type: string
|
||||
* description: SEO text
|
||||
* track_stock:
|
||||
* type: boolean
|
||||
* description: Whether to track inventory stock (defaults to true)
|
||||
* example:
|
||||
* categoryId: 10
|
||||
* name: New article
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Created
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* article:
|
||||
* $ref: '#/components/schemas/ArticleSummary'
|
||||
* 400:
|
||||
* description: Validation error
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized for parent category
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Parent not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 409:
|
||||
* description: SKU already exists
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region POST /article
|
||||
|
||||
app.post(`${basePath}/article`, async (req, res) => {
|
||||
const rawParent = req.body?.categoryId;
|
||||
if (rawParent === undefined || rawParent === null) {
|
||||
return res.status(400).json({ error: 'categoryId is required' });
|
||||
}
|
||||
if (typeof rawParent !== 'number' || !Number.isInteger(rawParent) || rawParent <= 0) {
|
||||
return res.status(400).json({ error: 'categoryId must be an integer' });
|
||||
}
|
||||
const parentId = rawParent;
|
||||
|
||||
const name = typeof req.body?.name === 'string' ? req.body.name.trim() : '';
|
||||
if (!name) {
|
||||
return res.status(400).json({ error: 'name is required' });
|
||||
}
|
||||
|
||||
const rawTrack = req.body?.track_stock;
|
||||
if (rawTrack !== undefined && typeof rawTrack !== 'boolean' && rawTrack !== 0 && rawTrack !== 1) {
|
||||
return res.status(400).json({ error: 'Invalid track_stock' });
|
||||
}
|
||||
const track_stock = rawTrack !== undefined ? Boolean(rawTrack) : true;
|
||||
const customSku = typeof req.body?.sku === 'string' && req.body.sku.trim() ? req.body.sku.trim() : undefined;
|
||||
|
||||
try {
|
||||
const desc = req.body?.desc;
|
||||
const created = await db.createUnderParent({
|
||||
googleAuthId: req.user.id,
|
||||
parentId,
|
||||
name,
|
||||
track_stock,
|
||||
sku: customSku,
|
||||
desc: desc !== undefined ? desc : undefined,
|
||||
seo: req.body?.seo !== undefined ? req.body.seo : undefined,
|
||||
});
|
||||
emitArticlesSignal(req);
|
||||
const article = {
|
||||
...created,
|
||||
categoryId: created.parentId,
|
||||
};
|
||||
res.status(201).json({ article });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Create article failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/export.zip:
|
||||
* get:
|
||||
* tags: [Article]
|
||||
* summary: Export articles as ZIP
|
||||
* description: |
|
||||
* Builds an `artikel.zip` for the authenticated user's selected company.
|
||||
* `categoryId` (optional) restricts the export to that category and below;
|
||||
* it must be reachable via the company's root category. Defaults to the
|
||||
* whole company root tree.
|
||||
* The ZIP contains `artikel.csv` (semicolon-separated, Windows-1252)
|
||||
* plus one AVIF entry per article image, named `<fullHash>.avif`
|
||||
* (content-addressed, so shared hashes are deduplicated).
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: categoryId
|
||||
* required: false
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Restrict export to this category subtree
|
||||
* responses:
|
||||
* 200:
|
||||
* description: ZIP archive
|
||||
* content:
|
||||
* application/zip:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* 400:
|
||||
* description: No company selected
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Company not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region GET /article/export.zip
|
||||
|
||||
app.get(`${basePath}/article/export.zip`, async (req, res) => {
|
||||
const companyId = req.user.selectedCompanyId;
|
||||
if (companyId == null) {
|
||||
return res.status(400).json({ error: 'No company selected' });
|
||||
}
|
||||
|
||||
let categoryId = null;
|
||||
if (req.query.categoryId != null && req.query.categoryId !== '') {
|
||||
const parsed = parsePositiveInt(req.query.categoryId, 'categoryId');
|
||||
if (parsed.error) {
|
||||
return res.status(400).json({ error: parsed.error });
|
||||
}
|
||||
categoryId = parsed.id;
|
||||
}
|
||||
|
||||
try {
|
||||
const rows = await db.listExport(req.user.id, categoryId);
|
||||
|
||||
const csv = buildArtikelCsv(rows);
|
||||
|
||||
const zip = new JSZip();
|
||||
zip.file('artikel.csv', toWindows1252(csv));
|
||||
|
||||
const seen = new Set();
|
||||
for (const row of rows) {
|
||||
for (const fullHash of row.fullHashes ?? []) {
|
||||
if (!fullHash || seen.has(fullHash)) continue;
|
||||
seen.add(fullHash);
|
||||
try {
|
||||
const { buffer } = await picDb.getImageByHash(req.user.id, fullHash);
|
||||
zip.file(`${fullHash}.avif`, buffer);
|
||||
} catch (error) {
|
||||
// Skip images this user cannot access; CSV already carries the hash.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const content = await zip.generateAsync({ type: 'nodebuffer' });
|
||||
res.setHeader('Content-Type', 'application/zip');
|
||||
res.setHeader('Content-Disposition', 'attachment; filename="artikel.zip"');
|
||||
res.status(200).send(content);
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Export articles failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}:
|
||||
* @openapi
|
||||
* /article/{sku}:
|
||||
* get:
|
||||
* tags: [Article]
|
||||
* summary: Get article by SKU
|
||||
* description: Returns article detail by SKU if the user may access its category.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-markdown: article/get.md
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Article SKU
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Article detail
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* article:
|
||||
* $ref: '#/components/schemas/ArticleDetail'
|
||||
* 400:
|
||||
* description: Missing sku
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* patch:
|
||||
* tags: [Article]
|
||||
* summary: Update article by SKU
|
||||
* description: |
|
||||
* Patches article fields. At least one of `name`, `unitamount`, `unitSi` required.
|
||||
* `unitSi` must already exist for the company. Returns the same detail shape as GET.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [articles]
|
||||
* x-markdown: article/update.md
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Article SKU
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* name:
|
||||
* type: string
|
||||
* desc:
|
||||
* type: string
|
||||
* description: Article description text/HTML
|
||||
* seo:
|
||||
* type: string
|
||||
* description: SEO text
|
||||
* unitamount:
|
||||
* type: number
|
||||
* description: Must be finite and `> 0`
|
||||
* unitSi:
|
||||
* type: string
|
||||
* description: Existing company unit `si`
|
||||
* track_stock:
|
||||
* type: boolean
|
||||
* description: Whether to track inventory stock
|
||||
* example:
|
||||
* unitamount: 0.24
|
||||
* unitSi: l
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated article detail
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* article:
|
||||
* $ref: '#/components/schemas/ArticleDetail'
|
||||
* 400:
|
||||
* description: Validation error (Name required / Invalid unitamount)
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article or unit not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* delete:
|
||||
* tags: [Article]
|
||||
* summary: Delete article by SKU
|
||||
* description: |
|
||||
* Deletes the article when it has no child articles. Cascades related rows;
|
||||
* nulls `manifestarticle.article_id` and appends a delete comment.
|
||||
* Auth like GET by SKU.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [articles]
|
||||
* x-markdown: article/delete.md
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Article SKU
|
||||
* - in: query
|
||||
* name: cascade
|
||||
* schema:
|
||||
* type: boolean
|
||||
* description: If true, recursively deletes all descendant child articles in the subtree
|
||||
* responses:
|
||||
* 204:
|
||||
* description: Deleted
|
||||
* 400:
|
||||
* description: Article has children
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region GET /article/:sku
|
||||
|
||||
app.get(`${basePath}/article/:sku`, async (req, res) => {
|
||||
const sku = typeof req.params.sku === 'string' ? req.params.sku.trim() : '';
|
||||
if (!sku) {
|
||||
return res.status(400).json({ error: 'sku is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const { article } = await db.getBySku(req.user.id, decodeURIComponent(sku));
|
||||
res.status(200).json({ article });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Get article by sku failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/history:
|
||||
* get:
|
||||
* tags: [Article]
|
||||
* summary: Get article history by SKU
|
||||
* description: |
|
||||
* Returns `articlehistory` rows for the article, newest first (`date` DESC, `id` DESC).
|
||||
* Auth like GET by SKU.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-markdown: article/history.md
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Article SKU
|
||||
* - in: query
|
||||
* name: limit
|
||||
* required: false
|
||||
* schema:
|
||||
* type: integer
|
||||
* minimum: 1
|
||||
* maximum: 1000
|
||||
* description: Maximum number of entries to return (newest first). Omit for all entries.
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Article history (newest first)
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [history, truncated]
|
||||
* properties:
|
||||
* history:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/ArticleHistoryEntry'
|
||||
* truncated:
|
||||
* type: boolean
|
||||
* description: True when a limit was applied and the result set was exactly that size (more entries may exist).
|
||||
* example:
|
||||
* history:
|
||||
* - id: 42
|
||||
* date: '2026-08-05T07:15:00.000Z'
|
||||
* text: "Name geändert von \"Tee\" auf \"Grüner Tee\"\nEinheit geändert von \"500g\" auf \"1kg\""
|
||||
* - id: 41
|
||||
* date: '2026-08-01T09:00:00.000Z'
|
||||
* text: 'Name geändert von "" auf "Tee"'
|
||||
* 400:
|
||||
* description: Missing sku
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region GET /article/:sku/history
|
||||
|
||||
app.get(`${basePath}/article/:sku/history`, async (req, res) => {
|
||||
const sku = typeof req.params.sku === 'string' ? req.params.sku.trim() : '';
|
||||
if (!sku) {
|
||||
return res.status(400).json({ error: 'sku is required' });
|
||||
}
|
||||
|
||||
const rawLimit = req.query.limit;
|
||||
let limit = null;
|
||||
if (rawLimit !== undefined) {
|
||||
limit = parseInt(rawLimit, 10);
|
||||
if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {
|
||||
return res.status(400).json({ error: 'limit must be an integer between 1 and 1000' });
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const history = await db.getHistoryBySku(req.user.id, decodeURIComponent(sku), limit != null ? { limit } : undefined);
|
||||
const truncated = limit != null && history.length === limit;
|
||||
res.status(200).json({ history, truncated });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Get article history by sku failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
// #region PATCH /article/:sku
|
||||
|
||||
app.patch(`${basePath}/article/:sku`, async (req, res) => {
|
||||
const sku = typeof req.params.sku === 'string' ? req.params.sku.trim() : '';
|
||||
if (!sku) {
|
||||
return res.status(400).json({ error: 'sku is required' });
|
||||
}
|
||||
|
||||
const body = req.body ?? {};
|
||||
const patch = {};
|
||||
if (Object.prototype.hasOwnProperty.call(body, 'name')) {
|
||||
patch.name = body.name;
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(body, 'unitamount')) {
|
||||
patch.unitamount = body.unitamount;
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(body, 'unitSi')) {
|
||||
patch.unitSi = body.unitSi;
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(body, 'track_stock')) {
|
||||
patch.track_stock = body.track_stock;
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(body, 'desc')) {
|
||||
patch.desc = body.desc;
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(body, 'seo')) {
|
||||
patch.seo = body.seo;
|
||||
}
|
||||
|
||||
if (
|
||||
!('name' in patch) &&
|
||||
!('unitamount' in patch) &&
|
||||
!('unitSi' in patch) &&
|
||||
!('track_stock' in patch) &&
|
||||
!('desc' in patch) &&
|
||||
!('seo' in patch)
|
||||
) {
|
||||
return res.status(400).json({ error: 'name, unitamount, unitSi, track_stock, desc, or seo is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const decodedSku = decodeURIComponent(sku);
|
||||
const article = await db.updateBySku(req.user.id, decodedSku, patch);
|
||||
emitArticlesSignal(req);
|
||||
emitArticleSignal(req, decodedSku);
|
||||
res.status(200).json({ article });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Update article by sku failed:', error);
|
||||
// #endregion
|
||||
|
||||
// #region DELETE /article/:sku
|
||||
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete(`${basePath}/article/:sku`, async (req, res) => {
|
||||
const parsed = parseSku(req.params.sku);
|
||||
if (parsed.error) {
|
||||
return res.status(400).json({ error: parsed.error });
|
||||
}
|
||||
|
||||
const cascade = req.query.cascade === 'true';
|
||||
|
||||
try {
|
||||
await db.remove(req.user.id, parsed.sku, { cascade });
|
||||
emitArticlesSignal(req);
|
||||
res.sendStatus(204);
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
|
||||
// #endregion
|
||||
if (status === 500) console.error('Delete article failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
}
|
||||
465
src/api/routes/article/media.js
Normal file
465
src/api/routes/article/media.js
Normal file
@@ -0,0 +1,465 @@
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import express from 'express';
|
||||
import { renderLabel } from 'react-canvas-label-editor';
|
||||
import * as db from '../../../db/article.js';
|
||||
import * as printerDb from '../../../db/printer.js';
|
||||
import * as labeltemplateDb from '../../../db/labeltemplate.js';
|
||||
import {
|
||||
AVIF_BODY_LIMIT,
|
||||
emitArticleSignal,
|
||||
parseSku,
|
||||
parseFullHash,
|
||||
articleErrorStatus,
|
||||
interpolateString,
|
||||
} from './shared.js';
|
||||
|
||||
/**
|
||||
* Registers article image and label-printing routes (requires auth middleware).
|
||||
* @param {import('express').Application} app - Express app
|
||||
* @param {string} [basePath=''] - Optional URL prefix for all routes in this module
|
||||
*/
|
||||
export function register(app, basePath = '') {
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/image:
|
||||
* post:
|
||||
* tags: [Article]
|
||||
* summary: Add article image
|
||||
* description: |
|
||||
* Accepts a full-size AVIF body (`Content-Type: image/avif`) or WebP body (`Content-Type: image/webp`).
|
||||
* WebP images are automatically converted to AVIF on the server.
|
||||
* Full: stored as-is when already AVIF and ≤1000×1000; otherwise scaled to max 1000×1000.
|
||||
* Thumb always scaled to max 200×200. Stores hash/thumbhash, links `articlepic`.
|
||||
* Auth like GET by SKU.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [article-<sku>]
|
||||
* x-markdown: article/add-image.md
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Article SKU
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* image/avif:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* image/webp:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Image stored and linked
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* image:
|
||||
* $ref: '#/components/schemas/ArticleImage'
|
||||
* 400:
|
||||
* description: Missing body or invalid image
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region POST /article/:sku/image
|
||||
|
||||
app.post(
|
||||
`${basePath}/article/:sku/image`,
|
||||
express.raw({ type: ['image/avif', 'image/webp', 'application/octet-stream'], limit: AVIF_BODY_LIMIT }),
|
||||
async (req, res) => {
|
||||
const sku = typeof req.params.sku === 'string' ? req.params.sku.trim() : '';
|
||||
if (!sku) {
|
||||
return res.status(400).json({ error: 'sku is required' });
|
||||
}
|
||||
|
||||
const imageBuffer = Buffer.isBuffer(req.body) ? req.body : null;
|
||||
if (!imageBuffer?.length) {
|
||||
return res.status(400).json({ error: 'AVIF or WebP image body is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const decodedSku = decodeURIComponent(sku);
|
||||
const image = await db.addImage(req.user.id, decodedSku, imageBuffer);
|
||||
emitArticleSignal(req, decodedSku);
|
||||
res.status(201).json({ image });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Add article image failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/image/{fullHash}:
|
||||
* delete:
|
||||
* tags: [Article]
|
||||
* summary: Delete article image
|
||||
* description: Removes `articlepic` and the `pic` row for this article (`fullHash`). Auth like GET by SKU.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [article-<sku>]
|
||||
* x-markdown: article/delete-image.md
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: path
|
||||
* name: fullHash
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* pattern: '^[a-zA-Z0-9]{8}$'
|
||||
* responses:
|
||||
* 204:
|
||||
* description: Deleted
|
||||
* 400:
|
||||
* description: Invalid hash
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article or image not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region DELETE /article/:sku/image/:fullHash
|
||||
|
||||
app.delete(`${basePath}/article/:sku/image/:fullHash`, async (req, res) => {
|
||||
const skuParsed = parseSku(req.params.sku);
|
||||
if (skuParsed.error) {
|
||||
return res.status(400).json({ error: skuParsed.error });
|
||||
}
|
||||
const hashParsed = parseFullHash(req.params.fullHash);
|
||||
if (hashParsed.error) {
|
||||
return res.status(400).json({ error: hashParsed.error });
|
||||
}
|
||||
|
||||
try {
|
||||
await db.deleteImage(req.user.id, skuParsed.sku, hashParsed.fullHash);
|
||||
emitArticleSignal(req, skuParsed.sku);
|
||||
res.sendStatus(204);
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Delete article image failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/images/order:
|
||||
* put:
|
||||
* tags: [Article]
|
||||
* summary: Reorder article images
|
||||
* description: |
|
||||
* Sets `articlepic.sort` to `0..n-1` in the given order.
|
||||
* `fullHashes` must list every image of the article exactly once.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [article-<sku>]
|
||||
* x-markdown: article/order-images.md
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [fullHashes]
|
||||
* properties:
|
||||
* fullHashes:
|
||||
* type: array
|
||||
* items:
|
||||
* type: string
|
||||
* pattern: '^[a-zA-Z0-9]{8}$'
|
||||
* example:
|
||||
* fullHashes:
|
||||
* - "aB1cD2eF"
|
||||
* - "gH3iJ4kL"
|
||||
* responses:
|
||||
* 200:
|
||||
* description: New order
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* fullHashes:
|
||||
* type: array
|
||||
* items:
|
||||
* type: string
|
||||
* 400:
|
||||
* description: Invalid image order
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region PUT /article/:sku/images/order
|
||||
|
||||
app.put(`${basePath}/article/:sku/images/order`, async (req, res) => {
|
||||
const skuParsed = parseSku(req.params.sku);
|
||||
if (skuParsed.error) {
|
||||
return res.status(400).json({ error: skuParsed.error });
|
||||
}
|
||||
|
||||
const rawHashes = req.body?.fullHashes;
|
||||
if (!Array.isArray(rawHashes)) {
|
||||
return res.status(400).json({ error: 'fullHashes is required' });
|
||||
}
|
||||
|
||||
const fullHashes = [];
|
||||
for (const value of rawHashes) {
|
||||
const parsed = parseFullHash(value);
|
||||
if (parsed.error) {
|
||||
return res.status(400).json({ error: parsed.error });
|
||||
}
|
||||
fullHashes.push(parsed.fullHash);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await db.orderImages(req.user.id, skuParsed.sku, { fullHashes });
|
||||
emitArticleSignal(req, skuParsed.sku);
|
||||
res.status(200).json(result);
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Order article images failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/print:
|
||||
* post:
|
||||
* tags: [Article]
|
||||
* summary: Print article label
|
||||
* description: Prints a label for the article using a label template.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [templateId, printerId, quantity]
|
||||
* properties:
|
||||
* templateId:
|
||||
* type: integer
|
||||
* printerId:
|
||||
* type: integer
|
||||
* quantity:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Print job dispatched
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [success]
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* 400:
|
||||
* description: Invalid parameters
|
||||
* 404:
|
||||
* description: Printer, Template or Article not found
|
||||
* 500:
|
||||
* description: Server error
|
||||
*/
|
||||
// #region POST /article/:sku/print
|
||||
|
||||
app.post(`${basePath}/article/:sku/print`, express.json(), async (req, res) => {
|
||||
const companyId = req.user?.selectedCompanyId;
|
||||
if (companyId == null) {
|
||||
return res.status(400).json({ error: 'No company selected' });
|
||||
}
|
||||
|
||||
const { sku: parsedSku, error: skuError } = parseSku(req.params.sku);
|
||||
if (skuError) return res.status(400).json({ error: skuError });
|
||||
const sku = parsedSku;
|
||||
|
||||
const { templateId, printerId, quantity } = req.body ?? {};
|
||||
|
||||
if (templateId === undefined || templateId === null) {
|
||||
return res.status(400).json({ error: 'templateId is required' });
|
||||
}
|
||||
if (typeof templateId !== 'number' || !Number.isInteger(templateId) || templateId <= 0) {
|
||||
return res.status(400).json({ error: 'templateId must be an integer' });
|
||||
}
|
||||
|
||||
if (printerId === undefined || printerId === null) {
|
||||
return res.status(400).json({ error: 'printerId is required' });
|
||||
}
|
||||
if (typeof printerId !== 'number' || !Number.isInteger(printerId) || printerId <= 0) {
|
||||
return res.status(400).json({ error: 'printerId must be an integer' });
|
||||
}
|
||||
|
||||
if (quantity === undefined || quantity === null) {
|
||||
return res.status(400).json({ error: 'quantity is required' });
|
||||
}
|
||||
if (typeof quantity !== 'number' || !Number.isInteger(quantity) || quantity <= 0) {
|
||||
return res.status(400).json({ error: 'quantity must be an integer' });
|
||||
}
|
||||
|
||||
const parsedPrinterId = { id: printerId };
|
||||
const parsedTemplateId = { id: templateId };
|
||||
const parsedQuantity = { id: quantity };
|
||||
|
||||
try {
|
||||
const printer = await printerDb.getById(req.user.id, parsedPrinterId.id);
|
||||
if (!printer || printer.company_id !== companyId) {
|
||||
return res.status(404).json({ error: 'Printer not found' });
|
||||
}
|
||||
if (printer.type !== 'zpl') {
|
||||
return res.status(400).json({ error: 'Printer is not a ZPL printer' });
|
||||
}
|
||||
|
||||
const template = await labeltemplateDb.getById(req.user.id, parsedTemplateId.id);
|
||||
if (!template || template.company_id !== companyId) {
|
||||
return res.status(404).json({ error: 'Label template not found' });
|
||||
}
|
||||
|
||||
let article;
|
||||
try {
|
||||
const result = await db.getBySku(req.user.id, sku);
|
||||
article = result?.article;
|
||||
} catch (err) {
|
||||
const status = articleErrorStatus(err);
|
||||
if (status === 500) console.error('Get article by sku failed for print:', err);
|
||||
return res.status(status).json({ error: err.message });
|
||||
}
|
||||
if (!article) {
|
||||
return res.status(404).json({ error: 'Article not found' });
|
||||
}
|
||||
|
||||
// Extract and interpolate canvas objects
|
||||
const content = template.content;
|
||||
const objects = Array.isArray(content?.objects)
|
||||
? content.objects
|
||||
: Array.isArray(content)
|
||||
? content
|
||||
: [];
|
||||
|
||||
const interpolatedObjects = objects.map(obj => {
|
||||
const cloned = { ...obj };
|
||||
if (typeof cloned.text === 'string') {
|
||||
cloned.text = interpolateString(cloned.text, article);
|
||||
}
|
||||
if (typeof cloned.code === 'string') {
|
||||
cloned.code = interpolateString(cloned.code, article);
|
||||
}
|
||||
return cloned;
|
||||
});
|
||||
|
||||
const printPayload = await renderLabel({
|
||||
width: template.width,
|
||||
height: template.height,
|
||||
objects: interpolatedObjects,
|
||||
});
|
||||
|
||||
// Mock network dispatch
|
||||
const printDir = path.join(process.cwd(), 'print_spool', `${printer.address}_${printer.type}`);
|
||||
await fs.mkdir(printDir, { recursive: true });
|
||||
|
||||
for (let i = 0; i < parsedQuantity.id; i++) {
|
||||
const timestamp = Date.now();
|
||||
const filename = parsedQuantity.id > 1 ? `${timestamp}_${i + 1}.png` : `${timestamp}.png`;
|
||||
const filePath = path.join(printDir, filename);
|
||||
await fs.writeFile(filePath, printPayload);
|
||||
}
|
||||
|
||||
res.status(200).json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('Print article label failed:', error);
|
||||
res.status(500).json({ error: error.message });
|
||||
|
||||
// #endregion
|
||||
}
|
||||
});
|
||||
}
|
||||
132
src/api/routes/article/shared.js
Normal file
132
src/api/routes/article/shared.js
Normal file
@@ -0,0 +1,132 @@
|
||||
import { emit } from '../../sse.js';
|
||||
|
||||
// #region Helpers
|
||||
|
||||
export const AVIF_BODY_LIMIT = '20mb';
|
||||
export const FULL_HASH_RE = /^[a-zA-Z0-9]{8}$/;
|
||||
|
||||
/** Notify SSE subscribers after create / rename-ish list-level article changes. */
|
||||
export function emitArticlesSignal(req) {
|
||||
const companyId = req.user?.selectedCompanyId;
|
||||
if (companyId == null) return;
|
||||
emit('articles', { companyId });
|
||||
}
|
||||
|
||||
/** Notify SSE subscribers of a single-article detail change. */
|
||||
export function emitArticleSignal(req, sku) {
|
||||
const companyId = req.user?.selectedCompanyId;
|
||||
if (companyId == null) return;
|
||||
emit(`article-${sku}`, { companyId });
|
||||
}
|
||||
|
||||
export function parsePositiveInt(value, field) {
|
||||
const id = Number(value);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
return { error: `${field} is required` };
|
||||
}
|
||||
return { id };
|
||||
}
|
||||
|
||||
export function parseSku(value) {
|
||||
const sku = typeof value === 'string' ? value.trim() : '';
|
||||
if (!sku) return { error: 'sku is required' };
|
||||
return { sku: decodeURIComponent(sku) };
|
||||
}
|
||||
|
||||
export function parseFullHash(value) {
|
||||
const fullHash = typeof value === 'string' ? value.trim() : '';
|
||||
if (!FULL_HASH_RE.test(fullHash)) {
|
||||
return { error: 'fullHash must be an 8-char alphanumeric string' };
|
||||
}
|
||||
return { fullHash };
|
||||
}
|
||||
|
||||
export function articleErrorStatus(error) {
|
||||
if (error.message === 'No company selected') return 400;
|
||||
if (error.message === 'Unsupported image format' || error.message?.includes('unsupported image format')) return 400;
|
||||
if (error.message === 'Not authorized') return 403;
|
||||
if (error.message === 'Parent not found') return 404;
|
||||
if (
|
||||
error.message === 'Article not found' ||
|
||||
error.message?.startsWith('Article not found') ||
|
||||
error.message?.startsWith('Component article not found') ||
|
||||
error.message?.startsWith('Option article not found')
|
||||
) return 404;
|
||||
if (error.message === 'Image not found') return 404;
|
||||
if (error.message === 'Name required') return 400;
|
||||
if (error.message === 'Invalid image order') return 400;
|
||||
if (error.message === 'Article has children') return 400;
|
||||
if (error.message === 'Invalid prices') return 400;
|
||||
if (error.message === 'POS customer group required') return 400;
|
||||
if (error.message === 'Invalid unitamount') return 400;
|
||||
if (error.message === 'Unit not found') return 404;
|
||||
if (error.message === 'Invalid eans') return 400;
|
||||
if (error.message === 'EAN already in use' || error.message === 'EAN already assigned') return 409;
|
||||
if (error.message?.includes('UNIQUE constraint') || error.message?.includes('duplicate key') || error.message?.includes('Unique constraint') || error.message?.includes('already exists')) return 409;
|
||||
if (error.message === 'Company not found') return 404;
|
||||
if (error.message === 'Brand not found') return 404;
|
||||
if (error.message === 'Invalid brandId') return 400;
|
||||
if (error.message === 'Invalid attributeValueId') return 400;
|
||||
if (error.message === 'Invalid weight') return 400;
|
||||
if (error.message === 'Invalid track_stock') return 400;
|
||||
if (error.message === 'Invalid categoryIds' || error.message === 'Article must have at least one category') return 400;
|
||||
if (error.message === 'Attribute name not found') return 404;
|
||||
if (error.message === 'attributeNameId is required to become a parent article') return 400;
|
||||
if (error.message?.includes('already used by an ancestor parent')) return 400;
|
||||
// Variant-parent preconditions: a parent article may not carry stock,
|
||||
// suppliers, a Stückliste or options. These are user-correctable 409s,
|
||||
// not server faults — without these the route returns a bare 500.
|
||||
if (error.message === 'An article with existing stock cannot become a parent article') return 409;
|
||||
if (error.message === 'An article with assigned suppliers cannot become a parent article') return 409;
|
||||
if (error.message === 'A Stückliste article cannot become a parent') return 409;
|
||||
if (error.message === 'An article with options cannot become a parent') return 409;
|
||||
if (error.message?.includes('cannot have attribute values for its variant attribute')) return 400;
|
||||
if (error.message?.includes('A parent article cannot have') || error.message?.includes('parent article cannot have')) return 400;
|
||||
if (error.message === 'Cannot disable parent mode on an article that still has children') return 400;
|
||||
if (error.message === 'Article is not a parent article') return 400;
|
||||
if (error.message === 'Attribute value is required for child article' || error.message === 'Attribute value is required') return 400;
|
||||
if (error.message === 'Attribute value not found or does not match parent attribute') return 400;
|
||||
if (error.message === 'Child article does not belong to this parent') return 400;
|
||||
if (error.message === 'Article already belongs to another parent') return 409;
|
||||
if (error.message?.includes('sku is not allowed when creating a child article')) return 400;
|
||||
if (error.message === 'sku is required' || error.message?.includes('sku is required')) return 400;
|
||||
if (error.message === 'Article is already connected to a parent article') return 400;
|
||||
if (error.message === 'An article cannot be a child of itself') return 400;
|
||||
if (error.message === 'Variant with this attribute value already exists') return 400;
|
||||
if (error.message?.startsWith('Child article') && error.message?.includes('already exists')) return 400;
|
||||
if (error.message?.toLowerCase().includes('duplicate variant')) return 400;
|
||||
if (error.message === 'Parent article not found') return 404;
|
||||
if (
|
||||
error.message?.includes('Stückliste') ||
|
||||
error.message?.toLowerCase().includes('option') ||
|
||||
error.message?.includes('Item at index') ||
|
||||
error.message?.includes('Option at index') ||
|
||||
error.message?.includes('Invalid items array') ||
|
||||
error.message?.includes('Invalid options array') ||
|
||||
error.message?.includes('Invalid count') ||
|
||||
error.message?.includes('Invalid sort') ||
|
||||
error.message?.includes('Invalid mandated') ||
|
||||
error.message?.includes('circular') ||
|
||||
error.message?.includes('Circular') ||
|
||||
error.message?.includes('Duplicate article')
|
||||
) return 400;
|
||||
return 500;
|
||||
}
|
||||
|
||||
export function interpolateString(str, article) {
|
||||
if (typeof str !== 'string') return str;
|
||||
const net = article.net_price ?? article.prices?.[0]?.net;
|
||||
const taxRate = article.prices?.[0]?.taxRate ?? 0;
|
||||
const gross = net != null ? +(net * (1 + taxRate / 100)).toFixed(2) : null;
|
||||
const ean = (article.eans && article.eans.length > 0) ? article.eans[0] : '';
|
||||
|
||||
return str
|
||||
.replace(/\{\{(?:ARTICLE_NAME|article_name|name)\}\}/gi, article.name || '')
|
||||
.replace(/\{\{SKU\}\}/gi, article.sku || '')
|
||||
.replace(/\{\{(?:NET_PRICE|net_price)\}\}/gi, net != null ? net.toString() : '')
|
||||
.replace(/\{\{(?:GROSS_PRICE|gross_price)\}\}/gi, gross != null ? gross.toString() : '')
|
||||
.replace(/\{\{(?:PRICE|price)\}\}/gi, gross != null ? gross.toString() : (net != null ? net.toString() : ''))
|
||||
.replace(/\{\{(?:EAN|ean)\}\}/gi, ean);
|
||||
}
|
||||
|
||||
// #endregion
|
||||
651
src/api/routes/article/variants.js
Normal file
651
src/api/routes/article/variants.js
Normal file
@@ -0,0 +1,651 @@
|
||||
import * as db from '../../../db/article.js';
|
||||
import {
|
||||
emitArticlesSignal,
|
||||
emitArticleSignal,
|
||||
parseSku,
|
||||
articleErrorStatus,
|
||||
} from './shared.js';
|
||||
|
||||
/**
|
||||
* Registers article variant routes — parent mode, children, Stückliste
|
||||
* (articlelist) and options (requires auth middleware).
|
||||
* @param {import('express').Application} app - Express app
|
||||
* @param {string} [basePath=''] - Optional URL prefix for all routes in this module
|
||||
*/
|
||||
export function register(app, basePath = '') {
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/parent:
|
||||
* post:
|
||||
* summary: Toggle parent mode for an article
|
||||
* description: |
|
||||
* Enables or disables parent article status. Enabling requires specifying an
|
||||
* attributeNameId; disabling requires the article to have zero children.
|
||||
*
|
||||
* `attributeNameId` is **conditionally required**: it is optional in the schema
|
||||
* because it is only required when `isParent` is `true`. Omitting it (or passing
|
||||
* `0`/a negative value) together with `isParent: true` returns `400`
|
||||
* `attributeNameId is required to become a parent article`. It must not be sent
|
||||
* when `isParent` is `false`.
|
||||
* tags:
|
||||
* - Article
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Article SKU
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [isParent]
|
||||
* properties:
|
||||
* isParent:
|
||||
* type: boolean
|
||||
* description: True to make article a parent, false to revert to regular article
|
||||
* attributeNameId:
|
||||
* type: integer
|
||||
* description: |
|
||||
* **Conditionally required when `isParent` is `true`** (required iff isParent=true).
|
||||
* The attributename id used for the article's variants. Omitting it while
|
||||
* enabling parent mode returns 400. Must be omitted when `isParent` is `false`.
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated article
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* article:
|
||||
* $ref: '#/components/schemas/Article'
|
||||
* 400:
|
||||
* description: |
|
||||
* Invalid input — `attributeNameId` missing while `isParent` is true, article still
|
||||
* has children (disabling), or the attribute is already used by an ancestor parent.
|
||||
* 409:
|
||||
* description: |
|
||||
* Article state conflicts with becoming a variant parent — it still has stock,
|
||||
* assigned suppliers, a Stückliste, or options. Clear these first.
|
||||
* 404:
|
||||
* description: Article or attribute name not found
|
||||
*/
|
||||
// #region POST /article/:sku/parent
|
||||
|
||||
app.post(`${basePath}/article/:sku/parent`, async (req, res) => {
|
||||
const parsed = parseSku(req.params.sku);
|
||||
if (parsed.error) return res.status(400).json({ error: parsed.error });
|
||||
|
||||
const isParent = req.body?.isParent;
|
||||
if (typeof isParent !== 'boolean') {
|
||||
return res.status(400).json({ error: 'isParent boolean is required' });
|
||||
}
|
||||
const attributeNameId = req.body?.attributeNameId;
|
||||
|
||||
try {
|
||||
const result = await db.toggleParent(req.user.id, parsed.sku, {
|
||||
isParent,
|
||||
attributeNameId,
|
||||
});
|
||||
emitArticleSignal(req, parsed.sku);
|
||||
emitArticlesSignal(req);
|
||||
res.status(200).json(result);
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Toggle parent failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/children:
|
||||
* get:
|
||||
* summary: List child articles of a parent article
|
||||
* description: Returns variants/children linked to this parent article.
|
||||
* tags:
|
||||
* - Article
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Parent article SKU
|
||||
* responses:
|
||||
* 200:
|
||||
* description: List of children
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* children:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/ArticleChild'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
*/
|
||||
// #region GET /article/:sku/children
|
||||
|
||||
app.get(`${basePath}/article/:sku/children`, async (req, res) => {
|
||||
const parsed = parseSku(req.params.sku);
|
||||
if (parsed.error) return res.status(400).json({ error: parsed.error });
|
||||
|
||||
try {
|
||||
const children = await db.listChildren(req.user.id, parsed.sku);
|
||||
res.status(200).json({ children });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('List children failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/children:
|
||||
* post:
|
||||
* summary: Create and attach a new child article to a parent article
|
||||
* description: Automatically generates SKU as parentSku-nextFreeIndex and name from parent name + value. Rejects a caller-supplied sku.
|
||||
* tags:
|
||||
* - Article
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Parent article SKU
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* attributeValueId:
|
||||
* type: integer
|
||||
* description: ID of existing attribute value for the parent's attribute
|
||||
* value:
|
||||
* type: string
|
||||
* description: String value to find or create under the parent's attribute
|
||||
* name:
|
||||
* type: string
|
||||
* description: Optional custom variant name
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Created child article
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* article:
|
||||
* $ref: '#/components/schemas/Article'
|
||||
* 400:
|
||||
* description: Parent not configured as parent, missing value, duplicate variant, or sku was provided in body
|
||||
* put:
|
||||
* summary: Attach an existing article as a child to a parent article
|
||||
* description: Attaches an existing article to this parent article. Idempotent if already a child. Returns 409 if the article already belongs to another parent.
|
||||
* tags:
|
||||
* - Article
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Parent article SKU
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - sku
|
||||
* properties:
|
||||
* sku:
|
||||
* type: string
|
||||
* description: SKU of the existing article to attach as child
|
||||
* attributeValueId:
|
||||
* type: integer
|
||||
* description: ID of existing attribute value for the parent's attribute
|
||||
* value:
|
||||
* type: string
|
||||
* description: String value to find or create under the parent's attribute
|
||||
* reparent:
|
||||
* type: boolean
|
||||
* description: Whether to allow re-parenting if child already belongs to another parent
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Attached child article and list of children
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* article:
|
||||
* $ref: '#/components/schemas/Article'
|
||||
* children:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/ArticleChild'
|
||||
* 400:
|
||||
* description: Missing sku or attribute value, or invalid input
|
||||
* 404:
|
||||
* description: Parent or child article not found
|
||||
* 409:
|
||||
* description: Article already belongs to another parent, or variant value already exists
|
||||
*/
|
||||
// #region POST /article/:sku/children
|
||||
|
||||
app.post(`${basePath}/article/:sku/children`, async (req, res) => {
|
||||
const parsed = parseSku(req.params.sku);
|
||||
if (parsed.error) return res.status(400).json({ error: parsed.error });
|
||||
|
||||
if (req.body?.sku || req.body?.childSku) {
|
||||
return res.status(400).json({
|
||||
error: 'sku is not allowed when creating a child article; omit sku to auto-generate or use PUT to attach an existing article',
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await db.addChild(req.user.id, parsed.sku, req.body || {});
|
||||
emitArticleSignal(req, parsed.sku);
|
||||
if (result?.article?.sku) {
|
||||
emitArticleSignal(req, result.article.sku);
|
||||
}
|
||||
emitArticlesSignal(req);
|
||||
res.status(201).json(result);
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Add child failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
// #region PUT /article/:sku/children
|
||||
|
||||
app.put(`${basePath}/article/:sku/children`, async (req, res) => {
|
||||
const parsed = parseSku(req.params.sku);
|
||||
if (parsed.error) return res.status(400).json({ error: parsed.error });
|
||||
|
||||
const childSku = typeof req.body?.sku === 'string' && req.body.sku.trim()
|
||||
? req.body.sku.trim()
|
||||
: (typeof req.body?.childSku === 'string' && req.body.childSku.trim() ? req.body.childSku.trim() : '');
|
||||
if (!childSku) {
|
||||
return res.status(400).json({ error: 'sku is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await db.attachChild(req.user.id, parsed.sku, req.body || {});
|
||||
emitArticleSignal(req, parsed.sku);
|
||||
emitArticleSignal(req, childSku);
|
||||
emitArticlesSignal(req);
|
||||
res.status(200).json(result);
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Attach child failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/children/{childSku}:
|
||||
* delete:
|
||||
* summary: Remove a child article from a parent article
|
||||
* description: Unlinks the child from the parent (or deletes if deleteArticle query/body is true).
|
||||
* tags:
|
||||
* - Article
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Parent article SKU
|
||||
* - in: path
|
||||
* name: childSku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Child article SKU
|
||||
* - in: query
|
||||
* name: deleteArticle
|
||||
* schema:
|
||||
* type: boolean
|
||||
* description: If true, permanently deletes the child article (and cascades its entire descendant subtree if it is a parent) instead of just unlinking
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Child removed
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* deleted:
|
||||
* type: boolean
|
||||
*/
|
||||
// #region DELETE /article/:sku/children/:childSku
|
||||
|
||||
app.delete(`${basePath}/article/:sku/children/:childSku`, async (req, res) => {
|
||||
const parsed = parseSku(req.params.sku);
|
||||
if (parsed.error) return res.status(400).json({ error: parsed.error });
|
||||
|
||||
const parsedChild = parseSku(req.params.childSku);
|
||||
if (parsedChild.error) return res.status(400).json({ error: 'childSku is required' });
|
||||
|
||||
const deleteArticle = req.query.deleteArticle === 'true' || req.body?.deleteArticle === true;
|
||||
|
||||
try {
|
||||
const result = await db.removeChild(req.user.id, parsed.sku, parsedChild.sku, {
|
||||
deleteArticle,
|
||||
});
|
||||
emitArticleSignal(req, parsed.sku);
|
||||
emitArticleSignal(req, parsedChild.sku);
|
||||
emitArticlesSignal(req);
|
||||
res.status(200).json(result);
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Remove child failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/articlelist:
|
||||
* @openapi
|
||||
* /article/{sku}/articlelist:
|
||||
* get:
|
||||
* summary: Get Stückliste (bundle items) for an article
|
||||
* description: Returns the list of component items for a Stückliste article.
|
||||
* tags:
|
||||
* - Article
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Article SKU
|
||||
* responses:
|
||||
* 200:
|
||||
* description: List of bundle items
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* items:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/StuecklisteItem'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
*/
|
||||
// #region GET /article/:sku/articlelist
|
||||
|
||||
app.get(`${basePath}/article/:sku/articlelist`, async (req, res) => {
|
||||
const parsed = parseSku(req.params.sku);
|
||||
if (parsed.error) return res.status(400).json({ error: parsed.error });
|
||||
|
||||
try {
|
||||
const items = await db.getArticlelist(req.user.id, parsed.sku);
|
||||
res.status(200).json({ items });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Get articlelist failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/articlelist:
|
||||
* put:
|
||||
* summary: Set Stückliste (bundle items) for an article
|
||||
* description: Configures the article as a Stückliste covering a list of count * article. A parent article cannot be a Stückliste. Can be combined with options. Pass an empty array to remove the Stückliste.
|
||||
* tags:
|
||||
* - Article
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Article SKU
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [items]
|
||||
* properties:
|
||||
* items:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* articleId:
|
||||
* type: integer
|
||||
* sku:
|
||||
* type: string
|
||||
* count:
|
||||
* type: integer
|
||||
* default: 1
|
||||
* sort:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated Stückliste items
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* items:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/StuecklisteItem'
|
||||
* 400:
|
||||
* description: Article is a parent, has options, or contains itself
|
||||
* 404:
|
||||
* description: Article or component article not found
|
||||
*/
|
||||
// #region PUT /article/:sku/articlelist
|
||||
|
||||
app.put(`${basePath}/article/:sku/articlelist`, async (req, res) => {
|
||||
const parsed = parseSku(req.params.sku);
|
||||
if (parsed.error) return res.status(400).json({ error: parsed.error });
|
||||
|
||||
const items = req.body?.items;
|
||||
if (!Array.isArray(items)) {
|
||||
return res.status(400).json({ error: 'items array is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await db.setArticlelist(req.user.id, parsed.sku, items);
|
||||
emitArticleSignal(req, parsed.sku);
|
||||
emitArticlesSignal(req);
|
||||
res.status(200).json({ items: updated });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Set articlelist failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/optionslist:
|
||||
* get:
|
||||
* summary: Get options list for an article
|
||||
* description: Returns the available options for an article.
|
||||
* tags:
|
||||
* - Article
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Article SKU
|
||||
* responses:
|
||||
* 200:
|
||||
* description: List of options
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* options:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/ArticleOptionItem'
|
||||
* 404:
|
||||
* description: Article not found
|
||||
*/
|
||||
// #region GET /article/:sku/optionslist
|
||||
|
||||
app.get(`${basePath}/article/:sku/optionslist`, async (req, res) => {
|
||||
const parsed = parseSku(req.params.sku);
|
||||
if (parsed.error) return res.status(400).json({ error: parsed.error });
|
||||
|
||||
try {
|
||||
const options = await db.getOptionslist(req.user.id, parsed.sku);
|
||||
res.status(200).json({ options });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Get optionslist failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /article/{sku}/optionslist:
|
||||
* put:
|
||||
* summary: Set options list for an article
|
||||
* description: Configures options for an article. Some options can be mandated (come with the article in any case). A parent article cannot have options. Can be combined with a Stückliste. Pass an empty array to remove options.
|
||||
* tags:
|
||||
* - Article
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sku
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Article SKU
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [options]
|
||||
* properties:
|
||||
* options:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* articleId:
|
||||
* type: integer
|
||||
* sku:
|
||||
* type: string
|
||||
* count:
|
||||
* type: integer
|
||||
* default: 1
|
||||
* sort:
|
||||
* type: integer
|
||||
* mandated:
|
||||
* type: boolean
|
||||
* default: false
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated options list
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* options:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/ArticleOptionItem'
|
||||
* 400:
|
||||
* description: Article is a parent, a Stückliste, or contains itself
|
||||
* 404:
|
||||
* description: Article or option article not found
|
||||
*/
|
||||
// #region PUT /article/:sku/optionslist
|
||||
|
||||
app.put(`${basePath}/article/:sku/optionslist`, async (req, res) => {
|
||||
const parsed = parseSku(req.params.sku);
|
||||
if (parsed.error) return res.status(400).json({ error: parsed.error });
|
||||
|
||||
const options = req.body?.options;
|
||||
if (!Array.isArray(options)) {
|
||||
return res.status(400).json({ error: 'options array is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await db.setOptionslist(req.user.id, parsed.sku, options);
|
||||
emitArticleSignal(req, parsed.sku);
|
||||
emitArticlesSignal(req);
|
||||
res.status(200).json({ options: updated });
|
||||
} catch (error) {
|
||||
const status = articleErrorStatus(error);
|
||||
if (status === 500) console.error('Set optionslist failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
}
|
||||
Reference in New Issue
Block a user