import { LIST_IDS_BY_COMPANY, UPDATE_SORT, } from '../../sql/customergroup.js'; import request from '../request.js'; import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js'; export default function order(pool) { const access = resolveSelectedCompanyAccess(pool); /** * Reorders the customer groups of the user's selected company. * * @param {number} googleAuthId - The id of the Google auth user. * @param {object} input - The reorder input. * @param {Array} input.customergroupIds - The customer group ids in their new order. * @returns {Promise<{customergroupIds: Array}>} The applied order. * @throws {Error} If the order is invalid. * * @example * const result = await store.customergroup.order(42, { customergroupIds: [3, 1, 2] }); * // => { customergroupIds: [3, 1, 2] } */ return async (googleAuthId, { customergroupIds } = {}) => { if (!Array.isArray(customergroupIds)) { throw new Error('Invalid customer group order'); } const { companyId } = await access(googleAuthId); const groups = await pool .request() .input('companyId', companyId) .query(LIST_IDS_BY_COMPANY); const existing = new Set(groups.recordset.map((r) => r.id)); if (customergroupIds.length !== existing.size) { throw new Error('Invalid customer group order'); } const seen = new Set(); for (const customergroupId of customergroupIds) { if ( !Number.isFinite(customergroupId) || !existing.has(customergroupId) || seen.has(customergroupId) ) { throw new Error('Invalid customer group order'); } seen.add(customergroupId); } const tx = pool.transaction(); await tx.begin(); try { for (let sort = 0; sort < customergroupIds.length; sort++) { await request(pool, tx) .input('id', customergroupIds[sort]) .input('companyId', companyId) .input('sort', sort) .query(UPDATE_SORT); } await tx.commit(); return { customergroupIds }; } catch (err) { try { await tx.rollback(); } catch { // ignore } throw err; } }; }