32718/backend/src/db/api/funds.js
2025-07-10 02:53:10 +00:00

471 lines
11 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 FundsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const funds = await db.funds.create(
{
id: data.id || undefined,
name: data.name || null,
nav: data.nav || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await funds.setClub(data.club || null, {
transaction,
});
await funds.setClubs(data.clubs || null, {
transaction,
});
await funds.setTrades(data.trades || [], {
transaction,
});
await funds.setDividends(data.dividends || [], {
transaction,
});
return funds;
}
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 fundsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name || null,
nav: item.nav || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const funds = await db.funds.bulkCreate(fundsData, { transaction });
// For each item created, replace relation files
return funds;
}
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 funds = await db.funds.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.nav !== undefined) updatePayload.nav = data.nav;
updatePayload.updatedById = currentUser.id;
await funds.update(updatePayload, { transaction });
if (data.club !== undefined) {
await funds.setClub(
data.club,
{ transaction },
);
}
if (data.clubs !== undefined) {
await funds.setClubs(
data.clubs,
{ transaction },
);
}
if (data.trades !== undefined) {
await funds.setTrades(data.trades, { transaction });
}
if (data.dividends !== undefined) {
await funds.setDividends(data.dividends, { transaction });
}
return funds;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const funds = await db.funds.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of funds) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of funds) {
await record.destroy({ transaction });
}
});
return funds;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const funds = await db.funds.findByPk(id, options);
await funds.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await funds.destroy({
transaction,
});
return funds;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const funds = await db.funds.findOne({ where }, { transaction });
if (!funds) {
return funds;
}
const output = funds.get({ plain: true });
output.dividends_fund = await funds.getDividends_fund({
transaction,
});
output.trades_fund = await funds.getTrades_fund({
transaction,
});
output.club = await funds.getClub({
transaction,
});
output.trades = await funds.getTrades({
transaction,
});
output.dividends = await funds.getDividends({
transaction,
});
output.clubs = await funds.getClubs({
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 userClubs = (user && user.clubs?.id) || null;
if (userClubs) {
if (options?.currentUser?.clubsId) {
where.clubsId = options.currentUser.clubsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.clubs,
as: 'club',
},
{
model: db.clubs,
as: 'clubs',
},
{
model: db.trades,
as: 'trades',
required: false,
},
{
model: db.dividends,
as: 'dividends',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike('funds', 'name', filter.name),
};
}
if (filter.navRange) {
const [start, end] = filter.navRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
nav: {
...where.nav,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
nav: {
...where.nav,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.club) {
const listItems = filter.club.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
clubId: { [Op.or]: listItems },
};
}
if (filter.clubs) {
const listItems = filter.clubs.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
clubsId: { [Op.or]: listItems },
};
}
if (filter.trades) {
const searchTerms = filter.trades.split('|');
include = [
{
model: db.trades,
as: 'trades_filter',
required: searchTerms.length > 0,
where:
searchTerms.length > 0
? {
[Op.or]: [
{
id: {
[Op.in]: searchTerms.map((term) => Utils.uuid(term)),
},
},
{
stock_symbol: {
[Op.or]: searchTerms.map((term) => ({
[Op.iLike]: `%${term}%`,
})),
},
},
],
}
: undefined,
},
...include,
];
}
if (filter.dividends) {
const searchTerms = filter.dividends.split('|');
include = [
{
model: db.dividends,
as: 'dividends_filter',
required: searchTerms.length > 0,
where:
searchTerms.length > 0
? {
[Op.or]: [
{
id: {
[Op.in]: searchTerms.map((term) => Utils.uuid(term)),
},
},
{
stock_symbol: {
[Op.or]: searchTerms.map((term) => ({
[Op.iLike]: `%${term}%`,
})),
},
},
],
}
: undefined,
},
...include,
];
}
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.clubsId;
}
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.funds.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('funds', 'name', query),
],
};
}
const records = await db.funds.findAll({
attributes: ['id', 'name'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};