This commit is contained in:
seb
2026-09-30 23:11:04 +02:00
parent 74ed74fc68
commit 9c770d765e
8 changed files with 202 additions and 56 deletions

View File

@@ -4,6 +4,8 @@ import { GET_CHILD_COUNT as MSSQL_GET_CHILD_COUNT } from '../../providers/mssql/
import { GET_CHILD_COUNT as SQLITE_GET_CHILD_COUNT } from '../../providers/sqlite3/queries/articleDelete.js';
import * as mssqlAttr from '../../providers/mssql/queries/attributename.js';
import * as sqliteAttr from '../../providers/sqlite3/queries/attributename.js';
import { INSERT as MSSQL_INSERT_HISTORY } from '../../providers/mssql/queries/articlehistory.js';
import { INSERT as SQLITE_INSERT_HISTORY } from '../../providers/sqlite3/queries/articlehistory.js';
import resolveArticleBySku from './resolveArticleBySku.js';
import getBySku from './getBySku.js';
import makeRunner from '../runner.js';
@@ -16,6 +18,7 @@ export default function toggleFather(provider) {
const queries = isSqlite ? sqliteArticle : mssqlArticle;
const getChildCountSql = isSqlite ? SQLITE_GET_CHILD_COUNT : MSSQL_GET_CHILD_COUNT;
const attrQueries = isSqlite ? sqliteAttr : mssqlAttr;
const insertHistorySql = isSqlite ? SQLITE_INSERT_HISTORY : MSSQL_INSERT_HISTORY;
/**
* Toggles an article into or out of father mode.
@@ -31,7 +34,7 @@ export default function toggleFather(provider) {
*/
return async (googleAuthId, sku, { isFather, attributeNameId, fatherAttributeNameId } = {}, tx) => {
const run = async (runner) => {
const { articleId, companyId } = await resolve(googleAuthId, sku, runner);
const { articleId, companyId, companyuserId } = await resolve(googleAuthId, sku, runner);
const targetIsFather = Boolean(isFather);
const targetAttrId = attributeNameId ?? fatherAttributeNameId;
@@ -78,6 +81,18 @@ export default function toggleFather(provider) {
throw new Error('An article with assigned suppliers cannot become a father article');
}
// Fetch existing prices before deletion to record in articlehistory
const existingPricesRes = await runner.query(
`SELECT pr.net, pr.minmultiplier, t.rate AS taxRate, cg.name AS customerGroupName
FROM price pr
LEFT JOIN tax t ON t.id = pr.tax_id
LEFT JOIN customergroup cg ON cg.id = pr.customergroup_id
WHERE pr.article_id = @articleId
ORDER BY pr.customergroup_id, pr.minmultiplier`,
{ articleId },
);
const existingPrices = existingPricesRes.rows;
await runner.query('DELETE FROM price WHERE article_id = @articleId', { articleId });
await runner.query('UPDATE article SET track_stock = 0 WHERE id = @articleId', { articleId });
@@ -107,6 +122,7 @@ export default function toggleFather(provider) {
if (!attrRes.rows[0]) {
throw new Error('Attribute name not found');
}
const attributeName = attrRes.rows[0].name;
// Verify article does not have an attribute value for this attribute
const existingValRes = await runner.query(
@@ -124,6 +140,35 @@ export default function toggleFather(provider) {
isFather: 1,
fatherAttributeNameId: Number(targetAttrId),
});
// Add history entry recording father conversion and deleted prices
const historyLines = [
`Artikel zu Vaterartikel konvertiert (Varianten-Attribut: "${attributeName}")`,
];
if (existingPrices.length > 0) {
const priceParts = existingPrices.map((p) => {
let str = `${p.net} €`;
if (p.taxRate != null) {
str += ` (${p.taxRate}% MwSt.)`;
}
if (p.minmultiplier > 1) {
str += ` ab ${p.minmultiplier} Stk.`;
}
if (p.customerGroupName) {
str += ` [${p.customerGroupName}]`;
}
return str;
});
const label = existingPrices.length === 1 ? 'Bisheriger Preis gelöscht' : 'Bisherige Preise gelöscht';
historyLines.push(`${label}: ${priceParts.join(', ')}`);
}
await runner.query(insertHistorySql, {
articleId,
companyuserId,
text: historyLines.join('\n'),
});
} else {
// Disabling father: verify zero children
const childCountRes = await runner.query(getChildCountSql, { articleId });
@@ -137,6 +182,12 @@ export default function toggleFather(provider) {
isFather: 0,
fatherAttributeNameId: null,
});
await runner.query(insertHistorySql, {
articleId,
companyuserId,
text: 'Vaterartikel-Modus deaktiviert',
});
}
return load(googleAuthId, sku, runner);

View File

@@ -94,17 +94,42 @@ export default function setItemsByArticleSku(provider) {
for (let i = 0; i < items.length; i++) {
const item = items[i];
let itemArticleId = item?.articleId != null ? Number(item.articleId) : null;
if (itemArticleId == null && item?.sku) {
const res = await runner.query(
'SELECT id FROM article WHERE sku = @itemSku AND company_id = @companyId',
{ itemSku: item.sku, companyId },
);
itemArticleId = res.rows[0]?.id;
if (!item || typeof item !== 'object') {
throw new Error(`Item at index ${i} must be an object`);
}
if (!itemArticleId || Number.isNaN(itemArticleId) || itemArticleId <= 0) {
let itemArticleId = null;
if (item.articleId !== undefined && item.articleId !== null) {
if (
typeof item.articleId !== 'number' ||
!Number.isInteger(item.articleId) ||
item.articleId <= 0
) {
throw new Error(`Item at index ${i} must specify a valid articleId or sku`);
}
const res = await runner.query(
'SELECT id FROM article WHERE id = @itemArticleId AND company_id = @companyId',
{ itemArticleId: item.articleId, companyId },
);
if (!res.rows[0]) {
throw new Error(`Article not found for component: ${item.articleId}`);
}
itemArticleId = res.rows[0].id;
} else if (item.sku !== undefined && item.sku !== null) {
if (typeof item.sku !== 'string' || !item.sku.trim()) {
throw new Error(`Item at index ${i} must specify a valid articleId or sku`);
}
const itemSku = item.sku.trim();
const res = await runner.query(
'SELECT id FROM article WHERE sku = @itemSku AND company_id = @companyId',
{ itemSku, companyId },
);
if (!res.rows[0]) {
throw new Error(`Article not found for component: ${itemSku}`);
}
itemArticleId = res.rows[0].id;
} else {
throw new Error(`Item at index ${i} must specify a valid articleId or sku`);
}
@@ -117,16 +142,7 @@ export default function setItemsByArticleSku(provider) {
}
seenArticleIds.add(itemArticleId);
// Verify component article exists in same company
const itemArtRes = await runner.query(
'SELECT id FROM article WHERE id = @itemArticleId AND company_id = @companyId',
{ itemArticleId, companyId },
);
if (!itemArtRes.rows[0]) {
throw new Error(`Article not found for component: ${itemArticleId}`);
}
const rawCount = item?.count;
const rawCount = item?.count === undefined ? 1 : item.count;
if (
typeof rawCount !== 'number' ||
!Number.isInteger(rawCount) ||
@@ -136,7 +152,13 @@ export default function setItemsByArticleSku(provider) {
throw new Error(`Invalid count for Stückliste item at index ${i}: must be a positive integer`);
}
const count = rawCount;
let sort = item?.sort != null && Number.isInteger(Number(item.sort)) ? Number(item.sort) : i;
if (item.sort !== undefined && item.sort !== null) {
if (typeof item.sort !== 'number' || !Number.isInteger(item.sort)) {
throw new Error(`Invalid sort for Stückliste item at index ${i}: must be an integer`);
}
}
let sort = (typeof item?.sort === 'number' && Number.isInteger(item.sort)) ? item.sort : i;
while (seenSorts.has(sort)) {
sort++;

View File

@@ -15,18 +15,63 @@ export default function del(provider) {
* @param {number} input.id - The id of the category to delete.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<void>}
* @throws {Error} If the category is the root category.
* @throws {Error} If the category is the root category or contains articles/subcategories.
*
* @example
* await store.category.delete({ googleAuthId: 42, id: 5 });
*/
return async ({ googleAuthId, id }, tx) => {
const { rootCategoryId } = await access(googleAuthId, id, tx);
const run = async (runner) => {
const { rootCategoryId } = await access(googleAuthId, id, runner);
if (id === rootCategoryId) {
throw new Error('Cannot delete root category');
if (id === rootCategoryId) {
throw new Error('Cannot delete root category');
}
const childRes = await runner.query(
'SELECT id FROM category WHERE parent_id = @id',
{ id },
);
if (childRes.rows?.length > 0) {
throw new Error('Category has subcategories');
}
const artRes = await runner.query(
'SELECT article_id FROM categoryarticle WHERE category_id = @id',
{ id },
);
if (artRes.rows?.length > 0) {
throw new Error('Category has articles');
}
const posRes = await runner.query(
'SELECT posterminal_id FROM posterminalcategory WHERE category_id = @id',
{ id },
);
if (posRes.rows?.length > 0) {
throw new Error('Category is assigned to POS terminals');
}
try {
await runner.query(sql, { id });
} catch (err) {
if (
err.message?.includes('FOREIGN KEY constraint failed') ||
err.message?.includes('foreign key constraint') ||
err.message?.includes('REFERENCE constraint')
) {
throw new Error('Category has articles');
}
throw err;
}
};
if (tx) {
return run(makeRunner(provider, tx));
}
await makeRunner(provider, tx).query(sql, { id });
if (typeof provider?.transaction === 'function') {
return provider.transaction(run);
}
return run(makeRunner(provider));
};
}

View File

@@ -94,17 +94,42 @@ export default function setOptionsByArticleSku(provider) {
for (let i = 0; i < options.length; i++) {
const item = options[i];
let itemArticleId = item?.articleId != null ? Number(item.articleId) : null;
if (itemArticleId == null && item?.sku) {
const res = await runner.query(
'SELECT id FROM article WHERE sku = @itemSku AND company_id = @companyId',
{ itemSku: item.sku, companyId },
);
itemArticleId = res.rows[0]?.id;
if (!item || typeof item !== 'object') {
throw new Error(`Option at index ${i} must be an object`);
}
if (!itemArticleId || Number.isNaN(itemArticleId) || itemArticleId <= 0) {
let itemArticleId = null;
if (item.articleId !== undefined && item.articleId !== null) {
if (
typeof item.articleId !== 'number' ||
!Number.isInteger(item.articleId) ||
item.articleId <= 0
) {
throw new Error(`Option at index ${i} must specify a valid articleId or sku`);
}
const res = await runner.query(
'SELECT id FROM article WHERE id = @itemArticleId AND company_id = @companyId',
{ itemArticleId: item.articleId, companyId },
);
if (!res.rows[0]) {
throw new Error(`Article not found for option: ${item.articleId}`);
}
itemArticleId = res.rows[0].id;
} else if (item.sku !== undefined && item.sku !== null) {
if (typeof item.sku !== 'string' || !item.sku.trim()) {
throw new Error(`Option at index ${i} must specify a valid articleId or sku`);
}
const itemSku = item.sku.trim();
const res = await runner.query(
'SELECT id FROM article WHERE sku = @itemSku AND company_id = @companyId',
{ itemSku, companyId },
);
if (!res.rows[0]) {
throw new Error(`Article not found for option: ${itemSku}`);
}
itemArticleId = res.rows[0].id;
} else {
throw new Error(`Option at index ${i} must specify a valid articleId or sku`);
}
@@ -117,16 +142,7 @@ export default function setOptionsByArticleSku(provider) {
}
seenArticleIds.add(itemArticleId);
// Verify component article exists in same company
const itemArtRes = await runner.query(
'SELECT id FROM article WHERE id = @itemArticleId AND company_id = @companyId',
{ itemArticleId, companyId },
);
if (!itemArtRes.rows[0]) {
throw new Error(`Article not found for option: ${itemArticleId}`);
}
const rawCount = item?.count;
const rawCount = item?.count === undefined ? 1 : item.count;
if (
typeof rawCount !== 'number' ||
!Number.isInteger(rawCount) ||
@@ -136,13 +152,22 @@ export default function setOptionsByArticleSku(provider) {
throw new Error(`Invalid count for options item at index ${i}: must be a positive integer`);
}
const count = rawCount;
let sort = item?.sort != null && Number.isInteger(Number(item.sort)) ? Number(item.sort) : i;
if (item.sort !== undefined && item.sort !== null) {
if (typeof item.sort !== 'number' || !Number.isInteger(item.sort)) {
throw new Error(`Invalid sort for options item at index ${i}: must be an integer`);
}
}
let sort = (typeof item?.sort === 'number' && Number.isInteger(item.sort)) ? item.sort : i;
while (seenSorts.has(sort)) {
sort++;
}
seenSorts.add(sort);
if (item.mandated !== undefined && item.mandated !== null && typeof item.mandated !== 'boolean') {
throw new Error(`Invalid mandated for options item at index ${i}: must be a boolean`);
}
const mandated = Boolean(item?.mandated);
validated.push({