Files
dashlibstorage/src/store/customergroup/order.js

77 lines
1.9 KiB
JavaScript

import {
LIST_IDS_BY_COMPANY,
UPDATE_SORT,
} from '../../sql/customergroup.js';
import request from '../request.js';
import resolveCompanyAccess from '../companyuser/resolveCompanyAccess.js';
/**
* Reorders the customer groups of a company.
*
* @param {object} pool - The mssql connection pool.
* @returns {Function} An async function that reorders customer groups.
*
* @example
* const fn = order(pool);
* const result = await fn(42, 1, { customergroupIds: [3, 1, 2] });
* // => { customergroupIds: [3, 1, 2] }
*/
export default function order(pool) {
const access = resolveCompanyAccess(pool);
return async (googleAuthId, companyId, { customergroupIds } = {}) => {
if (!Array.isArray(customergroupIds)) {
throw new Error('Invalid customer group order');
}
await access(googleAuthId, companyId);
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;
}
};
}