Files
dashlibstorage/src/store/company/getHistory.js
2026-10-04 09:33:27 +02:00

55 lines
2.2 KiB
JavaScript

import { LIST_BY_COMPANY_ID as MSSQL_QUERY, LIST_BY_COMPANY_ID_LIMITED as MSSQL_QUERY_LIMITED } from '../../providers/mssql/queries/companyhistory.js';
import { LIST_BY_COMPANY_ID as SQLITE_QUERY, LIST_BY_COMPANY_ID_LIMITED as SQLITE_QUERY_LIMITED } from '../../providers/sqlite3/queries/companyhistory.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
export default function getHistory(provider) {
const access = resolveSelectedCompanyAccess(provider);
const isSqlite = provider?.dialect === 'sqlite3';
const sql = isSqlite ? SQLITE_QUERY : MSSQL_QUERY;
const sqlLimited = isSqlite ? SQLITE_QUERY_LIMITED : MSSQL_QUERY_LIMITED;
/**
* Returns the company history for the user's selected company, newest first.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {object} [opts] - Optional options.
* @param {number} [opts.limit] - Maximum number of entries to return (newest first).
* @param {object} [tx] - Optional transaction.
* @returns {Promise<Array<{id: number, companyuserId: number|null, date: string, text: string}>>} The company history entries.
*
* @example
* const history = await store.company.getHistory(42);
* // => [{ id, companyuserId, date, text }]
*
* const recent = await store.company.getHistory(42, { limit: 5 });
* // => up to 5 most recent entries
*/
return async (googleAuthId, opts, tx) => {
let limit = null;
let resolvedTx = tx;
if (opts != null && typeof opts === 'object' && !opts._isTx) {
limit = opts.limit != null ? Number(opts.limit) : null;
} else if (opts != null) {
resolvedTx = opts;
}
const runner = makeRunner(provider, resolvedTx);
const { companyId } = await access(googleAuthId, runner);
let result;
if (limit != null && Number.isInteger(limit) && limit > 0) {
result = await runner.query(sqlLimited, { companyId, limit });
} else {
result = await runner.query(sql, { companyId });
}
return result.rows.map((row) => ({
id: row.id,
companyuserId: row.companyuserId ?? null,
date: row.date,
text: row.text,
}));
};
}