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

48 lines
1.5 KiB
JavaScript

import { DELETE_BY_COMPANY_AND_SI as MSSQL_DELETE } from '../../providers/mssql/queries/unit.js';
import { DELETE_BY_COMPANY_AND_SI as SQLITE_DELETE } from '../../providers/sqlite3/queries/unit.js';
import { isForeignKeyConstraintError } from '../../providers/provider.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
export default function del(provider) {
const access = resolveSelectedCompanyAccess(provider);
const sql = provider?.dialect === 'sqlite3' ? SQLITE_DELETE : MSSQL_DELETE;
/**
* Deletes a unit for the user's selected company by its SI code.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {string} si - The SI code of the unit to delete.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<void>}
* @throws {Error} If the unit is not found.
*
* @example
* await store.unit.delete(42, 'l');
*/
return async (googleAuthId, si, tx) => {
if (!si?.trim()) {
throw new Error('Unit not found');
}
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, tx);
try {
const result = await runner.query(sql, {
companyId,
si: si.trim(),
});
if (!result.rowsAffected) {
throw new Error('Unit not found');
}
} catch (err) {
if (isForeignKeyConstraintError(err)) {
throw new Error('Unit in use');
}
throw err;
}
};
}