feat(articlesupplier): add sort column, reorder method, and update queries and schema
This commit is contained in:
84
src/store/articlesupplier/order.js
Normal file
84
src/store/articlesupplier/order.js
Normal file
@@ -0,0 +1,84 @@
|
||||
import {
|
||||
LIST_IDS_BY_ARTICLE,
|
||||
SET_TEMP_SORTS,
|
||||
UPDATE_SORT,
|
||||
} from '../../sql/articlesupplier.js';
|
||||
import request from '../request.js';
|
||||
import resolveArticleBySku from '../article/resolveArticleBySku.js';
|
||||
|
||||
export default function order(pool) {
|
||||
const resolve = resolveArticleBySku(pool);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @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 } = {}) => {
|
||||
if (!Array.isArray(ids)) {
|
||||
throw new Error('Invalid supplier order');
|
||||
}
|
||||
|
||||
const { articleId } = await resolve(googleAuthId, sku);
|
||||
|
||||
const current = await pool
|
||||
.request()
|
||||
.input('articleId', articleId)
|
||||
.query(LIST_IDS_BY_ARTICLE);
|
||||
|
||||
const existing = new Set(current.recordset.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);
|
||||
}
|
||||
|
||||
const tx = pool.transaction();
|
||||
await tx.begin();
|
||||
|
||||
try {
|
||||
await request(pool, tx)
|
||||
.input('articleId', articleId)
|
||||
.query(SET_TEMP_SORTS);
|
||||
|
||||
for (let sort = 0; sort < ids.length; sort++) {
|
||||
const updateRes = await request(pool, tx)
|
||||
.input('id', ids[sort])
|
||||
.input('articleId', articleId)
|
||||
.input('sort', sort)
|
||||
.query(UPDATE_SORT);
|
||||
|
||||
if (!updateRes.rowsAffected[0]) {
|
||||
throw new Error('Invalid supplier order');
|
||||
}
|
||||
}
|
||||
|
||||
await tx.commit();
|
||||
|
||||
return { ids };
|
||||
} catch (err) {
|
||||
try {
|
||||
await tx.rollback();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user