55 lines
1.9 KiB
JavaScript
55 lines
1.9 KiB
JavaScript
import { DELETE_BY_COMPANY_AND_ID as MSSQL_DELETE_BY_COMPANY_AND_ID } from '../../providers/mssql/queries/customergroup.js';
|
|
import { DELETE_BY_COMPANY_AND_ID as SQLITE_DELETE_BY_COMPANY_AND_ID } from '../../providers/sqlite3/queries/customergroup.js';
|
|
import { isForeignKeyConstraintError } from '../../providers/provider.js';
|
|
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
|
import recordObituary from '../posterminal/recordObituary.js';
|
|
import makeRunner from '../runner.js';
|
|
|
|
export default function del(provider) {
|
|
const access = resolveSelectedCompanyAccess(provider);
|
|
const recordObit = recordObituary(provider);
|
|
const sql =
|
|
provider?.dialect === 'sqlite3'
|
|
? SQLITE_DELETE_BY_COMPANY_AND_ID
|
|
: MSSQL_DELETE_BY_COMPANY_AND_ID;
|
|
|
|
/**
|
|
* Deletes a customer group for the user's selected company by its id.
|
|
*
|
|
* @param {number} googleAuthId - The id of the Google auth user.
|
|
* @param {number} id - The id of the customer group to delete.
|
|
* @param {object} [tx] - Optional transaction to run within.
|
|
* @returns {Promise<void>}
|
|
* @throws {Error} If the customer group is not found.
|
|
*
|
|
* @example
|
|
* await store.customergroup.delete(42, 5);
|
|
*/
|
|
return async (googleAuthId, id, tx) => {
|
|
if (!Number.isFinite(id)) {
|
|
throw new Error('Customer group not found');
|
|
}
|
|
|
|
const { companyId } = await access(googleAuthId, tx);
|
|
|
|
try {
|
|
const runner = makeRunner(provider, tx);
|
|
const result = await runner.query(sql, {
|
|
id,
|
|
companyId,
|
|
});
|
|
|
|
if (!result.rowsAffected) {
|
|
throw new Error('Customer group not found');
|
|
}
|
|
|
|
await recordObit({ companyId, entityType: 'customergroup', entityId: id }, runner);
|
|
} catch (err) {
|
|
if (isForeignKeyConstraintError(err)) {
|
|
throw new Error('Customer group in use');
|
|
}
|
|
throw err;
|
|
}
|
|
};
|
|
}
|