Files
dashlibstorage/src/store/articlesupplier/order.js
2026-09-22 07:25:16 +02:00

81 lines
2.5 KiB
JavaScript

import * as mssqlQueries from '../../providers/mssql/queries/articlesupplier.js';
import * as sqliteQueries from '../../providers/sqlite3/queries/articlesupplier.js';
import resolveArticleBySku from '../article/resolveArticleBySku.js';
import makeRunner from '../runner.js';
export default function order(provider) {
const resolve = resolveArticleBySku(provider);
const isSqlite = provider?.dialect === 'sqlite3';
const queries = isSqlite ? sqliteQueries : mssqlQueries;
/**
* Reorders the supplier assignments of an article by its SKU.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {string} sku - The article SKU.
* @param {object} input - The reorder input.
* @param {Array<number>} input.ids - The articlesupplier ids in their new order.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{ids: Array<number>}>} The applied order.
* @throws {Error} If the order is invalid.
*
* @example
* const result = await store.articlesupplier.order(42, 'SKU-1', { ids: [12, 10, 15] });
* // => { ids: [12, 10, 15] }
*/
return async (googleAuthId, sku, { ids } = {}, tx) => {
if (!Array.isArray(ids)) {
throw new Error('Invalid supplier order');
}
const runOrder = async (runner) => {
const { articleId } = await resolve(googleAuthId, sku, runner);
const current = await runner.query(queries.LIST_IDS_BY_ARTICLE, {
articleId,
});
const existing = new Set(current.rows.map((r) => r.id));
if (ids.length !== existing.size) {
throw new Error('Invalid supplier order');
}
const seen = new Set();
for (const id of ids) {
if (!Number.isFinite(id) || !existing.has(id) || seen.has(id)) {
throw new Error('Invalid supplier order');
}
seen.add(id);
}
await runner.query(queries.SET_TEMP_SORTS, {
articleId,
});
for (let sort = 0; sort < ids.length; sort++) {
const updateRes = await runner.query(queries.UPDATE_SORT, {
id: ids[sort],
articleId,
sort,
});
if (!updateRes.rowsAffected) {
throw new Error('Invalid supplier order');
}
}
return { ids };
};
if (tx) {
return runOrder(makeRunner(provider, tx));
}
if (typeof provider?.transaction === 'function') {
return provider.transaction(runOrder);
}
return runOrder(makeRunner(provider));
};
}