import * as mssqlQueries from '../../providers/mssql/queries/optionslist.js'; import * as sqliteQueries from '../../providers/sqlite3/queries/optionslist.js'; import resolveArticleBySku from '../article/resolveArticleBySku.js'; import getOptionsByArticleSku from './getOptionsByArticleSku.js'; import { recordOptionsListChangeHistory, recordArticleHistory, } from '../articlehistory/record.js'; import makeRunner from '../runner.js'; async function hasOptionslistCycle(runner, rootArticleId, candidateOptionId) { const visited = new Set(); const queue = [candidateOptionId]; while (queue.length > 0) { const currentId = queue.shift(); if (currentId === rootArticleId) { return true; } if (visited.has(currentId)) continue; visited.add(currentId); const res = await runner.query( `SELECT ola.article_id FROM article a INNER JOIN optionslistarticle ola ON ola.optionslist_id = a.optionslist_id WHERE a.id = @currentId`, { currentId }, ); for (const row of res.rows) { if (row.article_id === rootArticleId) { return true; } if (!visited.has(row.article_id)) { queue.push(row.article_id); } } } return false; } export default function setOptionsByArticleSku(provider) { const resolve = resolveArticleBySku(provider); const getOptions = getOptionsByArticleSku(provider); const isSqlite = provider?.dialect === 'sqlite3'; const queries = isSqlite ? sqliteQueries : mssqlQueries; /** * Sets or clears the options list for an article. * * @param {number} googleAuthId - The id of the Google auth user. * @param {string} sku - The master article SKU. * @param {Array<{articleId?: number, sku?: string, count?: number, sort?: number, mandated?: boolean}>} [options=[]] - Array of options items. * @param {object} [tx] - Optional transaction. * @returns {Promise>} */ return async (googleAuthId, sku, options = [], tx) => { if (!Array.isArray(options)) { throw new Error('Invalid options array'); } const run = async (runner) => { const { articleId, companyId, companyuserId } = await resolve(googleAuthId, sku, runner); const artRes = await runner.query( 'SELECT id, is_parent, articlelist_id, optionslist_id FROM article WHERE id = @articleId', { articleId }, ); const article = artRes.rows[0]; if (!article) { throw new Error('Article not found'); } if (article.is_parent) { throw new Error('A parent article cannot have options'); } // If options is empty: clear optionslist if (options.length === 0) { if (article.optionslist_id != null) { // Read old options for history before clearing const oldOptRes = await runner.query( `SELECT a.sku, at.name FROM optionslistarticle ola INNER JOIN article a ON a.id = ola.article_id LEFT JOIN articletext at ON at.article_id = a.id WHERE ola.optionslist_id = @optionslistId ORDER BY ola.sort ASC, ola.id ASC`, { optionslistId: article.optionslist_id }, ); const oldOptNames = oldOptRes.rows.map((r) => r.name || r.sku); await runner.query(queries.SET_ARTICLE_OPTIONSLIST_ID, { articleId, optionslistId: null, }); await runner.query(queries.DELETE_OPTIONSLIST, { id: article.optionslist_id, }); if (oldOptNames.length) { await recordArticleHistory(runner, { articleId, companyuserId, text: `Optionsliste geleert (war: [${oldOptNames.join(', ')}])`, type: 'optionslist_cleared', }); } } return []; } // Validate options const validated = []; const seenArticleIds = new Set(); const seenSorts = new Set(); for (let i = 0; i < options.length; i++) { const item = options[i]; if (!item || typeof item !== 'object') { throw new Error(`Option at index ${i} must be an object`); } 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`); } if (itemArticleId === articleId || await hasOptionslistCycle(runner, articleId, itemArticleId)) { throw new Error('An article cannot have itself as an option or form a circular reference in options'); } if (seenArticleIds.has(itemArticleId)) { throw new Error(`Duplicate article in options: ${itemArticleId}`); } seenArticleIds.add(itemArticleId); const rawCount = item?.count === undefined ? 1 : item.count; if ( typeof rawCount !== 'number' || !Number.isInteger(rawCount) || rawCount <= 0 || rawCount > 2147483647 ) { throw new Error(`Invalid count for options item at index ${i}: must be a positive integer`); } const count = rawCount; 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({ articleId: itemArticleId, count, sort, mandated, }); } let targetListId = article.optionslist_id; if (targetListId == null) { const listRes = await runner.query(queries.CREATE_OPTIONSLIST); targetListId = listRes.rows[0]?.id ?? listRes.insertId; await runner.query(queries.SET_ARTICLE_OPTIONSLIST_ID, { articleId, optionslistId: targetListId, }); } else { await runner.query(queries.DELETE_OPTIONSLIST_ARTICLES, { optionslistId: targetListId, }); } for (const val of validated) { await runner.query(queries.INSERT_OPTIONSLIST_ARTICLE, { optionslistId: targetListId, articleId: val.articleId, count: val.count, sort: val.sort, mandated: val.mandated ? 1 : 0, }); } const result = await getOptions(googleAuthId, sku, runner); // Write history for options list change await recordOptionsListChangeHistory(runner, { articleId, companyuserId, options: result, }); return result; }; if (tx) { return run(makeRunner(provider, tx)); } if (typeof provider?.transaction === 'function') { return provider.transaction(run); } return run(makeRunner(provider)); }; }