feat(articlesupplier): implement store methods, schema constraints, and embed in getBySku
This commit is contained in:
11
src/index.js
11
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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
91
src/sql/articlesupplier.js
Normal file
91
src/sql/articlesupplier.js
Normal file
@@ -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;
|
||||
`;
|
||||
@@ -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,
|
||||
|
||||
156
src/store/articlesupplier/create.js
Normal file
156
src/store/articlesupplier/create.js
Normal file
@@ -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;
|
||||
}
|
||||
};
|
||||
}
|
||||
69
src/store/articlesupplier/delete.js
Normal file
69
src/store/articlesupplier/delete.js
Normal file
@@ -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<void>}
|
||||
* @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;
|
||||
}
|
||||
};
|
||||
}
|
||||
54
src/store/articlesupplier/helpers.js
Normal file
54
src/store/articlesupplier/helpers.js
Normal file
@@ -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;
|
||||
}
|
||||
31
src/store/articlesupplier/listByArticleSku.js
Normal file
31
src/store/articlesupplier/listByArticleSku.js
Normal file
@@ -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<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}>>} 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);
|
||||
};
|
||||
}
|
||||
200
src/store/articlesupplier/update.js
Normal file
200
src/store/articlesupplier/update.js
Normal file
@@ -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;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user