33768/backend/src/db/api/trades.js
2025-08-31 11:23:04 +00:00

421 lines
10 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 TradesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const trades = await db.trades.create(
{
id: data.id || undefined,
trade_id: data.trade_id || null,
symbol: data.symbol || null,
action: data.action || null,
entry_price: data.entry_price || null,
status: data.status || null,
timestamp: data.timestamp || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await trades.setMaster_account_ref(data.master_account_ref || null, {
transaction,
});
await trades.setFollower_account_ref(data.follower_account_ref || null, {
transaction,
});
return trades;
}
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 tradesData = data.map((item, index) => ({
id: item.id || undefined,
trade_id: item.trade_id || null,
symbol: item.symbol || null,
action: item.action || null,
entry_price: item.entry_price || null,
status: item.status || null,
timestamp: item.timestamp || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const trades = await db.trades.bulkCreate(tradesData, { transaction });
// For each item created, replace relation files
return trades;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const trades = await db.trades.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.trade_id !== undefined) updatePayload.trade_id = data.trade_id;
if (data.symbol !== undefined) updatePayload.symbol = data.symbol;
if (data.action !== undefined) updatePayload.action = data.action;
if (data.entry_price !== undefined)
updatePayload.entry_price = data.entry_price;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.timestamp !== undefined) updatePayload.timestamp = data.timestamp;
updatePayload.updatedById = currentUser.id;
await trades.update(updatePayload, { transaction });
if (data.master_account_ref !== undefined) {
await trades.setMaster_account_ref(
data.master_account_ref,
{ transaction },
);
}
if (data.follower_account_ref !== undefined) {
await trades.setFollower_account_ref(
data.follower_account_ref,
{ transaction },
);
}
return trades;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const trades = await db.trades.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of trades) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of trades) {
await record.destroy({ transaction });
}
});
return trades;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const trades = await db.trades.findByPk(id, options);
await trades.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await trades.destroy({
transaction,
});
return trades;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const trades = await db.trades.findOne({ where }, { transaction });
if (!trades) {
return trades;
}
const output = trades.get({ plain: true });
output.master_account_ref = await trades.getMaster_account_ref({
transaction,
});
output.follower_account_ref = await trades.getFollower_account_ref({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.accounts,
as: 'master_account_ref',
where: filter.master_account_ref
? {
[Op.or]: [
{
id: {
[Op.in]: filter.master_account_ref
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
account_name: {
[Op.or]: filter.master_account_ref
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.accounts,
as: 'follower_account_ref',
where: filter.follower_account_ref
? {
[Op.or]: [
{
id: {
[Op.in]: filter.follower_account_ref
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
account_name: {
[Op.or]: filter.follower_account_ref
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.trade_id) {
where = {
...where,
[Op.and]: Utils.ilike('trades', 'trade_id', filter.trade_id),
};
}
if (filter.symbol) {
where = {
...where,
[Op.and]: Utils.ilike('trades', 'symbol', filter.symbol),
};
}
if (filter.entry_priceRange) {
const [start, end] = filter.entry_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
entry_price: {
...where.entry_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
entry_price: {
...where.entry_price,
[Op.lte]: end,
},
};
}
}
if (filter.timestampRange) {
const [start, end] = filter.timestampRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
timestamp: {
...where.timestamp,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
timestamp: {
...where.timestamp,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.action) {
where = {
...where,
action: filter.action,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
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,
},
};
}
}
}
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.trades.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) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('trades', 'trade_id', query),
],
};
}
const records = await db.trades.findAll({
attributes: ['id', 'trade_id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['trade_id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.trade_id,
}));
}
};