Files
dashlibstorage/src/store/posterminal/setOffAll.js
2026-10-22 14:39:45 +02:00

80 lines
2.8 KiB
JavaScript

import {
GET_BY_ID as MSSQL_GET_BY_ID,
SET_OFF_ALL as MSSQL_SET_OFF_ALL,
LIST_CATEGORY_IDS as MSSQL_LIST_CATEGORY_IDS,
} from '../../providers/mssql/queries/posterminal.js';
import {
GET_BY_ID as SQLITE_GET_BY_ID,
SET_OFF_ALL as SQLITE_SET_OFF_ALL,
LIST_CATEGORY_IDS as SQLITE_LIST_CATEGORY_IDS,
} from '../../providers/sqlite3/queries/posterminal.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
export default function setOffAll(provider) {
const access = resolveSelectedCompanyAccess(provider);
const isSqlite = provider?.dialect === 'sqlite3';
const getByIdSql = isSqlite ? SQLITE_GET_BY_ID : MSSQL_GET_BY_ID;
const setOffAllSql = isSqlite ? SQLITE_SET_OFF_ALL : MSSQL_SET_OFF_ALL;
const listCatIdsSql = isSqlite
? SQLITE_LIST_CATEGORY_IDS
: MSSQL_LIST_CATEGORY_IDS;
const addCategoryObituariesSql = `
INSERT INTO posterminalobituary (posterminal_id, entity_type, entity_id)
SELECT posterminal_id, 'category', category_id
FROM posterminalcategory
WHERE posterminal_id = @posterminalId
`;
const addArticleObituariesSql = `
INSERT INTO posterminalobituary (posterminal_id, entity_type, entity_id)
SELECT DISTINCT pc.posterminal_id, 'article', ca.article_id
FROM posterminalcategory pc
INNER JOIN categoryarticle ca ON ca.category_id = pc.category_id
WHERE pc.posterminal_id = @posterminalId
`;
/**
* Removes all category assignments from a posterminal.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {number} posterminalId - The id of the posterminal.
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, categoryIds: Array<number>}>} The posterminal with an empty category list.
* @throws {Error} If the posterminal is not found.
*
* @example
* const result = await store.posterminal.setOffAll(42, 5);
* // => { id, categoryIds: [] }
*/
return async (googleAuthId, posterminalId, tx) => {
if (!Number.isFinite(posterminalId)) {
throw new Error('Invalid posterminal');
}
const runner = makeRunner(provider, tx);
const { companyId } = await access(googleAuthId, tx);
// Verify posterminal belongs to company
const pt = await runner.query(getByIdSql, { id: posterminalId });
if (!pt.rows[0] || pt.rows[0].companyId !== companyId) {
throw new Error('Posterminal not found');
}
await runner.query(addCategoryObituariesSql, { posterminalId });
await runner.query(addArticleObituariesSql, { posterminalId });
await runner.query(setOffAllSql, { posterminalId });
const result = await runner.query(listCatIdsSql, { posterminalId });
return {
id: posterminalId,
categoryIds: result.rows.map((r) => r.categoryId),
};
};
}