38127-vm/backend/src/db/api/imports.js
2026-02-03 02:50:52 +00:00

611 lines
15 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 ImportsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const imports = await db.imports.create(
{
id: data.id || undefined,
title: data.title
||
null
,
period_start: data.period_start
||
null
,
period_end: data.period_end
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await imports.setSource_account( data.source_account || null, {
transaction,
});
await imports.setUploaded_by( data.uploaded_by || null, {
transaction,
});
await imports.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.imports.getTableName(),
belongsToColumn: 'file',
belongsToId: imports.id,
},
data.file,
options,
);
return imports;
}
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 importsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
period_start: item.period_start
||
null
,
period_end: item.period_end
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const imports = await db.imports.bulkCreate(importsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < imports.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.imports.getTableName(),
belongsToColumn: 'file',
belongsToId: imports[i].id,
},
data[i].file,
options,
);
}
return imports;
}
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 imports = await db.imports.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.period_start !== undefined) updatePayload.period_start = data.period_start;
if (data.period_end !== undefined) updatePayload.period_end = data.period_end;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await imports.update(updatePayload, {transaction});
if (data.source_account !== undefined) {
await imports.setSource_account(
data.source_account,
{ transaction }
);
}
if (data.uploaded_by !== undefined) {
await imports.setUploaded_by(
data.uploaded_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await imports.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.imports.getTableName(),
belongsToColumn: 'file',
belongsToId: imports.id,
},
data.file,
options,
);
return imports;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const imports = await db.imports.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of imports) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of imports) {
await record.destroy({transaction});
}
});
return imports;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const imports = await db.imports.findByPk(id, options);
await imports.update({
deletedBy: currentUser.id
}, {
transaction,
});
await imports.destroy({
transaction
});
return imports;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const imports = await db.imports.findOne(
{ where },
{ transaction },
);
if (!imports) {
return imports;
}
const output = imports.get({plain: true});
output.expenses_import_record = await imports.getExpenses_import_record({
transaction
});
output.source_account = await imports.getSource_account({
transaction
});
output.file = await imports.getFile({
transaction
});
output.uploaded_by = await imports.getUploaded_by({
transaction
});
output.organizations = await imports.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.accounts,
as: 'source_account',
where: filter.source_account ? {
[Op.or]: [
{ id: { [Op.in]: filter.source_account.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.source_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'uploaded_by',
where: filter.uploaded_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.uploaded_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.uploaded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'imports',
'title',
filter.title,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'imports',
'notes',
filter.notes,
),
};
}
if (filter.period_startRange) {
const [start, end] = filter.period_startRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_start: {
...where.period_start,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_start: {
...where.period_start,
[Op.lte]: end,
},
};
}
}
if (filter.period_endRange) {
const [start, end] = filter.period_endRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_end: {
...where.period_end,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_end: {
...where.period_end,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
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.imports.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(
'imports',
'title',
query,
),
],
};
}
const records = await db.imports.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};