diff --git a/API.article.md b/API.article.md index 167d831..9991133 100644 --- a/API.article.md +++ b/API.article.md @@ -123,7 +123,7 @@ Returns the full detail of an article by its SKU, including unit, brand, categor **Returns** -`Promise<{article: object}>` — The full article detail. +`Promise<{article: {id: number, sku: string, name: string, slug: string, unitamount: number|null, weight: number|null, unit: {si: string|null, basesi: string|null, basesifactor: number|null, symbol: string|null, name: string|null}, brand: {name: string, thumbW: number, thumbH: number, thumbHash: string}|null, categoryIds: number[], photos: Array<{sort: number, fullHash: string, fullW: number, fullH: number, fullSize: number, thumbW: number, thumbH: number, thumbHash: string}>, eans: string[], prices: Array<{minmultiplier: number, net: number, taxRate: number, customergroupId: number}>, suppliers: Array<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, priceId: number|null, price: {net: number, taxId: number, taxRate?: number}|null}>, optionsCount: number, articleListCount: number, childCount: number, fatherArticleId: number|null, fatherSku: string|null}}>` — The full article detail. **Throws** diff --git a/API.articlesupplier.md b/API.articlesupplier.md new file mode 100644 index 0000000..55462af --- /dev/null +++ b/API.articlesupplier.md @@ -0,0 +1,140 @@ +# articlesupplier + +This document is auto-generated from the JSDoc comments in `src/store` by running `npm run api-doc`. + +## `articlesupplier.create` + +*Source: `src/store/articlesupplier/create.js`* + +Assigns a supplier to an article, optionally creating a purchase price. + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `googleAuthId` | `number` | The id of the Google auth user. | +| `sku` | `string` | The article SKU. | +| `input` | `object` | The supplier assignment input. | +| `input.entityId` | `number` | The id of the supplier entity. | +| `[input.sku]` | `string` | The supplier's item number/SKU. | +| `[input.pu]` | `number` | Packaging unit (defaults to 1). | +| `[input.stock]` | `number|null` | Current stock at the supplier. | +| `[input.netPrice]` | `number|null` | Net purchase price. | +| `[input.taxId]` | `number` | The tax id for the purchase price. | +| `[input.taxRate]` | `number` | The tax rate in percent (used if taxId is not provided). | + +**Returns** + +`Promise<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, priceId: number|null, price: {net: number, taxId: number, taxRate?: number}|null}>` — The created assignment. + +**Throws** + +`Error` — If input is invalid, article or supplier is not found, or supplier is already assigned. + +**Example** + +```js +const created = await store.articlesupplier.create(42, 'SKU-1', { + entityId: 88, + sku: 'MET-44910', + pu: 1, + netPrice: 4.20, +}); +// => { id, articleId, entityId, supplierName, sku, pu, stock, priceId, price } +``` + +## `articlesupplier.delete` + +*Source: `src/store/articlesupplier/delete.js`* + +Deletes a supplier assignment and cleans up its associated purchase price. + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `googleAuthId` | `number` | The id of the Google auth user. | +| `sku` | `string` | The article SKU. | +| `id` | `number` | The id of the articlesupplier record. | + +**Returns** + +`Promise` + +**Throws** + +`Error` — If the supplier assignment is not found. + +**Example** + +```js +await store.articlesupplier.delete(42, 'SKU-1', 12); +``` + +## `articlesupplier.listByArticleSku` + +*Source: `src/store/articlesupplier/listByArticleSku.js`* + +Lists the supplier assignments for an article by its SKU. + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `googleAuthId` | `number` | The id of the Google auth user. | +| `sku` | `string` | The article SKU. | + +**Returns** + +`Promise>` — The supplier assignments. + +**Throws** + +`Error` — If the article is not found or the user is not authorized. + +**Example** + +```js +const suppliers = await store.articlesupplier.listByArticleSku(42, 'SKU-1'); +// => [{ id, articleId, entityId, supplierName, sku, pu, stock, priceId, price }] +``` + +## `articlesupplier.update` + +*Source: `src/store/articlesupplier/update.js`* + +Updates an existing supplier assignment and its associated purchase price. + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `googleAuthId` | `number` | The id of the Google auth user. | +| `sku` | `string` | The article SKU. | +| `id` | `number` | The id of the articlesupplier record. | +| `patch` | `object` | The fields to update. | +| `[patch.sku]` | `string|null` | The supplier's item number/SKU. | +| `[patch.pu]` | `number` | Packaging unit (> 0). | +| `[patch.stock]` | `number|null` | Current stock at the supplier. | +| `[patch.netPrice]` | `number|null` | Net purchase price. | +| `[patch.taxId]` | `number` | The tax id for the purchase price. | +| `[patch.taxRate]` | `number` | The tax rate in percent. | + +**Returns** + +`Promise<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, priceId: number|null, price: {net: number, taxId: number, taxRate?: number}|null}>` — The updated assignment. + +**Throws** + +`Error` — If input is invalid or supplier assignment is not found. + +**Example** + +```js +const updated = await store.articlesupplier.update(42, 'SKU-1', 12, { + sku: 'MET-44910-B', + pu: 6, + netPrice: 22.50, +}); +// => { id, articleId, entityId, supplierName, sku, pu, stock, priceId, price } +``` diff --git a/API.md b/API.md index a76116a..ae228fd 100644 --- a/API.md +++ b/API.md @@ -33,7 +33,7 @@ The store is exposed as a `LibDashStore` instance (see `src/index.js`). Each met - `createUnderParent(input: {googleAuthId: number, parentId: number, name: string}): Promise<{id: number, parentId: number, name: string, sku: string}>` - `delete(googleAuthId: number, sku: string): Promise` - `deleteImage(googleAuthId: number, sku: string, fullHash: string): Promise` - - `getBySku(googleAuthId: number, sku: string): Promise<{article: object}>` + - `getBySku(googleAuthId: number, sku: string): Promise<{article: {id: number, sku: string, name: string, slug: string, unitamount: number|null, weight: number|null, unit: {si: string|null, basesi: string|null, basesifactor: number|null, symbol: string|null, name: string|null}, brand: {name: string, thumbW: number, thumbH: number, thumbHash: string}|null, categoryIds: number[], photos: Array<{sort: number, fullHash: string, fullW: number, fullH: number, fullSize: number, thumbW: number, thumbH: number, thumbHash: string}>, eans: string[], prices: Array<{minmultiplier: number, net: number, taxRate: number, customergroupId: number}>, suppliers: Array<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, priceId: number|null, price: {net: number, taxId: number, taxRate?: number}|null}>, optionsCount: number, articleListCount: number, childCount: number, fatherArticleId: number|null, fatherSku: string|null}}>` - `getHistoryBySku(googleAuthId: number, sku: string): Promise>` - `importRows(input: {googleAuthId: number, rows: Array}): Promise<{imported: Array, skipped: Array, errors: Array}>` - `listExport(googleAuthId: number, categoryId?: number|null): Promise>` @@ -98,6 +98,11 @@ The store is exposed as a `LibDashStore` instance (see `src/index.js`). Each met - `delete(googleAuthId: number, id: number): Promise` - `list(googleAuthId: number): Promise>` - `update(googleAuthId: number, id: number, input: {name: string}): Promise<{id: number, name: string, createdAt: string, updatedAt: string}>` +- [articlesupplier](API.articlesupplier.md) + - `create(googleAuthId: number, sku: string, input: {entityId: number, sku?: string, pu?: number, stock?: number|null, netPrice?: number|null, taxId?: number, taxRate?: number}): Promise<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, priceId: number|null, price: {net: number, taxId: number, taxRate?: number}|null}>` + - `delete(googleAuthId: number, sku: string, id: number): Promise` + - `listByArticleSku(googleAuthId: number, sku: string): Promise>` + - `update(googleAuthId: number, sku: string, id: number, patch: {sku?: string|null, pu?: number, stock?: number|null, netPrice?: number|null, taxId?: number, taxRate?: number}): Promise<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, priceId: number|null, price: {net: number, taxId: number, taxRate?: number}|null}>` - [delivery](API.delivery.md) - `create(googleAuthId: number, body: {date: string, supplierId: number, externalNumber?: string, lines?: Array<{sku?: string, name?: string, pu?: number, amount: number, net: number, rebate?: number, taxrate: number, comment?: string|null}>}): Promise<{id: number, number: string, type: string, entityId: number, externalNumber: string|null, date: string, lines: Array<{id: number, sku: string|null, name: string|null, pu: number, amount: number, net: number, rebate: number, taxrate: number, comment: string|null}>}>` - `delete(googleAuthId: number, id: number): Promise` diff --git a/README.md b/README.md index 852a956..527a7f1 100644 --- a/README.md +++ b/README.md @@ -296,11 +296,22 @@ Maps articles to suppliers (`entity`) with purchase pricing, stock, packaging un | `id` | `INT` | Primary Key (`IDENTITY(1,1)`) | | `article_id` | `INT` | FK → `article(id)` (`ON DELETE CASCADE`) | | `entity_id` | `INT` | FK → `entity(id)` (`ON DELETE CASCADE`) | -| `price_id` | `INT` | FK → `price(id)` (`ON DELETE NO ACTION`), nullable | +| `price_id` | `INT` | FK → `price(id)` (`ON DELETE SET NULL`), nullable | | `sku` | `NVARCHAR(100)` | Supplier's SKU code, nullable | | `stock` | `FLOAT` | Stock available at supplier, nullable | | `pu` | `FLOAT` | Packaging unit (Verpackungseinheit), default `1` | +Unique constraint: `UQ_articlesupplier_article_entity (article_id, entity_id)` + +| Method | Signature | Returns | +| --- | --- | --- | +| `listByArticleSku` | `(googleAuthId, sku)` | `ArticleSupplierSummary[]` | +| `create` | `(googleAuthId, sku, { entityId, sku?, pu?, stock?, netPrice?, taxId?, taxRate? })` | `ArticleSupplierSummary` | +| `update` | `(googleAuthId, sku, id, { sku?, pu?, stock?, netPrice?, taxId?, taxRate? })` | `ArticleSupplierSummary` | +| `delete` | `(googleAuthId, sku, id)` | `void` | + +Errors: `Not authorized`, `Article not found`, `Supplier required`, `Supplier not found`, `Supplier assignment not found`, `Supplier already assigned`, `Invalid pu`, `Invalid stock`, `Invalid price`. + --- ## `delivery` @@ -746,6 +757,10 @@ Company-scoped number sequences (`numbers` table). Auth via selected company (`g | `POST /api/supplier` | `supplier.create(googleAuthId, { name })` | | `PATCH /api/supplier/:id` | `supplier.update(googleAuthId, id, { name })` | | `DELETE /api/supplier/:id` | `supplier.delete(googleAuthId, id)` | +| `GET /api/article/:sku/supplier` | `articlesupplier.listByArticleSku(googleAuthId, sku)` | +| `POST /api/article/:sku/supplier` | `articlesupplier.create(googleAuthId, sku, { entityId, sku?, pu?, stock?, netPrice?, taxId?, taxRate? })` | +| `PATCH /api/article/:sku/supplier/:id` | `articlesupplier.update(googleAuthId, sku, id, patch)` | +| `DELETE /api/article/:sku/supplier/:id` | `articlesupplier.delete(googleAuthId, sku, id)` | | `GET /api/delivery` | `delivery.list(googleAuthId)` | | `GET /api/delivery/:id` | `delivery.getById(googleAuthId, id)` | | `POST /api/delivery` | `delivery.create(googleAuthId, { number, date, supplierId?, lines })` | diff --git a/generate-api-doc.js b/generate-api-doc.js index de3f850..6ca1c06 100644 --- a/generate-api-doc.js +++ b/generate-api-doc.js @@ -23,6 +23,7 @@ const MODULE_ORDER = [ 'entityaddress', 'entitycontact', 'supplier', + 'articlesupplier', 'delivery', 'quote', 'order', diff --git a/src/index.js b/src/index.js index 05ebc6f..f0317d3 100644 --- a/src/index.js +++ b/src/index.js @@ -65,6 +65,10 @@ import supplierList from './store/supplier/list.js'; import supplierCreate from './store/supplier/create.js'; import supplierUpdate from './store/supplier/update.js'; import supplierDelete from './store/supplier/delete.js'; +import articlesupplierListByArticleSku from './store/articlesupplier/listByArticleSku.js'; +import articlesupplierCreate from './store/articlesupplier/create.js'; +import articlesupplierUpdate from './store/articlesupplier/update.js'; +import articlesupplierDelete from './store/articlesupplier/delete.js'; import deliveryList from './store/delivery/list.js'; import deliveryGetById from './store/delivery/getById.js'; import deliveryCreate from './store/delivery/create.js'; @@ -237,6 +241,13 @@ export default class LibDashStore { delete: supplierDelete(pool), }; + this.articlesupplier = { + listByArticleSku: articlesupplierListByArticleSku(pool), + create: articlesupplierCreate(pool), + update: articlesupplierUpdate(pool), + delete: articlesupplierDelete(pool), + }; + this.delivery = { list: deliveryList(pool), getById: deliveryGetById(pool), diff --git a/src/schema.js b/src/schema.js index d649025..28ec668 100644 --- a/src/schema.js +++ b/src/schema.js @@ -541,7 +541,8 @@ BEGIN pu FLOAT NOT NULL CONSTRAINT DF_articlesupplier_pu DEFAULT 1, CONSTRAINT FK_articlesupplier_article FOREIGN KEY (article_id) REFERENCES article(id) ON DELETE CASCADE, CONSTRAINT FK_articlesupplier_entity FOREIGN KEY (entity_id) REFERENCES entity(id) ON DELETE CASCADE, - CONSTRAINT FK_articlesupplier_price FOREIGN KEY (price_id) REFERENCES price(id) ON DELETE NO ACTION + CONSTRAINT FK_articlesupplier_price FOREIGN KEY (price_id) REFERENCES price(id) ON DELETE SET NULL, + CONSTRAINT UQ_articlesupplier_article_entity UNIQUE (article_id, entity_id) ); CREATE INDEX IX_articlesupplier_article_entity diff --git a/src/sql/article.js b/src/sql/article.js index 395d9e6..da3b4d0 100644 --- a/src/sql/article.js +++ b/src/sql/article.js @@ -461,7 +461,28 @@ SELECT WHERE pr.article_id = a.id ORDER BY pr.customergroup_id, pr.minmultiplier FOR JSON PATH - ) AS pricesJson + ) AS pricesJson, + ( + SELECT + asup.id, + asup.article_id AS articleId, + asup.entity_id AS entityId, + e.name AS supplierName, + asup.sku, + asup.pu, + asup.stock, + asup.price_id AS priceId, + p.net AS [price.net], + p.tax_id AS [price.taxId], + t.rate AS [price.taxRate] + FROM articlesupplier asup + INNER JOIN entity e ON e.id = asup.entity_id + LEFT JOIN price p ON p.id = asup.price_id + LEFT JOIN tax t ON t.id = p.tax_id + WHERE asup.article_id = a.id + ORDER BY e.name, asup.id + FOR JSON PATH + ) AS suppliersJson FROM article a LEFT JOIN articletext at ON at.article_id = a.id AND at.language_id = auth.languageId diff --git a/src/sql/articlesupplier.js b/src/sql/articlesupplier.js new file mode 100644 index 0000000..7e6eb97 --- /dev/null +++ b/src/sql/articlesupplier.js @@ -0,0 +1,91 @@ +export const LIST_BY_ARTICLE_ID = ` +SELECT + asup.id, + asup.article_id AS articleId, + asup.entity_id AS entityId, + e.name AS supplierName, + asup.sku, + asup.pu, + asup.stock, + asup.price_id AS priceId, + p.net AS priceNet, + p.tax_id AS priceTaxId, + t.rate AS priceTaxRate +FROM articlesupplier asup +INNER JOIN entity e ON e.id = asup.entity_id +INNER JOIN customergroup cg ON cg.id = e.customergroup_id +LEFT JOIN price p ON p.id = asup.price_id +LEFT JOIN tax t ON t.id = p.tax_id +WHERE asup.article_id = @articleId + AND cg.company_id = @companyId +ORDER BY e.name, asup.id; +`; + +export const GET_BY_ID_AND_ARTICLE_ID = ` +SELECT + asup.id, + asup.article_id AS articleId, + asup.entity_id AS entityId, + e.name AS supplierName, + asup.sku, + asup.pu, + asup.stock, + asup.price_id AS priceId, + p.net AS priceNet, + p.tax_id AS priceTaxId, + t.rate AS priceTaxRate +FROM articlesupplier asup +INNER JOIN entity e ON e.id = asup.entity_id +INNER JOIN customergroup cg ON cg.id = e.customergroup_id +LEFT JOIN price p ON p.id = asup.price_id +LEFT JOIN tax t ON t.id = p.tax_id +WHERE asup.id = @id + AND asup.article_id = @articleId + AND cg.company_id = @companyId; +`; + +export const CHECK_EXISTS = ` +SELECT TOP 1 id +FROM articlesupplier +WHERE article_id = @articleId AND entity_id = @entityId; +`; + +export const CREATE = ` +INSERT INTO articlesupplier (article_id, entity_id, price_id, sku, stock, pu) +OUTPUT INSERTED.id +VALUES (@articleId, @entityId, @priceId, @sku, @stock, @pu); +`; + +export const UPDATE = ` +UPDATE articlesupplier +SET + sku = @sku, + stock = @stock, + pu = @pu, + price_id = @priceId +WHERE id = @id AND article_id = @articleId; +`; + +export const DELETE_BY_ID_AND_ARTICLE_ID = ` +DELETE FROM articlesupplier +WHERE id = @id AND article_id = @articleId; +`; + +export const UPDATE_PRICE = ` +UPDATE price +SET + net = @net, + tax_id = @taxId +WHERE id = @id AND article_id = @articleId; +`; + +export const DELETE_PRICE = ` +DELETE FROM price +WHERE id = @id AND article_id = @articleId; +`; + +export const GET_COMPANY_DEFAULT_TAX = ` +SELECT taxrate +FROM company +WHERE id = @companyId; +`; diff --git a/src/store/article/getBySku.js b/src/store/article/getBySku.js index b4b2155..c2dfd38 100644 --- a/src/store/article/getBySku.js +++ b/src/store/article/getBySku.js @@ -13,7 +13,7 @@ export default function getBySku(pool) { * * @param {number} googleAuthId - The id of the Google auth user. * @param {string} sku - The article SKU. - * @returns {Promise<{article: object}>} The full article detail. + * @returns {Promise<{article: {id: number, sku: string, name: string, slug: string, unitamount: number|null, weight: number|null, unit: {si: string|null, basesi: string|null, basesifactor: number|null, symbol: string|null, name: string|null}, brand: {name: string, thumbW: number, thumbH: number, thumbHash: string}|null, categoryIds: number[], photos: Array<{sort: number, fullHash: string, fullW: number, fullH: number, fullSize: number, thumbW: number, thumbH: number, thumbHash: string}>, eans: string[], prices: Array<{minmultiplier: number, net: number, taxRate: number, customergroupId: number}>, suppliers: Array<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, priceId: number|null, price: {net: number, taxId: number, taxRate?: number}|null}>, optionsCount: number, articleListCount: number, childCount: number, fatherArticleId: number|null, fatherSku: string|null}}>} The full article detail. * @throws {Error} If the article is not found or the user is not authorized. * * @example @@ -72,6 +72,17 @@ export default function getBySku(pool) { photos: parseJsonArray(a.photosJson), eans: parseJsonArray(a.eansJson).map((r) => r.ean), prices: parseJsonArray(a.pricesJson), + suppliers: parseJsonArray(a.suppliersJson).map((s) => ({ + id: s.id, + articleId: s.articleId, + entityId: s.entityId, + supplierName: s.supplierName, + sku: s.sku ?? null, + pu: s.pu, + stock: s.stock ?? null, + priceId: s.priceId ?? null, + price: s.priceId != null && s.price?.net != null ? s.price : null, + })), optionsCount: a.optionsCount, articleListCount: a.articleListCount, childCount: a.childCount, diff --git a/src/store/articlesupplier/create.js b/src/store/articlesupplier/create.js new file mode 100644 index 0000000..f61dcab --- /dev/null +++ b/src/store/articlesupplier/create.js @@ -0,0 +1,156 @@ +import { + CHECK_EXISTS, + CREATE as CREATE_ARTICLE_SUPPLIER, + GET_BY_ID_AND_ARTICLE_ID, +} from '../../sql/articlesupplier.js'; +import { CREATE as CREATE_PRICE } from '../../sql/price.js'; +import request from '../request.js'; +import resolveArticleBySku from '../article/resolveArticleBySku.js'; +import ensureLieferantenGroup from '../supplier/ensureLieferantenGroup.js'; +import taxEnsure from '../tax/ensure.js'; +import { + assertSupplier, + optionalString, + resolveCompanyDefaultTax, + shapeArticleSupplier, +} from './helpers.js'; + +export default function create(pool) { + const resolve = resolveArticleBySku(pool); + const ensureTax = taxEnsure(pool); + + /** + * Assigns a supplier to an article, optionally creating a purchase price. + * + * @param {number} googleAuthId - The id of the Google auth user. + * @param {string} sku - The article SKU. + * @param {object} input - The supplier assignment input. + * @param {number} input.entityId - The id of the supplier entity. + * @param {string} [input.sku] - The supplier's item number/SKU. + * @param {number} [input.pu] - Packaging unit (defaults to 1). + * @param {number|null} [input.stock] - Current stock at the supplier. + * @param {number|null} [input.netPrice] - Net purchase price. + * @param {number} [input.taxId] - The tax id for the purchase price. + * @param {number} [input.taxRate] - The tax rate in percent (used if taxId is not provided). + * @returns {Promise<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, priceId: number|null, price: {net: number, taxId: number, taxRate?: number}|null}>} The created assignment. + * @throws {Error} If input is invalid, article or supplier is not found, or supplier is already assigned. + * + * @example + * const created = await store.articlesupplier.create(42, 'SKU-1', { + * entityId: 88, + * sku: 'MET-44910', + * pu: 1, + * netPrice: 4.20, + * }); + * // => { id, articleId, entityId, supplierName, sku, pu, stock, priceId, price } + */ + return async (googleAuthId, sku, input = {}) => { + const entityId = input.entityId; + if (entityId == null || !Number.isFinite(entityId)) { + throw new Error('Supplier required'); + } + + const pu = input.pu === undefined || input.pu === null ? 1 : input.pu; + if (!Number.isFinite(pu) || pu <= 0) { + throw new Error('Invalid pu'); + } + + const supplierSku = optionalString(input.sku); + + const stock = + input.stock === undefined || input.stock === null ? null : input.stock; + if (stock !== null && !Number.isFinite(stock)) { + throw new Error('Invalid stock'); + } + + const netPrice = + input.netPrice === undefined || input.netPrice === null + ? null + : input.netPrice; + if (netPrice !== null && !Number.isFinite(netPrice)) { + throw new Error('Invalid price'); + } + + const { articleId, companyId } = await resolve(googleAuthId, sku); + + await assertSupplier(pool, null, companyId, entityId); + + const existingCheck = await pool + .request() + .input('articleId', articleId) + .input('entityId', entityId) + .query(CHECK_EXISTS); + + if (existingCheck.recordset[0]) { + throw new Error('Supplier already assigned'); + } + + const tx = pool.transaction(); + await tx.begin(); + + try { + let priceId = null; + + if (netPrice !== null) { + let taxId = input.taxId; + if (taxId == null || !Number.isFinite(taxId)) { + if (input.taxRate != null && Number.isFinite(input.taxRate)) { + taxId = await ensureTax(input.taxRate, tx); + } else { + const defaultTaxId = await resolveCompanyDefaultTax( + pool, + tx, + companyId, + ); + taxId = defaultTaxId != null ? defaultTaxId : await ensureTax(0, tx); + } + } + + const customerGroupId = await ensureLieferantenGroup( + pool, + companyId, + tx, + ); + + const priceRes = await request(pool, tx) + .input('taxId', taxId) + .input('articleId', articleId) + .input('minmultiplier', 1) + .input('customerGroupId', customerGroupId) + .input('net', netPrice) + .query(CREATE_PRICE); + + priceId = priceRes.recordset[0].id; + } + + const createdRes = await request(pool, tx) + .input('articleId', articleId) + .input('entityId', entityId) + .input('priceId', priceId) + .input('sku', supplierSku) + .input('stock', stock) + .input('pu', pu) + .query(CREATE_ARTICLE_SUPPLIER); + + const createdId = createdRes.recordset[0].id; + + await tx.commit(); + + const loadRes = await pool + .request() + .input('id', createdId) + .input('articleId', articleId) + .input('companyId', companyId) + .query(GET_BY_ID_AND_ARTICLE_ID); + + return shapeArticleSupplier(loadRes.recordset[0]); + } catch (err) { + try { + await tx.rollback(); + } catch { + // ignore + } + throw err; + } + }; +} diff --git a/src/store/articlesupplier/delete.js b/src/store/articlesupplier/delete.js new file mode 100644 index 0000000..2f6383c --- /dev/null +++ b/src/store/articlesupplier/delete.js @@ -0,0 +1,69 @@ +import { + DELETE_BY_ID_AND_ARTICLE_ID, + DELETE_PRICE, + GET_BY_ID_AND_ARTICLE_ID, +} from '../../sql/articlesupplier.js'; +import request from '../request.js'; +import resolveArticleBySku from '../article/resolveArticleBySku.js'; + +export default function del(pool) { + const resolve = resolveArticleBySku(pool); + + /** + * Deletes a supplier assignment and cleans up its associated purchase price. + * + * @param {number} googleAuthId - The id of the Google auth user. + * @param {string} sku - The article SKU. + * @param {number} id - The id of the articlesupplier record. + * @returns {Promise} + * @throws {Error} If the supplier assignment is not found. + * + * @example + * await store.articlesupplier.delete(42, 'SKU-1', 12); + */ + return async (googleAuthId, sku, id) => { + if (id == null || !Number.isFinite(id)) { + throw new Error('Supplier assignment not found'); + } + + const { articleId, companyId } = await resolve(googleAuthId, sku); + + const existingRes = await pool + .request() + .input('id', id) + .input('articleId', articleId) + .input('companyId', companyId) + .query(GET_BY_ID_AND_ARTICLE_ID); + + const existing = existingRes.recordset[0]; + if (!existing) { + throw new Error('Supplier assignment not found'); + } + + const tx = pool.transaction(); + await tx.begin(); + + try { + await request(pool, tx) + .input('id', id) + .input('articleId', articleId) + .query(DELETE_BY_ID_AND_ARTICLE_ID); + + if (existing.priceId != null) { + await request(pool, tx) + .input('id', existing.priceId) + .input('articleId', articleId) + .query(DELETE_PRICE); + } + + await tx.commit(); + } catch (err) { + try { + await tx.rollback(); + } catch { + // ignore + } + throw err; + } + }; +} diff --git a/src/store/articlesupplier/helpers.js b/src/store/articlesupplier/helpers.js new file mode 100644 index 0000000..6d53cff --- /dev/null +++ b/src/store/articlesupplier/helpers.js @@ -0,0 +1,54 @@ +import { GET_SUPPLIER_BY_ID, SUPPLIER_GROUP_NAME } from '../../sql/entity.js'; +import { GET_COMPANY_DEFAULT_TAX } from '../../sql/articlesupplier.js'; +import request from '../request.js'; + +export function optionalString(value) { + if (value == null || value === '') return null; + const s = String(value).trim(); + return s || null; +} + +export function shapeArticleSupplier(row) { + return { + id: row.id, + articleId: row.articleId, + entityId: row.entityId, + supplierName: row.supplierName ?? null, + sku: row.sku ?? null, + pu: row.pu, + stock: row.stock ?? null, + priceId: row.priceId ?? null, + price: + row.priceId != null && row.priceNet != null + ? { + net: row.priceNet, + taxId: row.priceTaxId, + ...(row.priceTaxRate != null ? { taxRate: row.priceTaxRate } : {}), + } + : null, + }; +} + +export async function assertSupplier(pool, tx, companyId, supplierId) { + if (supplierId == null || !Number.isFinite(supplierId)) { + throw new Error('Supplier not found'); + } + + const result = await request(pool, tx) + .input('id', supplierId) + .input('companyId', companyId) + .input('groupName', SUPPLIER_GROUP_NAME) + .query(GET_SUPPLIER_BY_ID); + + if (!result.recordset[0]) { + throw new Error('Supplier not found'); + } + return supplierId; +} + +export async function resolveCompanyDefaultTax(pool, tx, companyId) { + const result = await request(pool, tx) + .input('companyId', companyId) + .query(GET_COMPANY_DEFAULT_TAX); + return result.recordset[0]?.taxrate ?? null; +} diff --git a/src/store/articlesupplier/listByArticleSku.js b/src/store/articlesupplier/listByArticleSku.js new file mode 100644 index 0000000..551e6fa --- /dev/null +++ b/src/store/articlesupplier/listByArticleSku.js @@ -0,0 +1,31 @@ +import { LIST_BY_ARTICLE_ID } from '../../sql/articlesupplier.js'; +import resolveArticleBySku from '../article/resolveArticleBySku.js'; +import { shapeArticleSupplier } from './helpers.js'; + +export default function listByArticleSku(pool) { + const resolve = resolveArticleBySku(pool); + + /** + * Lists the supplier assignments for an article by its SKU. + * + * @param {number} googleAuthId - The id of the Google auth user. + * @param {string} sku - The article SKU. + * @returns {Promise>} The supplier assignments. + * @throws {Error} If the article is not found or the user is not authorized. + * + * @example + * const suppliers = await store.articlesupplier.listByArticleSku(42, 'SKU-1'); + * // => [{ id, articleId, entityId, supplierName, sku, pu, stock, priceId, price }] + */ + return async (googleAuthId, sku) => { + const { articleId, companyId } = await resolve(googleAuthId, sku); + + const result = await pool + .request() + .input('articleId', articleId) + .input('companyId', companyId) + .query(LIST_BY_ARTICLE_ID); + + return result.recordset.map(shapeArticleSupplier); + }; +} diff --git a/src/store/articlesupplier/update.js b/src/store/articlesupplier/update.js new file mode 100644 index 0000000..0b1e991 --- /dev/null +++ b/src/store/articlesupplier/update.js @@ -0,0 +1,200 @@ +import { + DELETE_PRICE, + GET_BY_ID_AND_ARTICLE_ID, + UPDATE as UPDATE_ARTICLE_SUPPLIER, + UPDATE_PRICE, +} from '../../sql/articlesupplier.js'; +import { CREATE as CREATE_PRICE } from '../../sql/price.js'; +import request from '../request.js'; +import resolveArticleBySku from '../article/resolveArticleBySku.js'; +import ensureLieferantenGroup from '../supplier/ensureLieferantenGroup.js'; +import taxEnsure from '../tax/ensure.js'; +import { + optionalString, + resolveCompanyDefaultTax, + shapeArticleSupplier, +} from './helpers.js'; + +export default function update(pool) { + const resolve = resolveArticleBySku(pool); + const ensureTax = taxEnsure(pool); + + /** + * Updates an existing supplier assignment and its associated purchase price. + * + * @param {number} googleAuthId - The id of the Google auth user. + * @param {string} sku - The article SKU. + * @param {number} id - The id of the articlesupplier record. + * @param {object} patch - The fields to update. + * @param {string|null} [patch.sku] - The supplier's item number/SKU. + * @param {number} [patch.pu] - Packaging unit (> 0). + * @param {number|null} [patch.stock] - Current stock at the supplier. + * @param {number|null} [patch.netPrice] - Net purchase price. + * @param {number} [patch.taxId] - The tax id for the purchase price. + * @param {number} [patch.taxRate] - The tax rate in percent. + * @returns {Promise<{id: number, articleId: number, entityId: number, supplierName: string|null, sku: string|null, pu: number, stock: number|null, priceId: number|null, price: {net: number, taxId: number, taxRate?: number}|null}>} The updated assignment. + * @throws {Error} If input is invalid or supplier assignment is not found. + * + * @example + * const updated = await store.articlesupplier.update(42, 'SKU-1', 12, { + * sku: 'MET-44910-B', + * pu: 6, + * netPrice: 22.50, + * }); + * // => { id, articleId, entityId, supplierName, sku, pu, stock, priceId, price } + */ + return async (googleAuthId, sku, id, patch = {}) => { + if (id == null || !Number.isFinite(id)) { + throw new Error('Supplier assignment not found'); + } + + if (patch.pu !== undefined) { + if (!Number.isFinite(patch.pu) || patch.pu <= 0) { + throw new Error('Invalid pu'); + } + } + + if (patch.stock !== undefined && patch.stock !== null) { + if (!Number.isFinite(patch.stock)) { + throw new Error('Invalid stock'); + } + } + + if (patch.netPrice !== undefined && patch.netPrice !== null) { + if (!Number.isFinite(patch.netPrice)) { + throw new Error('Invalid price'); + } + } + + const { articleId, companyId } = await resolve(googleAuthId, sku); + + const existingRes = await pool + .request() + .input('id', id) + .input('articleId', articleId) + .input('companyId', companyId) + .query(GET_BY_ID_AND_ARTICLE_ID); + + const existing = existingRes.recordset[0]; + if (!existing) { + throw new Error('Supplier assignment not found'); + } + + const tx = pool.transaction(); + await tx.begin(); + + try { + let priceId = existing.priceId; + + if (patch.netPrice !== undefined) { + if (patch.netPrice === null) { + if (priceId != null) { + const oldPriceId = priceId; + priceId = null; + + await request(pool, tx) + .input('id', id) + .input('articleId', articleId) + .input('sku', existing.sku) + .input('stock', existing.stock) + .input('pu', existing.pu) + .input('priceId', null) + .query(UPDATE_ARTICLE_SUPPLIER); + + await request(pool, tx) + .input('id', oldPriceId) + .input('articleId', articleId) + .query(DELETE_PRICE); + } + } else { + // netPrice is a valid number + if (priceId != null) { + let taxId = patch.taxId; + if (taxId == null || !Number.isFinite(taxId)) { + if (patch.taxRate != null && Number.isFinite(patch.taxRate)) { + taxId = await ensureTax(patch.taxRate, tx); + } else { + taxId = existing.priceTaxId; + } + } + + await request(pool, tx) + .input('id', priceId) + .input('articleId', articleId) + .input('net', patch.netPrice) + .input('taxId', taxId) + .query(UPDATE_PRICE); + } else { + // create new price row + let taxId = patch.taxId; + if (taxId == null || !Number.isFinite(taxId)) { + if (patch.taxRate != null && Number.isFinite(patch.taxRate)) { + taxId = await ensureTax(patch.taxRate, tx); + } else { + const defaultTaxId = await resolveCompanyDefaultTax( + pool, + tx, + companyId, + ); + taxId = defaultTaxId != null ? defaultTaxId : await ensureTax(0, tx); + } + } + + const customerGroupId = await ensureLieferantenGroup( + pool, + companyId, + tx, + ); + + const priceRes = await request(pool, tx) + .input('taxId', taxId) + .input('articleId', articleId) + .input('minmultiplier', 1) + .input('customerGroupId', customerGroupId) + .input('net', patch.netPrice) + .query(CREATE_PRICE); + + priceId = priceRes.recordset[0].id; + } + } + } + + const nextSku = + patch.sku !== undefined ? optionalString(patch.sku) : existing.sku; + const nextStock = + patch.stock !== undefined + ? patch.stock === null + ? null + : patch.stock + : existing.stock; + const nextPu = patch.pu !== undefined ? patch.pu : existing.pu; + + await request(pool, tx) + .input('id', id) + .input('articleId', articleId) + .input('sku', nextSku) + .input('stock', nextStock) + .input('pu', nextPu) + .input('priceId', priceId) + .query(UPDATE_ARTICLE_SUPPLIER); + + await tx.commit(); + + const loadRes = await pool + .request() + .input('id', id) + .input('articleId', articleId) + .input('companyId', companyId) + .query(GET_BY_ID_AND_ARTICLE_ID); + + return shapeArticleSupplier(loadRes.recordset[0]); + } catch (err) { + try { + await tx.rollback(); + } catch { + // ignore + } + throw err; + } + }; +}