186 lines
7.8 KiB
JavaScript
186 lines
7.8 KiB
JavaScript
import * as mssqlArticle from '../../providers/mssql/queries/article.js';
|
|
import * as sqliteArticle from '../../providers/sqlite3/queries/article.js';
|
|
import { GET_CHILD_COUNT as MSSQL_GET_CHILD_COUNT } from '../../providers/mssql/queries/articleDelete.js';
|
|
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 resolveArticleBySku from './resolveArticleBySku.js';
|
|
import getBySku from './getBySku.js';
|
|
import {
|
|
recordParentConvertedHistory,
|
|
recordParentDeactivatedHistory,
|
|
} from '../articlehistory/record.js';
|
|
import makeRunner from '../runner.js';
|
|
import { removeArticleWarehouseSummary } from '../articlewarehousesummary/syncSummary.js';
|
|
|
|
export default function toggleParent(provider) {
|
|
const resolve = resolveArticleBySku(provider);
|
|
const load = getBySku(provider);
|
|
const isSqlite = provider?.dialect === 'sqlite3';
|
|
|
|
const queries = isSqlite ? sqliteArticle : mssqlArticle;
|
|
const getChildCountSql = isSqlite ? SQLITE_GET_CHILD_COUNT : MSSQL_GET_CHILD_COUNT;
|
|
const attrQueries = isSqlite ? sqliteAttr : mssqlAttr;
|
|
|
|
/**
|
|
* Toggles an article into or out of parent mode.
|
|
*
|
|
* @param {number} googleAuthId - The id of the Google auth user.
|
|
* @param {string} sku - The article SKU.
|
|
* @param {object} options
|
|
* @param {boolean} options.isParent - Whether the article should be a parent article.
|
|
* @param {number} [options.attributeNameId] - The attribute name id required when enabling parent mode.
|
|
* @param {number} [options.parentAttributeNameId] - Alias for attributeNameId.
|
|
* @param {object} [tx] - Optional transaction.
|
|
* @returns {Promise<object>} The updated article detail.
|
|
*/
|
|
return async (googleAuthId, sku, { isParent, attributeNameId, parentAttributeNameId } = {}, tx) => {
|
|
const run = async (runner) => {
|
|
const { articleId, companyId, companyuserId } = await resolve(googleAuthId, sku, runner);
|
|
|
|
const targetIsParent = Boolean(isParent);
|
|
const targetAttrId = attributeNameId ?? parentAttributeNameId;
|
|
|
|
if (targetIsParent) {
|
|
if (!targetAttrId || Number(targetAttrId) <= 0) {
|
|
throw new Error('attributeNameId is required to become a parent article');
|
|
}
|
|
|
|
const currentRes = await runner.query(
|
|
'SELECT parentarticle_id, articlelist_id, optionslist_id FROM article WHERE id = @articleId',
|
|
{ articleId },
|
|
);
|
|
const currentArt = currentRes.rows[0];
|
|
if (currentArt?.articlelist_id != null) {
|
|
throw new Error('A Stückliste article cannot become a parent');
|
|
}
|
|
if (currentArt?.optionslist_id != null) {
|
|
throw new Error('An article with options cannot become a parent');
|
|
}
|
|
|
|
const stockRes = await runner.query(
|
|
`SELECT COALESCE(SUM(l.amount), 0) AS totalStock
|
|
FROM ledger l
|
|
INNER JOIN manifestarticle ma ON ma.id = l.manifestarticle_id
|
|
INNER JOIN manifest m ON m.id = ma.manifest_id
|
|
WHERE m.company_id = @companyId
|
|
AND (
|
|
ma.sku = @sku
|
|
OR ma.sku IN (SELECT asup.sku FROM articlesupplier asup WHERE asup.article_id = @articleId)
|
|
)`,
|
|
{ companyId, sku, articleId },
|
|
);
|
|
const totalStock = Number(stockRes.rows[0]?.totalStock ?? 0);
|
|
if (totalStock !== 0) {
|
|
throw new Error('An article with existing stock cannot become a parent article');
|
|
}
|
|
|
|
const supRes = await runner.query(
|
|
'SELECT COUNT(*) AS count FROM articlesupplier WHERE article_id = @articleId',
|
|
{ articleId },
|
|
);
|
|
if ((supRes.rows[0]?.count ?? 0) > 0) {
|
|
throw new Error('An article with assigned suppliers cannot become a parent 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 });
|
|
await removeArticleWarehouseSummary(runner, { articleId });
|
|
|
|
// If article is a child, verify attribute is not used by parent or any parent up the chain
|
|
let currentParentId = currentArt?.parentarticle_id;
|
|
const visited = new Set();
|
|
while (currentParentId != null && !visited.has(currentParentId)) {
|
|
visited.add(currentParentId);
|
|
const fRes = await runner.query(
|
|
'SELECT a.parentarticle_id, a.parentattributename_id, an.name AS parentAttributeName FROM article a LEFT JOIN attributename an ON an.id = a.parentattributename_id WHERE a.id = @currentParentId',
|
|
{ currentParentId },
|
|
);
|
|
const fRow = fRes.rows[0];
|
|
if (!fRow) break;
|
|
if (fRow.parentattributename_id != null && Number(fRow.parentattributename_id) === Number(targetAttrId)) {
|
|
const attrName = fRow.parentAttributeName || 'ancestor';
|
|
throw new Error(`Attribute "${attrName}" is already used by an ancestor parent article`);
|
|
}
|
|
currentParentId = fRow.parentarticle_id;
|
|
}
|
|
|
|
// Verify attribute exists and belongs to company
|
|
const attrRes = await runner.query(attrQueries.GET_BY_COMPANY_AND_ID, {
|
|
id: Number(targetAttrId),
|
|
companyId,
|
|
});
|
|
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(
|
|
`SELECT aav.id FROM articleattributevalue aav
|
|
INNER JOIN attributevalue av ON av.id = aav.attributevalue_id
|
|
WHERE aav.article_id = @articleId AND av.attribute_id = @attributeId`,
|
|
{ articleId, attributeId: Number(targetAttrId) },
|
|
);
|
|
if (existingValRes.rows.length > 0) {
|
|
throw new Error('A parent article cannot have attribute values for its variant attribute');
|
|
}
|
|
|
|
await runner.query(queries.TOGGLE_PARENT, {
|
|
articleId,
|
|
isParent: 1,
|
|
parentAttributeNameId: Number(targetAttrId),
|
|
});
|
|
|
|
// Add history entry recording parent conversion and deleted prices
|
|
await recordParentConvertedHistory(runner, {
|
|
articleId,
|
|
companyuserId,
|
|
attributeName,
|
|
existingPrices,
|
|
});
|
|
} else {
|
|
// Disabling parent: verify zero children
|
|
const childCountRes = await runner.query(getChildCountSql, { articleId });
|
|
const childCount = childCountRes.rows[0]?.count ?? 0;
|
|
if (childCount > 0) {
|
|
throw new Error('Cannot disable parent mode on an article that still has children');
|
|
}
|
|
|
|
await runner.query(queries.TOGGLE_PARENT, {
|
|
articleId,
|
|
isParent: 0,
|
|
parentAttributeNameId: null,
|
|
});
|
|
|
|
await recordParentDeactivatedHistory(runner, {
|
|
articleId,
|
|
companyuserId,
|
|
});
|
|
}
|
|
|
|
return load(googleAuthId, sku, runner);
|
|
};
|
|
|
|
if (tx) {
|
|
return run(makeRunner(provider, tx));
|
|
}
|
|
if (typeof provider?.transaction === 'function') {
|
|
return provider.transaction(run);
|
|
}
|
|
return run(makeRunner(provider));
|
|
};
|
|
}
|