39457-vm/backend/src/db/api/expenses.js
2026-04-03 15:43:02 +00:00

671 lines
16 KiB
JavaScript

const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ExpensesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const expenses = await db.expenses.create(
{
id: data.id || undefined,
spent_at: data.spent_at
||
null
,
amount: data.amount
||
null
,
payment_method: data.payment_method
||
null
,
vendor_name: data.vendor_name
||
null
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await expenses.setStore( data.store || null, {
transaction,
});
await expenses.setCategory( data.category || null, {
transaction,
});
await expenses.setRecorded_by( data.recorded_by || null, {
transaction,
});
await expenses.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.expenses.getTableName(),
belongsToColumn: 'attachments',
belongsToId: expenses.id,
},
data.attachments,
options,
);
return expenses;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const expensesData = data.map((item, index) => ({
id: item.id || undefined,
spent_at: item.spent_at
||
null
,
amount: item.amount
||
null
,
payment_method: item.payment_method
||
null
,
vendor_name: item.vendor_name
||
null
,
description: item.description
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const expenses = await db.expenses.bulkCreate(expensesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < expenses.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.expenses.getTableName(),
belongsToColumn: 'attachments',
belongsToId: expenses[i].id,
},
data[i].attachments,
options,
);
}
return expenses;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const expenses = await db.expenses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.spent_at !== undefined) updatePayload.spent_at = data.spent_at;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.payment_method !== undefined) updatePayload.payment_method = data.payment_method;
if (data.vendor_name !== undefined) updatePayload.vendor_name = data.vendor_name;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await expenses.update(updatePayload, {transaction});
if (data.store !== undefined) {
await expenses.setStore(
data.store,
{ transaction }
);
}
if (data.category !== undefined) {
await expenses.setCategory(
data.category,
{ transaction }
);
}
if (data.recorded_by !== undefined) {
await expenses.setRecorded_by(
data.recorded_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await expenses.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.expenses.getTableName(),
belongsToColumn: 'attachments',
belongsToId: expenses.id,
},
data.attachments,
options,
);
return expenses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const expenses = await db.expenses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of expenses) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of expenses) {
await record.destroy({transaction});
}
});
return expenses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const expenses = await db.expenses.findByPk(id, options);
await expenses.update({
deletedBy: currentUser.id
}, {
transaction,
});
await expenses.destroy({
transaction
});
return expenses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const expenses = await db.expenses.findOne(
{ where },
{ transaction },
);
if (!expenses) {
return expenses;
}
const output = expenses.get({plain: true});
output.store = await expenses.getStore({
transaction
});
output.category = await expenses.getCategory({
transaction
});
output.recorded_by = await expenses.getRecorded_by({
transaction
});
output.attachments = await expenses.getAttachments({
transaction
});
output.organizations = await expenses.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.stores,
as: 'store',
where: filter.store ? {
[Op.or]: [
{ id: { [Op.in]: filter.store.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.store.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.expense_categories,
as: 'category',
where: filter.category ? {
[Op.or]: [
{ id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'recorded_by',
where: filter.recorded_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.recorded_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.recorded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.vendor_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'expenses',
'vendor_name',
filter.vendor_name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'expenses',
'description',
filter.description,
),
};
}
if (filter.spent_atRange) {
const [start, end] = filter.spent_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
spent_at: {
...where.spent_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
spent_at: {
...where.spent_at,
[Op.lte]: end,
},
};
}
}
if (filter.amountRange) {
const [start, end] = filter.amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.payment_method) {
where = {
...where,
payment_method: filter.payment_method,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.expenses.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'expenses',
'vendor_name',
query,
),
],
};
}
const records = await db.expenses.findAll({
attributes: [ 'id', 'vendor_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['vendor_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.vendor_name,
}));
}
};