39636-vm/backend/src/db/api/strategies.js
2026-04-14 07:50:16 +00:00

549 lines
14 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 StrategiesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const strategies = await db.strategies.create(
{
id: data.id || undefined,
name: data.name
||
null
,
category: data.category
||
null
,
description: data.description
||
null
,
is_active: data.is_active
||
false
,
default_timeframe_minutes: data.default_timeframe_minutes
||
null
,
min_history_bars: data.min_history_bars
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.strategies.getTableName(),
belongsToColumn: 'attachments',
belongsToId: strategies.id,
},
data.attachments,
options,
);
return strategies;
}
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 strategiesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
category: item.category
||
null
,
description: item.description
||
null
,
is_active: item.is_active
||
false
,
default_timeframe_minutes: item.default_timeframe_minutes
||
null
,
min_history_bars: item.min_history_bars
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const strategies = await db.strategies.bulkCreate(strategiesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < strategies.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.strategies.getTableName(),
belongsToColumn: 'attachments',
belongsToId: strategies[i].id,
},
data[i].attachments,
options,
);
}
return strategies;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const strategies = await db.strategies.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.category !== undefined) updatePayload.category = data.category;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.default_timeframe_minutes !== undefined) updatePayload.default_timeframe_minutes = data.default_timeframe_minutes;
if (data.min_history_bars !== undefined) updatePayload.min_history_bars = data.min_history_bars;
updatePayload.updatedById = currentUser.id;
await strategies.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.strategies.getTableName(),
belongsToColumn: 'attachments',
belongsToId: strategies.id,
},
data.attachments,
options,
);
return strategies;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const strategies = await db.strategies.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of strategies) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of strategies) {
await record.destroy({transaction});
}
});
return strategies;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const strategies = await db.strategies.findByPk(id, options);
await strategies.update({
deletedBy: currentUser.id
}, {
transaction,
});
await strategies.destroy({
transaction
});
return strategies;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const strategies = await db.strategies.findOne(
{ where },
{ transaction },
);
if (!strategies) {
return strategies;
}
const output = strategies.get({plain: true});
output.strategy_parameters_strategy = await strategies.getStrategy_parameters_strategy({
transaction
});
output.session_strategies_strategy = await strategies.getSession_strategies_strategy({
transaction
});
output.trade_signals_strategy = await strategies.getTrade_signals_strategy({
transaction
});
output.backtest_runs_strategy = await strategies.getBacktest_runs_strategy({
transaction
});
output.optimization_runs_strategy = await strategies.getOptimization_runs_strategy({
transaction
});
output.attachments = await strategies.getAttachments({
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.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'strategies',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'strategies',
'description',
filter.description,
),
};
}
if (filter.default_timeframe_minutesRange) {
const [start, end] = filter.default_timeframe_minutesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
default_timeframe_minutes: {
...where.default_timeframe_minutes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
default_timeframe_minutes: {
...where.default_timeframe_minutes,
[Op.lte]: end,
},
};
}
}
if (filter.min_history_barsRange) {
const [start, end] = filter.min_history_barsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_history_bars: {
...where.min_history_bars,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_history_bars: {
...where.min_history_bars,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.category) {
where = {
...where,
category: filter.category,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.strategies.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(
'strategies',
'name',
query,
),
],
};
}
const records = await db.strategies.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,
}));
}
};