Compare commits

...

1 Commits

Author SHA1 Message Date
Flatlogic Bot
253ab10a40 Updated via schema editor on 2025-08-28 05:05 2025-08-28 05:06:27 +00:00
47 changed files with 3454 additions and 381 deletions

5
.gitignore vendored
View File

@ -1,3 +1,8 @@
node_modules/
*/node_modules/
*/build/
**/node_modules/
**/build/
.DS_Store
.env

File diff suppressed because one or more lines are too long

391
backend/src/db/api/bot.js Normal file
View File

@ -0,0 +1,391 @@
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 BotDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const bot = await db.bot.create(
{
id: data.id || undefined,
name: data.name || null,
description: data.description || null,
order_count: data.order_count || null,
initial_order_value: data.initial_order_value || null,
order_size_increment: data.order_size_increment || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await bot.setUser(data.user || null, {
transaction,
});
return bot;
}
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 botData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name || null,
description: item.description || null,
order_count: item.order_count || null,
initial_order_value: item.initial_order_value || null,
order_size_increment: item.order_size_increment || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const bot = await db.bot.bulkCreate(botData, { transaction });
// For each item created, replace relation files
return bot;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const bot = await db.bot.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined)
updatePayload.description = data.description;
if (data.order_count !== undefined)
updatePayload.order_count = data.order_count;
if (data.initial_order_value !== undefined)
updatePayload.initial_order_value = data.initial_order_value;
if (data.order_size_increment !== undefined)
updatePayload.order_size_increment = data.order_size_increment;
updatePayload.updatedById = currentUser.id;
await bot.update(updatePayload, { transaction });
if (data.user !== undefined) {
await bot.setUser(
data.user,
{ transaction },
);
}
return bot;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const bot = await db.bot.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of bot) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of bot) {
await record.destroy({ transaction });
}
});
return bot;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const bot = await db.bot.findByPk(id, options);
await bot.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await bot.destroy({
transaction,
});
return bot;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const bot = await db.bot.findOne({ where }, { transaction });
if (!bot) {
return bot;
}
const output = bot.get({ plain: true });
output.orders_strategy = await bot.getOrders_strategy({
transaction,
});
output.user = await bot.getUser({
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.users,
as: 'user',
where: filter.user
? {
[Op.or]: [
{
id: {
[Op.in]: filter.user
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
firstName: {
[Op.or]: filter.user
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike('bot', 'name', filter.name),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike('bot', 'description', filter.description),
};
}
if (filter.order_countRange) {
const [start, end] = filter.order_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
order_count: {
...where.order_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
order_count: {
...where.order_count,
[Op.lte]: end,
},
};
}
}
if (filter.initial_order_valueRange) {
const [start, end] = filter.initial_order_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
initial_order_value: {
...where.initial_order_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
initial_order_value: {
...where.initial_order_value,
[Op.lte]: end,
},
};
}
}
if (filter.order_size_incrementRange) {
const [start, end] = filter.order_size_incrementRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
order_size_increment: {
...where.order_size_increment,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
order_size_increment: {
...where.order_size_increment,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
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.bot.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('bot', 'name', query),
],
};
}
const records = await db.bot.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,
}));
}
};

View File

@ -186,7 +186,7 @@ module.exports = class OrdersDBApi {
let include = [
{
model: db.strategies,
model: db.bot,
as: 'strategy',
where: filter.strategy

View File

@ -166,7 +166,7 @@ module.exports = class Trading_pairsDBApi {
let include = [
{
model: db.strategies,
model: db.bot,
as: 'strategies',
required: false,
},
@ -199,7 +199,7 @@ module.exports = class Trading_pairsDBApi {
include = [
{
model: db.strategies,
model: db.bot,
as: 'strategies_filter',
required: searchTerms.length > 0,
where:

View File

@ -271,7 +271,7 @@ module.exports = class UsersDBApi {
transaction,
});
output.strategies_user = await users.getStrategies_user({
output.bot_user = await users.getBot_user({
transaction,
});

View File

@ -0,0 +1,40 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.renameTable('strategies', 'bot', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.renameTable('bot', 'strategies', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,81 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function (sequelize, DataTypes) {
const bot = sequelize.define(
'bot',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
order_count: {
type: DataTypes.INTEGER,
},
initial_order_value: {
type: DataTypes.DECIMAL,
},
order_size_increment: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
bot.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.bot.hasMany(db.orders, {
as: 'orders_strategy',
foreignKey: {
name: 'strategyId',
},
constraints: false,
});
//end loop
db.bot.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.bot.belongsTo(db.users, {
as: 'createdBy',
});
db.bot.belongsTo(db.users, {
as: 'updatedBy',
});
};
return bot;
};

View File

@ -47,7 +47,7 @@ module.exports = function (sequelize, DataTypes) {
//end loop
db.orders.belongsTo(db.strategies, {
db.orders.belongsTo(db.bot, {
as: 'strategy',
foreignKey: {
name: 'strategyId',

View File

@ -32,22 +32,22 @@ module.exports = function (sequelize, DataTypes) {
);
trading_pairs.associate = (db) => {
db.trading_pairs.belongsToMany(db.strategies, {
db.trading_pairs.belongsToMany(db.bot, {
as: 'strategies',
foreignKey: {
name: 'trading_pairs_strategiesId',
},
constraints: false,
through: 'trading_pairsStrategiesStrategies',
through: 'trading_pairsStrategiesBot',
});
db.trading_pairs.belongsToMany(db.strategies, {
db.trading_pairs.belongsToMany(db.bot, {
as: 'strategies_filter',
foreignKey: {
name: 'trading_pairs_strategiesId',
},
constraints: false,
through: 'trading_pairsStrategiesStrategies',
through: 'trading_pairsStrategiesBot',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity

View File

@ -110,8 +110,8 @@ module.exports = function (sequelize, DataTypes) {
constraints: false,
});
db.users.hasMany(db.strategies, {
as: 'strategies_user',
db.users.hasMany(db.bot, {
as: 'bot_user',
foreignKey: {
name: 'userId',
},

View File

@ -87,7 +87,7 @@ module.exports = {
'users',
'api_keys',
'orders',
'strategies',
'bot',
'trading_pairs',
'roles',
'permissions',
@ -377,104 +377,6 @@ primary key ("roles_permissionsId", "permissionId")
permissionId: getId('READ_ORDERS'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('CryptoMaster'),
permissionId: getId('CREATE_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('CryptoMaster'),
permissionId: getId('READ_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('CryptoMaster'),
permissionId: getId('UPDATE_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('CryptoMaster'),
permissionId: getId('DELETE_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('TradeManager'),
permissionId: getId('CREATE_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('TradeManager'),
permissionId: getId('READ_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('TradeManager'),
permissionId: getId('UPDATE_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('TradeManager'),
permissionId: getId('DELETE_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('StrategyAnalyst'),
permissionId: getId('CREATE_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('StrategyAnalyst'),
permissionId: getId('READ_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('StrategyAnalyst'),
permissionId: getId('UPDATE_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('MarketViewer'),
permissionId: getId('READ_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('MarketViewer'),
permissionId: getId('UPDATE_STRATEGIES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('DataObserver'),
permissionId: getId('READ_STRATEGIES'),
},
{
createdAt,
updatedAt,
@ -673,25 +575,25 @@ primary key ("roles_permissionsId", "permissionId")
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('CREATE_STRATEGIES'),
permissionId: getId('CREATE_BOT'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('READ_STRATEGIES'),
permissionId: getId('READ_BOT'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('UPDATE_STRATEGIES'),
permissionId: getId('UPDATE_BOT'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('DELETE_STRATEGIES'),
permissionId: getId('DELETE_BOT'),
},
{

View File

@ -5,7 +5,7 @@ const ApiKeys = db.api_keys;
const Orders = db.orders;
const Strategies = db.strategies;
const Bot = db.bot;
const TradingPairs = db.trading_pairs;
@ -39,26 +39,6 @@ const ApiKeysData = [
// type code here for "relation_one" field
},
{
exchange: 'KuCoin',
api_key: 'kucoinApiKey890',
secret_key: 'kucoinSecretKey345',
// type code here for "relation_one" field
},
{
exchange: 'Binance',
api_key: 'binanceApiKey345',
secret_key: 'binanceSecretKey678',
// type code here for "relation_one" field
},
];
const OrdersData = [
@ -97,99 +77,47 @@ const OrdersData = [
is_profitable: true,
},
{
// type code here for "relation_one" field
// type code here for "relation_one" field
order_value: 5.5,
order_date: new Date('2023-10-04T13:00:00Z'),
is_profitable: true,
},
{
// type code here for "relation_one" field
// type code here for "relation_one" field
order_value: 12.6,
order_date: new Date('2023-10-05T14:00:00Z'),
is_profitable: true,
},
];
const StrategiesData = [
const BotData = [
{
name: 'Bullish Breakout',
name: 'Noam Chomsky',
description: 'Strategy for bullish market conditions',
description: 'Pierre Simon de Laplace',
order_count: 100,
order_count: 3,
initial_order_value: 10,
initial_order_value: 72.64,
order_size_increment: 1,
order_size_increment: 93.14,
// type code here for "relation_one" field
},
{
name: 'Bearish Reversal',
name: 'Arthur Eddington',
description: 'Strategy for bearish market conditions',
description: 'Ludwig Boltzmann',
order_count: 150,
order_count: 6,
initial_order_value: 15,
initial_order_value: 10.55,
order_size_increment: 1.5,
order_size_increment: 89.51,
// type code here for "relation_one" field
},
{
name: 'Range Trading',
name: 'Marie Curie',
description: 'Strategy for range-bound markets',
description: 'Tycho Brahe',
order_count: 200,
order_count: 4,
initial_order_value: 20,
initial_order_value: 71.49,
order_size_increment: 2,
// type code here for "relation_one" field
},
{
name: 'Scalping',
description: 'Quick trades for small profits',
order_count: 50,
initial_order_value: 5,
order_size_increment: 0.5,
// type code here for "relation_one" field
},
{
name: 'Swing Trading',
description: 'Strategy for capturing market swings',
order_count: 120,
initial_order_value: 12,
order_size_increment: 1.2,
order_size_increment: 71.66,
// type code here for "relation_one" field
},
@ -213,18 +141,6 @@ const TradingPairsData = [
// type code here for "relation_many" field
},
{
pair_name: 'LTC/USDT',
// type code here for "relation_many" field
},
{
pair_name: 'ADA/USDT',
// type code here for "relation_many" field
},
];
// Similar logic for "relation_many"
@ -262,33 +178,11 @@ async function associateApiKeyWithUser() {
if (ApiKey2?.setUser) {
await ApiKey2.setUser(relatedUser2);
}
const relatedUser3 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const ApiKey3 = await ApiKeys.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (ApiKey3?.setUser) {
await ApiKey3.setUser(relatedUser3);
}
const relatedUser4 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const ApiKey4 = await ApiKeys.findOne({
order: [['id', 'ASC']],
offset: 4,
});
if (ApiKey4?.setUser) {
await ApiKey4.setUser(relatedUser4);
}
}
async function associateOrderWithStrategy() {
const relatedStrategy0 = await Strategies.findOne({
offset: Math.floor(Math.random() * (await Strategies.count())),
const relatedStrategy0 = await Bot.findOne({
offset: Math.floor(Math.random() * (await Bot.count())),
});
const Order0 = await Orders.findOne({
order: [['id', 'ASC']],
@ -298,8 +192,8 @@ async function associateOrderWithStrategy() {
await Order0.setStrategy(relatedStrategy0);
}
const relatedStrategy1 = await Strategies.findOne({
offset: Math.floor(Math.random() * (await Strategies.count())),
const relatedStrategy1 = await Bot.findOne({
offset: Math.floor(Math.random() * (await Bot.count())),
});
const Order1 = await Orders.findOne({
order: [['id', 'ASC']],
@ -309,8 +203,8 @@ async function associateOrderWithStrategy() {
await Order1.setStrategy(relatedStrategy1);
}
const relatedStrategy2 = await Strategies.findOne({
offset: Math.floor(Math.random() * (await Strategies.count())),
const relatedStrategy2 = await Bot.findOne({
offset: Math.floor(Math.random() * (await Bot.count())),
});
const Order2 = await Orders.findOne({
order: [['id', 'ASC']],
@ -319,28 +213,6 @@ async function associateOrderWithStrategy() {
if (Order2?.setStrategy) {
await Order2.setStrategy(relatedStrategy2);
}
const relatedStrategy3 = await Strategies.findOne({
offset: Math.floor(Math.random() * (await Strategies.count())),
});
const Order3 = await Orders.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (Order3?.setStrategy) {
await Order3.setStrategy(relatedStrategy3);
}
const relatedStrategy4 = await Strategies.findOne({
offset: Math.floor(Math.random() * (await Strategies.count())),
});
const Order4 = await Orders.findOne({
order: [['id', 'ASC']],
offset: 4,
});
if (Order4?.setStrategy) {
await Order4.setStrategy(relatedStrategy4);
}
}
async function associateOrderWithTrading_pair() {
@ -376,84 +248,40 @@ async function associateOrderWithTrading_pair() {
if (Order2?.setTrading_pair) {
await Order2.setTrading_pair(relatedTrading_pair2);
}
const relatedTrading_pair3 = await TradingPairs.findOne({
offset: Math.floor(Math.random() * (await TradingPairs.count())),
});
const Order3 = await Orders.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (Order3?.setTrading_pair) {
await Order3.setTrading_pair(relatedTrading_pair3);
}
const relatedTrading_pair4 = await TradingPairs.findOne({
offset: Math.floor(Math.random() * (await TradingPairs.count())),
});
const Order4 = await Orders.findOne({
order: [['id', 'ASC']],
offset: 4,
});
if (Order4?.setTrading_pair) {
await Order4.setTrading_pair(relatedTrading_pair4);
}
}
async function associateStrategyWithUser() {
async function associateBotWithUser() {
const relatedUser0 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Strategy0 = await Strategies.findOne({
const Bot0 = await Bot.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Strategy0?.setUser) {
await Strategy0.setUser(relatedUser0);
if (Bot0?.setUser) {
await Bot0.setUser(relatedUser0);
}
const relatedUser1 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Strategy1 = await Strategies.findOne({
const Bot1 = await Bot.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Strategy1?.setUser) {
await Strategy1.setUser(relatedUser1);
if (Bot1?.setUser) {
await Bot1.setUser(relatedUser1);
}
const relatedUser2 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Strategy2 = await Strategies.findOne({
const Bot2 = await Bot.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Strategy2?.setUser) {
await Strategy2.setUser(relatedUser2);
}
const relatedUser3 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Strategy3 = await Strategies.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (Strategy3?.setUser) {
await Strategy3.setUser(relatedUser3);
}
const relatedUser4 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Strategy4 = await Strategies.findOne({
order: [['id', 'ASC']],
offset: 4,
});
if (Strategy4?.setUser) {
await Strategy4.setUser(relatedUser4);
if (Bot2?.setUser) {
await Bot2.setUser(relatedUser2);
}
}
@ -465,7 +293,7 @@ module.exports = {
await Orders.bulkCreate(OrdersData);
await Strategies.bulkCreate(StrategiesData);
await Bot.bulkCreate(BotData);
await TradingPairs.bulkCreate(TradingPairsData);
@ -478,7 +306,7 @@ module.exports = {
await associateOrderWithTrading_pair(),
await associateStrategyWithUser(),
await associateBotWithUser(),
// Similar logic for "relation_many"
]);
@ -489,7 +317,7 @@ module.exports = {
await queryInterface.bulkDelete('orders', null, {});
await queryInterface.bulkDelete('strategies', null, {});
await queryInterface.bulkDelete('bot', null, {});
await queryInterface.bulkDelete('trading_pairs', null, {});
},

View File

@ -0,0 +1,103 @@
const { v4: uuid } = require('uuid');
const db = require('../models');
const Sequelize = require('sequelize');
const config = require('../../config');
module.exports = {
/**
* @param{import("sequelize").QueryInterface} queryInterface
* @return {Promise<void>}
*/
async up(queryInterface) {
const createdAt = new Date();
const updatedAt = new Date();
/** @type {Map<string, string>} */
const idMap = new Map();
/**
* @param {string} key
* @return {string}
*/
function getId(key) {
if (idMap.has(key)) {
return idMap.get(key);
}
const id = uuid();
idMap.set(key, id);
return id;
}
/**
* @param {string} name
*/
function createPermissions(name) {
return [
{
id: getId(`CREATE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `CREATE_${name.toUpperCase()}`,
},
{
id: getId(`READ_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `READ_${name.toUpperCase()}`,
},
{
id: getId(`UPDATE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `UPDATE_${name.toUpperCase()}`,
},
{
id: getId(`DELETE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `DELETE_${name.toUpperCase()}`,
},
];
}
const entities = ['bot'];
const previousValues = ['strategies'];
const createdPreviousPermissions =
previousValues.flatMap(createPermissions);
const namesPreviousPermissions = createdPreviousPermissions.map(
(p) => p.name,
);
const createdPermissions = entities.flatMap(createPermissions);
// Add permissions to database
await queryInterface.bulkInsert('permissions', createdPermissions);
// Get permissions ids
const permissionsIds = createdPermissions.map((p) => p.id);
// Get admin role
const adminRole = await db.roles.findOne({
where: { name: config.roles.admin },
});
if (adminRole) {
// Add permissions to admin role if it exists
await adminRole.addPermissions(permissionsIds);
}
// Remove previous permissions
await db.permissions.destroy({
where: {
name: {
[Sequelize.Op.in]: namesPreviousPermissions,
},
},
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete(
'permissions',
entities.flatMap(createPermissions),
);
},
};

View File

@ -23,7 +23,7 @@ const api_keysRoutes = require('./routes/api_keys');
const ordersRoutes = require('./routes/orders');
const strategiesRoutes = require('./routes/strategies');
const botRoutes = require('./routes/bot');
const trading_pairsRoutes = require('./routes/trading_pairs');
@ -115,9 +115,9 @@ app.use(
);
app.use(
'/api/strategies',
'/api/bot',
passport.authenticate('jwt', { session: false }),
strategiesRoutes,
botRoutes,
);
app.use(

454
backend/src/routes/bot.js Normal file
View File

@ -0,0 +1,454 @@
const express = require('express');
const BotService = require('../services/bot');
const BotDBApi = require('../db/api/bot');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const { checkCrudPermissions } = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('bot'));
/**
* @swagger
* components:
* schemas:
* Bot:
* type: object
* properties:
* name:
* type: string
* default: name
* description:
* type: string
* default: description
* order_count:
* type: integer
* format: int64
* initial_order_value:
* type: integer
* format: int64
* order_size_increment:
* type: integer
* format: int64
*/
/**
* @swagger
* tags:
* name: Bot
* description: The Bot managing API
*/
/**
* @swagger
* /api/bot:
* post:
* security:
* - bearerAuth: []
* tags: [Bot]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Bot"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Bot"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post(
'/',
wrapAsync(async (req, res) => {
const referer =
req.headers.referer ||
`${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await BotService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Bot]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Bot"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Bot"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post(
'/bulk-import',
wrapAsync(async (req, res) => {
const referer =
req.headers.referer ||
`${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await BotService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/bot/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Bot]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Bot"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Bot"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put(
'/:id',
wrapAsync(async (req, res) => {
await BotService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/bot/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Bot]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Bot"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete(
'/:id',
wrapAsync(async (req, res) => {
await BotService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/bot/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Bot]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Bot"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post(
'/deleteByIds',
wrapAsync(async (req, res) => {
await BotService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/bot:
* get:
* security:
* - bearerAuth: []
* tags: [Bot]
* summary: Get all bot
* description: Get all bot
* responses:
* 200:
* description: Bot list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Bot"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get(
'/',
wrapAsync(async (req, res) => {
const filetype = req.query.filetype;
const currentUser = req.currentUser;
const payload = await BotDBApi.findAll(req.query, { currentUser });
if (filetype && filetype === 'csv') {
const fields = [
'id',
'name',
'description',
'order_count',
'initial_order_value',
'order_size_increment',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv);
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}),
);
/**
* @swagger
* /api/bot/count:
* get:
* security:
* - bearerAuth: []
* tags: [Bot]
* summary: Count all bot
* description: Count all bot
* responses:
* 200:
* description: Bot count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Bot"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get(
'/count',
wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await BotDBApi.findAll(req.query, null, {
countOnly: true,
currentUser,
});
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/bot/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Bot]
* summary: Find all bot that match search criteria
* description: Find all bot that match search criteria
* responses:
* 200:
* description: Bot list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Bot"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await BotDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/bot/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Bot]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Bot"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get(
'/:id',
wrapAsync(async (req, res) => {
const payload = await BotDBApi.findBy({ id: req.params.id });
res.status(200).send(payload);
}),
);
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

114
backend/src/services/bot.js Normal file
View File

@ -0,0 +1,114 @@
const db = require('../db/models');
const BotDBApi = require('../db/api/bot');
const processFile = require('../middlewares/upload');
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
module.exports = class BotService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await BotDBApi.create(data, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
try {
await processFile(req, res);
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, 'utf-8')); // convert Buffer to Stream
await new Promise((resolve, reject) => {
bufferStream
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
console.log('CSV results', results);
resolve();
})
.on('error', (error) => reject(error));
});
await BotDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let bot = await BotDBApi.findBy({ id }, { transaction });
if (!bot) {
throw new ValidationError('botNotFound');
}
const updatedBot = await BotDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedBot;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await BotDBApi.deleteByIds(ids, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await BotDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -45,20 +45,14 @@ module.exports = class SearchService {
api_keys: ['exchange', 'api_key', 'secret_key'],
strategies: ['name', 'description'],
bot: ['name', 'description'],
trading_pairs: ['pair_name'],
};
const columnsInt = {
orders: ['order_value'],
strategies: [
'order_count',
'initial_order_value',
'order_size_increment',
],
bot: ['order_count', 'initial_order_value', 'order_size_increment'],
};
let allFoundRecords = [];

View File

@ -0,0 +1,160 @@
import React from 'react';
import ImageField from '../ImageField';
import ListActionsPopover from '../ListActionsPopover';
import { useAppSelector } from '../../stores/hooks';
import dataFormatter from '../../helpers/dataFormatter';
import { Pagination } from '../Pagination';
import { saveFile } from '../../helpers/fileSaver';
import LoadingSpinner from '../LoadingSpinner';
import Link from 'next/link';
import { hasPermission } from '../../helpers/userPermissions';
type Props = {
bot: any[];
loading: boolean;
onDelete: (id: string) => void;
currentPage: number;
numPages: number;
onPageChange: (page: number) => void;
};
const CardBot = ({
bot,
loading,
onDelete,
currentPage,
numPages,
onPageChange,
}: Props) => {
const asideScrollbarsStyle = useAppSelector(
(state) => state.style.asideScrollbarsStyle,
);
const bgColor = useAppSelector((state) => state.style.cardsColor);
const darkMode = useAppSelector((state) => state.style.darkMode);
const corners = useAppSelector((state) => state.style.corners);
const focusRing = useAppSelector((state) => state.style.focusRingColor);
const currentUser = useAppSelector((state) => state.auth.currentUser);
const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_BOT');
return (
<div className={'p-4'}>
{loading && <LoadingSpinner />}
<ul
role='list'
className='grid grid-cols-1 gap-x-6 gap-y-8 lg:grid-cols-3 2xl:grid-cols-4 xl:gap-x-8'
>
{!loading &&
bot.map((item, index) => (
<li
key={item.id}
className={`overflow-hidden ${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
} border ${focusRing} border-gray-200 dark:border-dark-700 ${
darkMode ? 'aside-scrollbars-[slate]' : asideScrollbarsStyle
}`}
>
<div
className={`flex items-center ${bgColor} p-6 gap-x-4 border-b border-gray-900/5 bg-gray-50 dark:bg-dark-800 relative`}
>
<Link
href={`/bot/bot-view/?id=${item.id}`}
className='text-lg font-bold leading-6 line-clamp-1'
>
{item.name}
</Link>
<div className='ml-auto '>
<ListActionsPopover
onDelete={onDelete}
itemId={item.id}
pathEdit={`/bot/bot-edit/?id=${item.id}`}
pathView={`/bot/bot-view/?id=${item.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>
</div>
<dl className='divide-y divide-gray-600 dark:divide-dark-700 px-6 py-4 text-sm leading-6 h-64 overflow-y-auto'>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
BotName
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>{item.name}</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Description
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.description}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
OrderCount
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.order_count}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
InitialOrderValue
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.initial_order_value}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
OrderSizeIncrement
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.order_size_increment}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>User</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{dataFormatter.usersOneListFormatter(item.user)}
</div>
</dd>
</div>
</dl>
</li>
))}
{!loading && bot.length === 0 && (
<div className='col-span-full flex items-center justify-center h-40'>
<p className=''>No data to display</p>
</div>
)}
</ul>
<div className={'flex items-center justify-center my-6'}>
<Pagination
currentPage={currentPage}
numPages={numPages}
setCurrentPage={onPageChange}
/>
</div>
</div>
);
};
export default CardBot;

View File

@ -0,0 +1,124 @@
import React from 'react';
import CardBox from '../CardBox';
import ImageField from '../ImageField';
import dataFormatter from '../../helpers/dataFormatter';
import { saveFile } from '../../helpers/fileSaver';
import ListActionsPopover from '../ListActionsPopover';
import { useAppSelector } from '../../stores/hooks';
import { Pagination } from '../Pagination';
import LoadingSpinner from '../LoadingSpinner';
import Link from 'next/link';
import { hasPermission } from '../../helpers/userPermissions';
type Props = {
bot: any[];
loading: boolean;
onDelete: (id: string) => void;
currentPage: number;
numPages: number;
onPageChange: (page: number) => void;
};
const ListBot = ({
bot,
loading,
onDelete,
currentPage,
numPages,
onPageChange,
}: Props) => {
const currentUser = useAppSelector((state) => state.auth.currentUser);
const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_BOT');
const corners = useAppSelector((state) => state.style.corners);
const bgColor = useAppSelector((state) => state.style.cardsColor);
return (
<>
<div className='relative overflow-x-auto p-4 space-y-4'>
{loading && <LoadingSpinner />}
{!loading &&
bot.map((item) => (
<div key={item.id}>
<CardBox hasTable isList className={'rounded shadow-none'}>
<div
className={`flex ${bgColor} ${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
} dark:bg-dark-900 border border-gray-600 items-center overflow-hidden`}
>
<Link
href={`/bot/bot-view/?id=${item.id}`}
className={
'flex-1 px-4 py-6 h-24 flex divide-x-2 divide-gray-600 items-center overflow-hidden`}> dark:divide-dark-700 overflow-x-auto'
}
>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>BotName</p>
<p className={'line-clamp-2'}>{item.name}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Description</p>
<p className={'line-clamp-2'}>{item.description}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>OrderCount</p>
<p className={'line-clamp-2'}>{item.order_count}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>
InitialOrderValue
</p>
<p className={'line-clamp-2'}>
{item.initial_order_value}
</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>
OrderSizeIncrement
</p>
<p className={'line-clamp-2'}>
{item.order_size_increment}
</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>User</p>
<p className={'line-clamp-2'}>
{dataFormatter.usersOneListFormatter(item.user)}
</p>
</div>
</Link>
<ListActionsPopover
onDelete={onDelete}
itemId={item.id}
pathEdit={`/bot/bot-edit/?id=${item.id}`}
pathView={`/bot/bot-view/?id=${item.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>
</CardBox>
</div>
))}
{!loading && bot.length === 0 && (
<div className='col-span-full flex items-center justify-center h-40'>
<p className=''>No data to display</p>
</div>
)}
</div>
<div className={'flex items-center justify-center my-6'}>
<Pagination
currentPage={currentPage}
numPages={numPages}
setCurrentPage={onPageChange}
/>
</div>
</>
);
};
export default ListBot;

View File

@ -0,0 +1,492 @@
import React, { useEffect, useState, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { ToastContainer, toast } from 'react-toastify';
import BaseButton from '../BaseButton';
import CardBoxModal from '../CardBoxModal';
import CardBox from '../CardBox';
import {
fetch,
update,
deleteItem,
setRefetch,
deleteItemsByIds,
} from '../../stores/bot/botSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { Field, Form, Formik } from 'formik';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { loadColumns } from './configureBotCols';
import _ from 'lodash';
import dataFormatter from '../../helpers/dataFormatter';
import { dataGridStyles } from '../../styles';
import CardBot from './CardBot';
const perPage = 10;
const TableSampleBot = ({ filterItems, setFilterItems, filters, showGrid }) => {
const notify = (type, msg) => toast(msg, { type, position: 'bottom-center' });
const dispatch = useAppDispatch();
const router = useRouter();
const pagesList = [];
const [id, setId] = useState(null);
const [currentPage, setCurrentPage] = useState(0);
const [filterRequest, setFilterRequest] = React.useState('');
const [columns, setColumns] = useState<GridColDef[]>([]);
const [selectedRows, setSelectedRows] = useState([]);
const [sortModel, setSortModel] = useState([
{
field: '',
sort: 'desc',
},
]);
const {
bot,
loading,
count,
notify: botNotify,
refetch,
} = useAppSelector((state) => state.bot);
const { currentUser } = useAppSelector((state) => state.auth);
const focusRing = useAppSelector((state) => state.style.focusRingColor);
const bgColor = useAppSelector((state) => state.style.bgLayoutColor);
const corners = useAppSelector((state) => state.style.corners);
const numPages =
Math.floor(count / perPage) === 0 ? 1 : Math.ceil(count / perPage);
for (let i = 0; i < numPages; i++) {
pagesList.push(i);
}
const loadData = async (page = currentPage, request = filterRequest) => {
if (page !== currentPage) setCurrentPage(page);
if (request !== filterRequest) setFilterRequest(request);
const { sort, field } = sortModel[0];
const query = `?page=${page}&limit=${perPage}${request}&sort=${sort}&field=${field}`;
dispatch(fetch({ limit: perPage, page, query }));
};
useEffect(() => {
if (botNotify.showNotification) {
notify(botNotify.typeNotification, botNotify.textNotification);
}
}, [botNotify.showNotification]);
useEffect(() => {
if (!currentUser) return;
loadData();
}, [sortModel, currentUser]);
useEffect(() => {
if (refetch) {
loadData(0);
dispatch(setRefetch(false));
}
}, [refetch, dispatch]);
const [isModalInfoActive, setIsModalInfoActive] = useState(false);
const [isModalTrashActive, setIsModalTrashActive] = useState(false);
const handleModalAction = () => {
setIsModalInfoActive(false);
setIsModalTrashActive(false);
};
const handleDeleteModalAction = (id: string) => {
setId(id);
setIsModalTrashActive(true);
};
const handleDeleteAction = async () => {
if (id) {
await dispatch(deleteItem(id));
await loadData(0);
setIsModalTrashActive(false);
}
};
const generateFilterRequests = useMemo(() => {
let request = '&';
filterItems.forEach((item) => {
const isRangeFilter = filters.find(
(filter) =>
filter.title === item.fields.selectedField &&
(filter.number || filter.date),
);
if (isRangeFilter) {
const from = item.fields.filterValueFrom;
const to = item.fields.filterValueTo;
if (from) {
request += `${item.fields.selectedField}Range=${from}&`;
}
if (to) {
request += `${item.fields.selectedField}Range=${to}&`;
}
} else {
const value = item.fields.filterValue;
if (value) {
request += `${item.fields.selectedField}=${value}&`;
}
}
});
return request;
}, [filterItems, filters]);
const deleteFilter = (value) => {
const newItems = filterItems.filter((item) => item.id !== value);
if (newItems.length) {
setFilterItems(newItems);
} else {
loadData(0, '');
setFilterItems(newItems);
}
};
const handleSubmit = () => {
loadData(0, generateFilterRequests);
};
const handleChange = (id) => (e) => {
const value = e.target.value;
const name = e.target.name;
setFilterItems(
filterItems.map((item) => {
if (item.id !== id) return item;
if (name === 'selectedField') return { id, fields: { [name]: value } };
return { id, fields: { ...item.fields, [name]: value } };
}),
);
};
const handleReset = () => {
setFilterItems([]);
loadData(0, '');
};
const onPageChange = (page: number) => {
loadData(page);
setCurrentPage(page);
};
useEffect(() => {
if (!currentUser) return;
loadColumns(handleDeleteModalAction, `bot`, currentUser).then((newCols) =>
setColumns(newCols),
);
}, [currentUser]);
const handleTableSubmit = async (id: string, data) => {
if (!_.isEmpty(data)) {
await dispatch(update({ id, data }))
.unwrap()
.then((res) => res)
.catch((err) => {
throw new Error(err);
});
}
};
const onDeleteRows = async (selectedRows) => {
await dispatch(deleteItemsByIds(selectedRows));
await loadData(0);
};
const controlClasses =
'w-full py-2 px-2 my-2 rounded dark:placeholder-gray-400 ' +
` ${bgColor} ${focusRing} ${corners} ` +
'dark:bg-slate-800 border';
const dataGrid = (
<div className='relative overflow-x-auto'>
<DataGrid
autoHeight
rowHeight={64}
sx={dataGridStyles}
className={'datagrid--table'}
getRowClassName={() => `datagrid--row`}
rows={bot ?? []}
columns={columns}
initialState={{
pagination: {
paginationModel: {
pageSize: 10,
},
},
}}
disableRowSelectionOnClick
onProcessRowUpdateError={(params) => {
console.log('Error', params);
}}
processRowUpdate={async (newRow, oldRow) => {
const data = dataFormatter.dataGridEditFormatter(newRow);
try {
await handleTableSubmit(newRow.id, data);
return newRow;
} catch {
return oldRow;
}
}}
sortingMode={'server'}
checkboxSelection
onRowSelectionModelChange={(ids) => {
setSelectedRows(ids);
}}
onSortModelChange={(params) => {
params.length
? setSortModel(params)
: setSortModel([{ field: '', sort: 'desc' }]);
}}
rowCount={count}
pageSizeOptions={[10]}
paginationMode={'server'}
loading={loading}
onPaginationModelChange={(params) => {
onPageChange(params.page);
}}
/>
</div>
);
return (
<>
{filterItems && Array.isArray(filterItems) && filterItems.length ? (
<CardBox>
<Formik
initialValues={{
checkboxes: ['lorem'],
switches: ['lorem'],
radio: 'lorem',
}}
onSubmit={() => null}
>
<Form>
<>
{filterItems &&
filterItems.map((filterItem) => {
return (
<div key={filterItem.id} className='flex mb-4'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
Filter
</div>
<Field
className={controlClasses}
name='selectedField'
id='selectedField'
component='select'
value={filterItem?.fields?.selectedField || ''}
onChange={handleChange(filterItem.id)}
>
{filters.map((selectOption) => (
<option
key={selectOption.title}
value={`${selectOption.title}`}
>
{selectOption.label}
</option>
))}
</Field>
</div>
{filters.find(
(filter) =>
filter.title === filterItem?.fields?.selectedField,
)?.type === 'enum' ? (
<div className='flex flex-col w-full mr-3'>
<div className='text-gray-500 font-bold'>Value</div>
<Field
className={controlClasses}
name='filterValue'
id='filterValue'
component='select'
value={filterItem?.fields?.filterValue || ''}
onChange={handleChange(filterItem.id)}
>
<option value=''>Select Value</option>
{filters
.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)
?.options?.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</Field>
</div>
) : filters.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)?.number ? (
<div className='flex flex-row w-full mr-3'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
From
</div>
<Field
className={controlClasses}
name='filterValueFrom'
placeholder='From'
id='filterValueFrom'
value={
filterItem?.fields?.filterValueFrom || ''
}
onChange={handleChange(filterItem.id)}
/>
</div>
<div className='flex flex-col w-full'>
<div className=' text-gray-500 font-bold'>
To
</div>
<Field
className={controlClasses}
name='filterValueTo'
placeholder='to'
id='filterValueTo'
value={filterItem?.fields?.filterValueTo || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
</div>
) : filters.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)?.date ? (
<div className='flex flex-row w-full mr-3'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
From
</div>
<Field
className={controlClasses}
name='filterValueFrom'
placeholder='From'
id='filterValueFrom'
type='datetime-local'
value={
filterItem?.fields?.filterValueFrom || ''
}
onChange={handleChange(filterItem.id)}
/>
</div>
<div className='flex flex-col w-full'>
<div className=' text-gray-500 font-bold'>
To
</div>
<Field
className={controlClasses}
name='filterValueTo'
placeholder='to'
id='filterValueTo'
type='datetime-local'
value={filterItem?.fields?.filterValueTo || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
</div>
) : (
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
Contains
</div>
<Field
className={controlClasses}
name='filterValue'
placeholder='Contained'
id='filterValue'
value={filterItem?.fields?.filterValue || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
)}
<div className='flex flex-col'>
<div className=' text-gray-500 font-bold'>
Action
</div>
<BaseButton
className='my-2'
type='reset'
color='danger'
label='Delete'
onClick={() => {
deleteFilter(filterItem.id);
}}
/>
</div>
</div>
);
})}
<div className='flex'>
<BaseButton
className='my-2 mr-3'
type='submit'
color='info'
label='Apply'
onClick={handleSubmit}
/>
<BaseButton
className='my-2'
type='reset'
color='info'
outline
label='Cancel'
onClick={handleReset}
/>
</div>
</>
</Form>
</Formik>
</CardBox>
) : null}
<CardBoxModal
title='Please confirm'
buttonColor='info'
buttonLabel={loading ? 'Deleting...' : 'Confirm'}
isActive={isModalTrashActive}
onConfirm={handleDeleteAction}
onCancel={handleModalAction}
>
<p>Are you sure you want to delete this item?</p>
</CardBoxModal>
{bot && Array.isArray(bot) && !showGrid && (
<CardBot
bot={bot}
loading={loading}
onDelete={handleDeleteModalAction}
currentPage={currentPage}
numPages={numPages}
onPageChange={onPageChange}
/>
)}
{showGrid && dataGrid}
{selectedRows.length > 0 &&
createPortal(
<BaseButton
className='me-4'
color='danger'
label={`Delete ${selectedRows.length === 1 ? 'Row' : 'Rows'}`}
onClick={() => onDeleteRows(selectedRows)}
/>,
document.getElementById('delete-rows-button'),
)}
<ToastContainer />
</>
);
};
export default TableSampleBot;

View File

@ -0,0 +1,148 @@
import React from 'react';
import BaseIcon from '../BaseIcon';
import { mdiEye, mdiTrashCan, mdiPencilOutline } from '@mdi/js';
import axios from 'axios';
import {
GridActionsCellItem,
GridRowParams,
GridValueGetterParams,
} from '@mui/x-data-grid';
import ImageField from '../ImageField';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import DataGridMultiSelect from '../DataGridMultiSelect';
import ListActionsPopover from '../ListActionsPopover';
import { hasPermission } from '../../helpers/userPermissions';
type Params = (id: string) => void;
export const loadColumns = async (
onDelete: Params,
entityName: string,
user,
) => {
async function callOptionsApi(entityName: string) {
if (!hasPermission(user, 'READ_' + entityName.toUpperCase())) return [];
try {
const data = await axios(`/${entityName}/autocomplete?limit=100`);
return data.data;
} catch (error) {
console.log(error);
return [];
}
}
const hasUpdatePermission = hasPermission(user, 'UPDATE_BOT');
return [
{
field: 'name',
headerName: 'BotName',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
},
{
field: 'description',
headerName: 'Description',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
},
{
field: 'order_count',
headerName: 'OrderCount',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
type: 'number',
},
{
field: 'initial_order_value',
headerName: 'InitialOrderValue',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
type: 'number',
},
{
field: 'order_size_increment',
headerName: 'OrderSizeIncrement',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
type: 'number',
},
{
field: 'user',
headerName: 'User',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
sortable: false,
type: 'singleSelect',
getOptionValue: (value: any) => value?.id,
getOptionLabel: (value: any) => value?.label,
valueOptions: await callOptionsApi('users'),
valueGetter: (params: GridValueGetterParams) =>
params?.value?.id ?? params?.value,
},
{
field: 'actions',
type: 'actions',
minWidth: 30,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
getActions: (params: GridRowParams) => {
return [
<div key={params?.row?.id}>
<ListActionsPopover
onDelete={onDelete}
itemId={params?.row?.id}
pathEdit={`/bot/bot-edit/?id=${params?.row?.id}`}
pathView={`/bot/bot-view/?id=${params?.row?.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>,
];
},
},
];
};

View File

@ -82,7 +82,7 @@ const CardOrders = ({
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{dataFormatter.strategiesOneListFormatter(item.strategy)}
{dataFormatter.botOneListFormatter(item.strategy)}
</div>
</dd>
</div>

View File

@ -56,9 +56,7 @@ const ListOrders = ({
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Strategy</p>
<p className={'line-clamp-2'}>
{dataFormatter.strategiesOneListFormatter(
item.strategy,
)}
{dataFormatter.botOneListFormatter(item.strategy)}
</p>
</div>

View File

@ -53,7 +53,7 @@ export const loadColumns = async (
type: 'singleSelect',
getOptionValue: (value: any) => value?.id,
getOptionLabel: (value: any) => value?.label,
valueOptions: await callOptionsApi('strategies'),
valueOptions: await callOptionsApi('bot'),
valueGetter: (params: GridValueGetterParams) =>
params?.value?.id ?? params?.value,
},

View File

@ -97,7 +97,7 @@ const CardTrading_pairs = ({
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{dataFormatter
.strategiesManyListFormatter(item.strategies)
.botManyListFormatter(item.strategies)
.join(', ')}
</div>
</dd>

View File

@ -65,7 +65,7 @@ const ListTrading_pairs = ({
<p className={'text-xs text-gray-500 '}>Strategies</p>
<p className={'line-clamp-2'}>
{dataFormatter
.strategiesManyListFormatter(item.strategies)
.botManyListFormatter(item.strategies)
.join(', ')}
</p>
</div>

View File

@ -63,9 +63,9 @@ export const loadColumns = async (
sortable: false,
type: 'singleSelect',
valueFormatter: ({ value }) =>
dataFormatter.strategiesManyListFormatter(value).join(', '),
dataFormatter.botManyListFormatter(value).join(', '),
renderEditCell: (params) => (
<DataGridMultiSelect {...params} entityName={'strategies'} />
<DataGridMultiSelect {...params} entityName={'bot'} />
),
},

View File

@ -58,21 +58,21 @@ export default {
return { label: val.firstName, id: val.id };
},
strategiesManyListFormatter(val) {
botManyListFormatter(val) {
if (!val || !val.length) return [];
return val.map((item) => item.name);
},
strategiesOneListFormatter(val) {
botOneListFormatter(val) {
if (!val) return '';
return val.name;
},
strategiesManyListFormatterEdit(val) {
botManyListFormatterEdit(val) {
if (!val || !val.length) return [];
return val.map((item) => {
return { id: item.id, label: item.name };
});
},
strategiesOneListFormatterEdit(val) {
botOneListFormatterEdit(val) {
if (!val) return '';
return { label: val.name, id: val.id };
},

View File

@ -39,15 +39,15 @@ const menuAside: MenuAsideItem[] = [
permissions: 'READ_ORDERS',
},
{
href: '/strategies/strategies-list',
label: 'Strategies',
href: '/bot/bot-list',
label: 'Bot',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon:
'mdiChartLine' in icon
? icon['mdiChartLine' as keyof typeof icon]
: icon.mdiTable ?? icon.mdiTable,
permissions: 'READ_STRATEGIES',
permissions: 'READ_BOT',
},
{
href: '/trading_pairs/trading_pairs-list',

View File

@ -0,0 +1,175 @@
import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import dayjs from 'dayjs';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import { Field, Form, Formik } from 'formik';
import FormField from '../../components/FormField';
import BaseDivider from '../../components/BaseDivider';
import BaseButtons from '../../components/BaseButtons';
import BaseButton from '../../components/BaseButton';
import FormCheckRadio from '../../components/FormCheckRadio';
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup';
import FormFilePicker from '../../components/FormFilePicker';
import FormImagePicker from '../../components/FormImagePicker';
import { SelectField } from '../../components/SelectField';
import { SelectFieldMany } from '../../components/SelectFieldMany';
import { SwitchField } from '../../components/SwitchField';
import { RichTextField } from '../../components/RichTextField';
import { update, fetch } from '../../stores/bot/botSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
const EditBot = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const initVals = {
name: '',
description: '',
order_count: '',
initial_order_value: '',
order_size_increment: '',
user: null,
};
const [initialValues, setInitialValues] = useState(initVals);
const { bot } = useAppSelector((state) => state.bot);
const { botId } = router.query;
useEffect(() => {
dispatch(fetch({ id: botId }));
}, [botId]);
useEffect(() => {
if (typeof bot === 'object') {
setInitialValues(bot);
}
}, [bot]);
useEffect(() => {
if (typeof bot === 'object') {
const newInitialVal = { ...initVals };
Object.keys(initVals).forEach((el) => (newInitialVal[el] = bot[el]));
setInitialValues(newInitialVal);
}
}, [bot]);
const handleSubmit = async (data) => {
await dispatch(update({ id: botId, data }));
await router.push('/bot/bot-list');
};
return (
<>
<Head>
<title>{getPageTitle('Edit bot')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={'Edit bot'}
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='BotName'>
<Field name='name' placeholder='BotName' />
</FormField>
<FormField label='Description' hasTextareaHeight>
<Field
name='description'
as='textarea'
placeholder='Description'
/>
</FormField>
<FormField label='OrderCount'>
<Field
type='number'
name='order_count'
placeholder='OrderCount'
/>
</FormField>
<FormField label='InitialOrderValue'>
<Field
type='number'
name='initial_order_value'
placeholder='InitialOrderValue'
/>
</FormField>
<FormField label='OrderSizeIncrement'>
<Field
type='number'
name='order_size_increment'
placeholder='OrderSizeIncrement'
/>
</FormField>
<FormField label='User' labelFor='user'>
<Field
name='user'
id='user'
component={SelectField}
options={initialValues.user}
itemRef={'users'}
showField={'firstName'}
></Field>
</FormField>
<BaseDivider />
<BaseButtons>
<BaseButton type='submit' color='info' label='Submit' />
<BaseButton type='reset' color='info' outline label='Reset' />
<BaseButton
type='reset'
color='danger'
outline
label='Cancel'
onClick={() => router.push('/bot/bot-list')}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
EditBot.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'UPDATE_BOT'}>{page}</LayoutAuthenticated>
);
};
export default EditBot;

View File

@ -0,0 +1,173 @@
import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import dayjs from 'dayjs';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import { Field, Form, Formik } from 'formik';
import FormField from '../../components/FormField';
import BaseDivider from '../../components/BaseDivider';
import BaseButtons from '../../components/BaseButtons';
import BaseButton from '../../components/BaseButton';
import FormCheckRadio from '../../components/FormCheckRadio';
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup';
import FormFilePicker from '../../components/FormFilePicker';
import FormImagePicker from '../../components/FormImagePicker';
import { SelectField } from '../../components/SelectField';
import { SelectFieldMany } from '../../components/SelectFieldMany';
import { SwitchField } from '../../components/SwitchField';
import { RichTextField } from '../../components/RichTextField';
import { update, fetch } from '../../stores/bot/botSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
const EditBotPage = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const initVals = {
name: '',
description: '',
order_count: '',
initial_order_value: '',
order_size_increment: '',
user: null,
};
const [initialValues, setInitialValues] = useState(initVals);
const { bot } = useAppSelector((state) => state.bot);
const { id } = router.query;
useEffect(() => {
dispatch(fetch({ id: id }));
}, [id]);
useEffect(() => {
if (typeof bot === 'object') {
setInitialValues(bot);
}
}, [bot]);
useEffect(() => {
if (typeof bot === 'object') {
const newInitialVal = { ...initVals };
Object.keys(initVals).forEach((el) => (newInitialVal[el] = bot[el]));
setInitialValues(newInitialVal);
}
}, [bot]);
const handleSubmit = async (data) => {
await dispatch(update({ id: id, data }));
await router.push('/bot/bot-list');
};
return (
<>
<Head>
<title>{getPageTitle('Edit bot')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={'Edit bot'}
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='BotName'>
<Field name='name' placeholder='BotName' />
</FormField>
<FormField label='Description' hasTextareaHeight>
<Field
name='description'
as='textarea'
placeholder='Description'
/>
</FormField>
<FormField label='OrderCount'>
<Field
type='number'
name='order_count'
placeholder='OrderCount'
/>
</FormField>
<FormField label='InitialOrderValue'>
<Field
type='number'
name='initial_order_value'
placeholder='InitialOrderValue'
/>
</FormField>
<FormField label='OrderSizeIncrement'>
<Field
type='number'
name='order_size_increment'
placeholder='OrderSizeIncrement'
/>
</FormField>
<FormField label='User' labelFor='user'>
<Field
name='user'
id='user'
component={SelectField}
options={initialValues.user}
itemRef={'users'}
showField={'firstName'}
></Field>
</FormField>
<BaseDivider />
<BaseButtons>
<BaseButton type='submit' color='info' label='Submit' />
<BaseButton type='reset' color='info' outline label='Reset' />
<BaseButton
type='reset'
color='danger'
outline
label='Cancel'
onClick={() => router.push('/bot/bot-list')}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
EditBotPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'UPDATE_BOT'}>{page}</LayoutAuthenticated>
);
};
export default EditBotPage;

View File

@ -0,0 +1,180 @@
import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import { uniqueId } from 'lodash';
import React, { ReactElement, useState } from 'react';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import TableBot from '../../components/Bot/TableBot';
import BaseButton from '../../components/BaseButton';
import axios from 'axios';
import Link from 'next/link';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import CardBoxModal from '../../components/CardBoxModal';
import DragDropFilePicker from '../../components/DragDropFilePicker';
import { setRefetch, uploadCsv } from '../../stores/bot/botSlice';
import { hasPermission } from '../../helpers/userPermissions';
const BotTablesPage = () => {
const [filterItems, setFilterItems] = useState([]);
const [csvFile, setCsvFile] = useState<File | null>(null);
const [isModalActive, setIsModalActive] = useState(false);
const [showTableView, setShowTableView] = useState(false);
const { currentUser } = useAppSelector((state) => state.auth);
const dispatch = useAppDispatch();
const [filters] = useState([
{ label: 'BotName', title: 'name' },
{ label: 'Description', title: 'description' },
{ label: 'OrderCount', title: 'order_count', number: 'true' },
{
label: 'InitialOrderValue',
title: 'initial_order_value',
number: 'true',
},
{
label: 'OrderSizeIncrement',
title: 'order_size_increment',
number: 'true',
},
{ label: 'User', title: 'user' },
]);
const hasCreatePermission =
currentUser && hasPermission(currentUser, 'CREATE_BOT');
const addFilter = () => {
const newItem = {
id: uniqueId(),
fields: {
filterValue: '',
filterValueFrom: '',
filterValueTo: '',
selectedField: '',
},
};
newItem.fields.selectedField = filters[0].title;
setFilterItems([...filterItems, newItem]);
};
const getBotCSV = async () => {
const response = await axios({
url: '/bot?filetype=csv',
method: 'GET',
responseType: 'blob',
});
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'botCSV.csv';
link.click();
};
const onModalConfirm = async () => {
if (!csvFile) return;
await dispatch(uploadCsv(csvFile));
dispatch(setRefetch(true));
setCsvFile(null);
setIsModalActive(false);
};
const onModalCancel = () => {
setCsvFile(null);
setIsModalActive(false);
};
return (
<>
<Head>
<title>{getPageTitle('Bot')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='Bot'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
{hasCreatePermission && (
<BaseButton
className={'mr-3'}
href={'/bot/bot-new'}
color='info'
label='New Item'
/>
)}
<BaseButton
className={'mr-3'}
color='info'
label='Filter'
onClick={addFilter}
/>
<BaseButton
className={'mr-3'}
color='info'
label='Download CSV'
onClick={getBotCSV}
/>
{hasCreatePermission && (
<BaseButton
color='info'
label='Upload CSV'
onClick={() => setIsModalActive(true)}
/>
)}
<div className='md:inline-flex items-center ms-auto'>
<div id='delete-rows-button'></div>
</div>
<div className='md:inline-flex items-center ms-auto'>
<Link href={'/bot/bot-table'}>Switch to Table</Link>
</div>
</CardBox>
<CardBox className='mb-6' hasTable>
<TableBot
filterItems={filterItems}
setFilterItems={setFilterItems}
filters={filters}
showGrid={false}
/>
</CardBox>
</SectionMain>
<CardBoxModal
title='Upload CSV'
buttonColor='info'
buttonLabel={'Confirm'}
// buttonLabel={false ? 'Deleting...' : 'Confirm'}
isActive={isModalActive}
onConfirm={onModalConfirm}
onCancel={onModalCancel}
>
<DragDropFilePicker
file={csvFile}
setFile={setCsvFile}
formats={'.csv'}
/>
</CardBoxModal>
</>
);
};
BotTablesPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_BOT'}>{page}</LayoutAuthenticated>
);
};
export default BotTablesPage;

View File

@ -0,0 +1,148 @@
import {
mdiAccount,
mdiChartTimelineVariant,
mdiMail,
mdiUpload,
} from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement } from 'react';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import { Field, Form, Formik } from 'formik';
import FormField from '../../components/FormField';
import BaseDivider from '../../components/BaseDivider';
import BaseButtons from '../../components/BaseButtons';
import BaseButton from '../../components/BaseButton';
import FormCheckRadio from '../../components/FormCheckRadio';
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup';
import FormFilePicker from '../../components/FormFilePicker';
import FormImagePicker from '../../components/FormImagePicker';
import { SwitchField } from '../../components/SwitchField';
import { SelectField } from '../../components/SelectField';
import { SelectFieldMany } from '../../components/SelectFieldMany';
import { RichTextField } from '../../components/RichTextField';
import { create } from '../../stores/bot/botSlice';
import { useAppDispatch } from '../../stores/hooks';
import { useRouter } from 'next/router';
import moment from 'moment';
const initialValues = {
name: '',
description: '',
order_count: '',
initial_order_value: '',
order_size_increment: '',
user: '',
};
const BotNew = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const handleSubmit = async (data) => {
await dispatch(create(data));
await router.push('/bot/bot-list');
};
return (
<>
<Head>
<title>{getPageTitle('New Item')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='New Item'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='BotName'>
<Field name='name' placeholder='BotName' />
</FormField>
<FormField label='Description' hasTextareaHeight>
<Field
name='description'
as='textarea'
placeholder='Description'
/>
</FormField>
<FormField label='OrderCount'>
<Field
type='number'
name='order_count'
placeholder='OrderCount'
/>
</FormField>
<FormField label='InitialOrderValue'>
<Field
type='number'
name='initial_order_value'
placeholder='InitialOrderValue'
/>
</FormField>
<FormField label='OrderSizeIncrement'>
<Field
type='number'
name='order_size_increment'
placeholder='OrderSizeIncrement'
/>
</FormField>
<FormField label='User' labelFor='user'>
<Field
name='user'
id='user'
component={SelectField}
options={[]}
itemRef={'users'}
></Field>
</FormField>
<BaseDivider />
<BaseButtons>
<BaseButton type='submit' color='info' label='Submit' />
<BaseButton type='reset' color='info' outline label='Reset' />
<BaseButton
type='reset'
color='danger'
outline
label='Cancel'
onClick={() => router.push('/bot/bot-list')}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
BotNew.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'CREATE_BOT'}>{page}</LayoutAuthenticated>
);
};
export default BotNew;

View File

@ -0,0 +1,179 @@
import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import { uniqueId } from 'lodash';
import React, { ReactElement, useState } from 'react';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import TableBot from '../../components/Bot/TableBot';
import BaseButton from '../../components/BaseButton';
import axios from 'axios';
import Link from 'next/link';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import CardBoxModal from '../../components/CardBoxModal';
import DragDropFilePicker from '../../components/DragDropFilePicker';
import { setRefetch, uploadCsv } from '../../stores/bot/botSlice';
import { hasPermission } from '../../helpers/userPermissions';
const BotTablesPage = () => {
const [filterItems, setFilterItems] = useState([]);
const [csvFile, setCsvFile] = useState<File | null>(null);
const [isModalActive, setIsModalActive] = useState(false);
const [showTableView, setShowTableView] = useState(false);
const { currentUser } = useAppSelector((state) => state.auth);
const dispatch = useAppDispatch();
const [filters] = useState([
{ label: 'BotName', title: 'name' },
{ label: 'Description', title: 'description' },
{ label: 'OrderCount', title: 'order_count', number: 'true' },
{
label: 'InitialOrderValue',
title: 'initial_order_value',
number: 'true',
},
{
label: 'OrderSizeIncrement',
title: 'order_size_increment',
number: 'true',
},
{ label: 'User', title: 'user' },
]);
const hasCreatePermission =
currentUser && hasPermission(currentUser, 'CREATE_BOT');
const addFilter = () => {
const newItem = {
id: uniqueId(),
fields: {
filterValue: '',
filterValueFrom: '',
filterValueTo: '',
selectedField: '',
},
};
newItem.fields.selectedField = filters[0].title;
setFilterItems([...filterItems, newItem]);
};
const getBotCSV = async () => {
const response = await axios({
url: '/bot?filetype=csv',
method: 'GET',
responseType: 'blob',
});
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'botCSV.csv';
link.click();
};
const onModalConfirm = async () => {
if (!csvFile) return;
await dispatch(uploadCsv(csvFile));
dispatch(setRefetch(true));
setCsvFile(null);
setIsModalActive(false);
};
const onModalCancel = () => {
setCsvFile(null);
setIsModalActive(false);
};
return (
<>
<Head>
<title>{getPageTitle('Bot')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='Bot'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
{hasCreatePermission && (
<BaseButton
className={'mr-3'}
href={'/bot/bot-new'}
color='info'
label='New Item'
/>
)}
<BaseButton
className={'mr-3'}
color='info'
label='Filter'
onClick={addFilter}
/>
<BaseButton
className={'mr-3'}
color='info'
label='Download CSV'
onClick={getBotCSV}
/>
{hasCreatePermission && (
<BaseButton
color='info'
label='Upload CSV'
onClick={() => setIsModalActive(true)}
/>
)}
<div className='md:inline-flex items-center ms-auto'>
<div id='delete-rows-button'></div>
<Link href={'/bot/bot-list'}>
Back to <span className='capitalize'>card</span>
</Link>
</div>
</CardBox>
<CardBox className='mb-6' hasTable>
<TableBot
filterItems={filterItems}
setFilterItems={setFilterItems}
filters={filters}
showGrid={true}
/>
</CardBox>
</SectionMain>
<CardBoxModal
title='Upload CSV'
buttonColor='info'
buttonLabel={'Confirm'}
// buttonLabel={false ? 'Deleting...' : 'Confirm'}
isActive={isModalActive}
onConfirm={onModalConfirm}
onCancel={onModalCancel}
>
<DragDropFilePicker
file={csvFile}
setFile={setCsvFile}
formats={'.csv'}
/>
</CardBoxModal>
</>
);
};
BotTablesPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_BOT'}>{page}</LayoutAuthenticated>
);
};
export default BotTablesPage;

View File

@ -0,0 +1,153 @@
import React, { ReactElement, useEffect } from 'react';
import Head from 'next/head';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import dayjs from 'dayjs';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { fetch } from '../../stores/bot/botSlice';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
import LayoutAuthenticated from '../../layouts/Authenticated';
import { getPageTitle } from '../../config';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import SectionMain from '../../components/SectionMain';
import CardBox from '../../components/CardBox';
import BaseButton from '../../components/BaseButton';
import BaseDivider from '../../components/BaseDivider';
import { mdiChartTimelineVariant } from '@mdi/js';
import { SwitchField } from '../../components/SwitchField';
import FormField from '../../components/FormField';
const BotView = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const { bot } = useAppSelector((state) => state.bot);
const { id } = router.query;
function removeLastCharacter(str) {
console.log(str, `str`);
return str.slice(0, -1);
}
useEffect(() => {
dispatch(fetch({ id }));
}, [dispatch, id]);
return (
<>
<Head>
<title>{getPageTitle('View bot')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={removeLastCharacter('View bot')}
main
>
<BaseButton
color='info'
label='Edit'
href={`/bot/bot-edit/?id=${id}`}
/>
</SectionTitleLineWithButton>
<CardBox>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>BotName</p>
<p>{bot?.name}</p>
</div>
<FormField label='Multi Text' hasTextareaHeight>
<textarea className={'w-full'} disabled value={bot?.description} />
</FormField>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>OrderCount</p>
<p>{bot?.order_count || 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>InitialOrderValue</p>
<p>{bot?.initial_order_value || 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>OrderSizeIncrement</p>
<p>{bot?.order_size_increment || 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>User</p>
<p>{bot?.user?.firstName ?? 'No data'}</p>
</div>
<>
<p className={'block font-bold mb-2'}>Orders Strategy</p>
<CardBox
className='mb-6 border border-gray-300 rounded overflow-hidden'
hasTable
>
<div className='overflow-x-auto'>
<table>
<thead>
<tr>
<th>OrderValue</th>
<th>OrderDate</th>
<th>IsProfitable</th>
</tr>
</thead>
<tbody>
{bot.orders_strategy &&
Array.isArray(bot.orders_strategy) &&
bot.orders_strategy.map((item: any) => (
<tr
key={item.id}
onClick={() =>
router.push(`/orders/orders-view/?id=${item.id}`)
}
>
<td data-label='order_value'>{item.order_value}</td>
<td data-label='order_date'>
{dataFormatter.dateTimeFormatter(item.order_date)}
</td>
<td data-label='is_profitable'>
{dataFormatter.booleanFormatter(item.is_profitable)}
</td>
</tr>
))}
</tbody>
</table>
</div>
{!bot?.orders_strategy?.length && (
<div className={'text-center py-4'}>No data</div>
)}
</CardBox>
</>
<BaseDivider />
<BaseButton
color='info'
label='Back'
onClick={() => router.push('/bot/bot-list')}
/>
</CardBox>
</SectionMain>
</>
);
};
BotView.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_BOT'}>{page}</LayoutAuthenticated>
);
};
export default BotView;

View File

@ -31,7 +31,7 @@ const Dashboard = () => {
const [users, setUsers] = React.useState(loadingMessage);
const [api_keys, setApi_keys] = React.useState(loadingMessage);
const [orders, setOrders] = React.useState(loadingMessage);
const [strategies, setStrategies] = React.useState(loadingMessage);
const [bot, setBot] = React.useState(loadingMessage);
const [trading_pairs, setTrading_pairs] = React.useState(loadingMessage);
const [roles, setRoles] = React.useState(loadingMessage);
const [permissions, setPermissions] = React.useState(loadingMessage);
@ -49,7 +49,7 @@ const Dashboard = () => {
'users',
'api_keys',
'orders',
'strategies',
'bot',
'trading_pairs',
'roles',
'permissions',
@ -58,7 +58,7 @@ const Dashboard = () => {
setUsers,
setApi_keys,
setOrders,
setStrategies,
setBot,
setTrading_pairs,
setRoles,
setPermissions,
@ -280,8 +280,8 @@ const Dashboard = () => {
</Link>
)}
{hasPermission(currentUser, 'READ_STRATEGIES') && (
<Link href={'/strategies/strategies-list'}>
{hasPermission(currentUser, 'READ_BOT') && (
<Link href={'/bot/bot-list'}>
<div
className={`${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
@ -290,10 +290,10 @@ const Dashboard = () => {
<div className='flex justify-between align-center'>
<div>
<div className='text-lg leading-tight text-gray-500 dark:text-gray-400'>
Strategies
Bot
</div>
<div className='text-3xl leading-tight font-semibold'>
{strategies}
{bot}
</div>
</div>
<div>

View File

@ -103,7 +103,7 @@ const EditOrders = () => {
id='strategy'
component={SelectField}
options={initialValues.strategy}
itemRef={'strategies'}
itemRef={'bot'}
showField={'name'}
></Field>
</FormField>

View File

@ -101,7 +101,7 @@ const EditOrdersPage = () => {
id='strategy'
component={SelectField}
options={initialValues.strategy}
itemRef={'strategies'}
itemRef={'bot'}
showField={'name'}
></Field>
</FormField>

View File

@ -77,7 +77,7 @@ const OrdersNew = () => {
id='strategy'
component={SelectField}
options={[]}
itemRef={'strategies'}
itemRef={'bot'}
></Field>
</FormField>

View File

@ -103,7 +103,7 @@ const EditTrading_pairs = () => {
id='strategies'
component={SelectFieldMany}
options={initialValues.strategies}
itemRef={'strategies'}
itemRef={'bot'}
showField={'name'}
></Field>
</FormField>

View File

@ -101,7 +101,7 @@ const EditTrading_pairsPage = () => {
id='strategies'
component={SelectFieldMany}
options={initialValues.strategies}
itemRef={'strategies'}
itemRef={'bot'}
showField={'name'}
></Field>
</FormField>

View File

@ -73,7 +73,7 @@ const Trading_pairsNew = () => {
<Field
name='strategies'
id='strategies'
itemRef={'strategies'}
itemRef={'bot'}
options={[]}
component={SelectFieldMany}
></Field>

View File

@ -69,7 +69,7 @@ const Trading_pairsView = () => {
<table>
<thead>
<tr>
<th>StrategyName</th>
<th>BotName</th>
<th>Description</th>
@ -87,9 +87,7 @@ const Trading_pairsView = () => {
<tr
key={item.id}
onClick={() =>
router.push(
`/strategies/strategies-view/?id=${item.id}`,
)
router.push(`/bot/bot-view/?id=${item.id}`)
}
>
<td data-label='name'>{item.name}</td>

View File

@ -184,7 +184,7 @@ const UsersView = () => {
</>
<>
<p className={'block font-bold mb-2'}>Strategies User</p>
<p className={'block font-bold mb-2'}>Bot User</p>
<CardBox
className='mb-6 border border-gray-300 rounded overflow-hidden'
hasTable
@ -193,7 +193,7 @@ const UsersView = () => {
<table>
<thead>
<tr>
<th>StrategyName</th>
<th>BotName</th>
<th>Description</th>
@ -205,15 +205,13 @@ const UsersView = () => {
</tr>
</thead>
<tbody>
{users.strategies_user &&
Array.isArray(users.strategies_user) &&
users.strategies_user.map((item: any) => (
{users.bot_user &&
Array.isArray(users.bot_user) &&
users.bot_user.map((item: any) => (
<tr
key={item.id}
onClick={() =>
router.push(
`/strategies/strategies-view/?id=${item.id}`,
)
router.push(`/bot/bot-view/?id=${item.id}`)
}
>
<td data-label='name'>{item.name}</td>
@ -234,7 +232,7 @@ const UsersView = () => {
</tbody>
</table>
</div>
{!users?.strategies_user?.length && (
{!users?.bot_user?.length && (
<div className={'text-center py-4'}>No data</div>
)}
</CardBox>

View File

@ -0,0 +1,236 @@
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axios from 'axios';
import {
fulfilledNotify,
rejectNotify,
resetNotify,
} from '../../helpers/notifyStateHandler';
interface MainState {
bot: any;
loading: boolean;
count: number;
refetch: boolean;
rolesWidgets: any[];
notify: {
showNotification: boolean;
textNotification: string;
typeNotification: string;
};
}
const initialState: MainState = {
bot: [],
loading: false,
count: 0,
refetch: false,
rolesWidgets: [],
notify: {
showNotification: false,
textNotification: '',
typeNotification: 'warn',
},
};
export const fetch = createAsyncThunk('bot/fetch', async (data: any) => {
const { id, query } = data;
const result = await axios.get(`bot${query || (id ? `/${id}` : '')}`);
return id
? result.data
: { rows: result.data.rows, count: result.data.count };
});
export const deleteItemsByIds = createAsyncThunk(
'bot/deleteByIds',
async (data: any, { rejectWithValue }) => {
try {
await axios.post('bot/deleteByIds', { data });
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const deleteItem = createAsyncThunk(
'bot/deleteBot',
async (id: string, { rejectWithValue }) => {
try {
await axios.delete(`bot/${id}`);
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const create = createAsyncThunk(
'bot/createBot',
async (data: any, { rejectWithValue }) => {
try {
const result = await axios.post('bot', { data });
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const uploadCsv = createAsyncThunk(
'bot/uploadCsv',
async (file: File, { rejectWithValue }) => {
try {
const data = new FormData();
data.append('file', file);
data.append('filename', file.name);
const result = await axios.post('bot/bulk-import', data, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const update = createAsyncThunk(
'bot/updateBot',
async (payload: any, { rejectWithValue }) => {
try {
const result = await axios.put(`bot/${payload.id}`, {
id: payload.id,
data: payload.data,
});
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const botSlice = createSlice({
name: 'bot',
initialState,
reducers: {
setRefetch: (state, action: PayloadAction<boolean>) => {
state.refetch = action.payload;
},
},
extraReducers: (builder) => {
builder.addCase(fetch.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(fetch.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(fetch.fulfilled, (state, action) => {
if (action.payload.rows && action.payload.count >= 0) {
state.bot = action.payload.rows;
state.count = action.payload.count;
} else {
state.bot = action.payload;
}
state.loading = false;
});
builder.addCase(deleteItemsByIds.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(deleteItemsByIds.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, 'Bot has been deleted');
});
builder.addCase(deleteItemsByIds.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(deleteItem.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(deleteItem.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, `${'Bot'.slice(0, -1)} has been deleted`);
});
builder.addCase(deleteItem.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(create.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(create.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(create.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, `${'Bot'.slice(0, -1)} has been created`);
});
builder.addCase(update.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(update.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, `${'Bot'.slice(0, -1)} has been updated`);
});
builder.addCase(update.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(uploadCsv.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(uploadCsv.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, 'Bot has been uploaded');
});
builder.addCase(uploadCsv.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
},
});
// Action creators are generated for each case reducer function
export const { setRefetch } = botSlice.actions;
export default botSlice.reducer;

View File

@ -7,7 +7,7 @@ import openAiSlice from './openAiSlice';
import usersSlice from './users/usersSlice';
import api_keysSlice from './api_keys/api_keysSlice';
import ordersSlice from './orders/ordersSlice';
import strategiesSlice from './strategies/strategiesSlice';
import botSlice from './bot/botSlice';
import trading_pairsSlice from './trading_pairs/trading_pairsSlice';
import rolesSlice from './roles/rolesSlice';
import permissionsSlice from './permissions/permissionsSlice';
@ -22,7 +22,7 @@ export const store = configureStore({
users: usersSlice,
api_keys: api_keysSlice,
orders: ordersSlice,
strategies: strategiesSlice,
bot: botSlice,
trading_pairs: trading_pairsSlice,
roles: rolesSlice,
permissions: permissionsSlice,