Skip to content

Commit

Permalink
lnp2pBot#371 take actions refactor (lnp2pBot#387)
Browse files Browse the repository at this point in the history
  • Loading branch information
dolchi21 authored Sep 5, 2023
1 parent afeb052 commit f57ea9f
Show file tree
Hide file tree
Showing 7 changed files with 135 additions and 93 deletions.
75 changes: 0 additions & 75 deletions bot/commands.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
const {
validateSeller,
validateObjectId,
validateTakeBuyOrder,
validateTakeSellOrder,
validateUserWaitingOrder,
isBannedFromCommunity,
validateFiatSentOrder,
validateReleaseOrder,
} = require('./validations');
Expand All @@ -18,7 +12,6 @@ const { Order, User, Dispute } = require('../models');
const messages = require('./messages');
const {
getBtcFiatPrice,
extractId,
deleteOrderFromChannel,
getUserI18nContext,
getFee,
Expand All @@ -28,72 +21,6 @@ const ordersActions = require('./ordersActions');
const { resolvLightningAddress } = require('../lnurl/lnurl-pay');
const logger = require('../logger');

const takebuy = async (ctx, bot) => {
try {
const text = ctx.update.callback_query.message.text;
if (!text) return;

const { user } = ctx;

if (!(await validateUserWaitingOrder(ctx, bot, user))) return;

// Sellers with orders in status = FIAT_SENT, have to solve the order
const isOnFiatSentStatus = await validateSeller(ctx, user);

if (!isOnFiatSentStatus) return;
const orderId = extractId(text);
if (!orderId) return;
if (!(await validateObjectId(ctx, orderId))) return;
const order = await Order.findOne({ _id: orderId });
if (!order) return;
// We verify if the user is not banned on this community
if (await isBannedFromCommunity(user, order.community_id))
return await messages.bannedUserErrorMessage(ctx, user);

if (!(await validateTakeBuyOrder(ctx, bot, user, order))) return;
// We change the status to trigger the expiration of this order
// if the user don't do anything
order.status = 'WAITING_PAYMENT';
order.seller_id = user._id;
order.taken_at = Date.now();
await order.save();
// We delete the messages related to that order from the channel
await deleteOrderFromChannel(order, bot.telegram);
await messages.beginTakeBuyMessage(ctx, bot, user, order);
} catch (error) {
logger.error(error);
}
};

const takesell = async (ctx, bot) => {
try {
const text = ctx.update.callback_query.message.text;
if (!text) return;

const { user } = ctx;

if (!(await validateUserWaitingOrder(ctx, bot, user))) return;
const orderId = extractId(text);
if (!orderId) return;
const order = await Order.findOne({ _id: orderId });
if (!order) return;
// We verify if the user is not banned on this community
if (await isBannedFromCommunity(user, order.community_id))
return await messages.bannedUserErrorMessage(ctx, user);
if (!(await validateTakeSellOrder(ctx, bot, user, order))) return;
order.status = 'WAITING_BUYER_INVOICE';
order.buyer_id = user._id;
order.taken_at = Date.now();

await order.save();
// We delete the messages related to that order from the channel
await deleteOrderFromChannel(order, bot.telegram);
await messages.beginTakeSellMessage(ctx, bot, user, order);
} catch (error) {
logger.error(error);
}
};

const waitPayment = async (ctx, bot, buyer, seller, order, buyerInvoice) => {
try {
// If there is not fiat amount the function don't do anything
Expand Down Expand Up @@ -788,8 +715,6 @@ const release = async (ctx, orderId, user) => {
};

module.exports = {
takebuy,
takesell,
rateUser,
saveUserReview,
cancelAddInvoice,
Expand Down
10 changes: 7 additions & 3 deletions bot/messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const {
sanitizeMD,
getEmojiRate,
decimalRound,
getUserAge
getUserAge,
} = require('../util');
const logger = require('../logger');

Expand Down Expand Up @@ -81,7 +81,7 @@ const invoicePaymentRequestMessage = async (
order,
expirationTime,
rate,
days: ageInDays
days: ageInDays,
});
await ctx.telegram.sendMessage(user.tg_id, message);
// Create QR code
Expand Down Expand Up @@ -402,7 +402,11 @@ const onGoingTakeBuyMessage = async (
const ageInDays = getUserAge(seller);
await bot.telegram.sendMessage(
buyer.tg_id,
i18nBuyer.t('someone_took_your_order', { expirationTime, rate, days: ageInDays })
i18nBuyer.t('someone_took_your_order', {
expirationTime,
rate,
days: ageInDays,
})
);
await bot.telegram.sendMessage(buyer.tg_id, order._id, {
reply_markup: {
Expand Down
34 changes: 34 additions & 0 deletions bot/modules/orders/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ const ordersActions = require('../../ordersActions');
const commands = require('./commands');
const messages = require('./messages');
const { tooManyPendingOrdersMessage } = require('../../messages');
const {
takeOrderActionValidation,
takeOrderValidation,
takesell,
takebuyValidation,
takebuy,
} = require('./takeOrder');
const { extractId } = require('../../../util');
exports.Scenes = require('./scenes');

exports.configure = bot => {
Expand Down Expand Up @@ -52,4 +60,30 @@ exports.configure = bot => {
return logger.error(error);
}
});

bot.action(
'takesell',
userMiddleware,
takeOrderActionValidation,
takeOrderValidation,
async ctx => {
const text = ctx.update.callback_query.message.text;
const orderId = extractId(text);
if (!orderId) return;
await takesell(ctx, bot, orderId);
}
);
bot.action(
'takebuy',
userMiddleware,
takeOrderActionValidation,
takeOrderValidation,
takebuyValidation,
async ctx => {
const text = ctx.update.callback_query.message.text;
const orderId = extractId(text);
if (!orderId) return;
await takebuy(ctx, bot, orderId);
}
);
};
89 changes: 89 additions & 0 deletions bot/modules/orders/takeOrder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// @ts-check
const logger = require('../../../logger');
const { Order } = require('../../../models');
const { deleteOrderFromChannel } = require('../../../util');
const messages = require('../../messages');
const {
validateUserWaitingOrder,
isBannedFromCommunity,
validateTakeSellOrder,
validateSeller,
validateObjectId,
validateTakeBuyOrder,
} = require('../../validations');

exports.takeOrderActionValidation = async (ctx, next) => {
try {
const text = ctx.update.callback_query.message.text;
if (!text) return;
next();
} catch (err) {
logger.error(err);
}
};
exports.takeOrderValidation = async (ctx, next) => {
try {
const { user } = ctx;
if (!(await validateUserWaitingOrder(ctx, ctx, user))) return;
next();
} catch (err) {
logger.error(err);
}
};
exports.takebuyValidation = async (ctx, next) => {
try {
// Sellers with orders in status = FIAT_SENT, have to solve the order
const isOnFiatSentStatus = await validateSeller(ctx, ctx.user);
if (!isOnFiatSentStatus) return;
next();
} catch (err) {
logger.error(err);
}
};
exports.takebuy = async (ctx, bot, orderId) => {
try {
if (!orderId) return;
const { user } = ctx;
if (!(await validateObjectId(ctx, orderId))) return;
const order = await Order.findOne({ _id: orderId });
if (!order) return;
// We verify if the user is not banned on this community
if (await isBannedFromCommunity(user, order.community_id))
return await messages.bannedUserErrorMessage(ctx, user);

if (!(await validateTakeBuyOrder(ctx, bot, user, order))) return;
// We change the status to trigger the expiration of this order
// if the user don't do anything
order.status = 'WAITING_PAYMENT';
order.seller_id = user._id;
order.taken_at = Date.now();
await order.save();
// We delete the messages related to that order from the channel
await deleteOrderFromChannel(order, bot.telegram);
await messages.beginTakeBuyMessage(ctx, bot, user, order);
} catch (error) {
logger.error(error);
}
};
exports.takesell = async (ctx, bot, orderId) => {
try {
const { user } = ctx;
if (!orderId) return;
const order = await Order.findOne({ _id: orderId });
if (!order) return;
// We verify if the user is not banned on this community
if (await isBannedFromCommunity(user, order.community_id))
return await messages.bannedUserErrorMessage(ctx, user);
if (!(await validateTakeSellOrder(ctx, bot, user, order))) return;
order.status = 'WAITING_BUYER_INVOICE';
order.buyer_id = user._id;
order.taken_at = Date.now();

await order.save();
// We delete the messages related to that order from the channel
await deleteOrderFromChannel(order, bot.telegram);
await messages.beginTakeSellMessage(ctx, bot, user, order);
} catch (error) {
logger.error(error);
}
};
2 changes: 1 addition & 1 deletion bot/ordersActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const {
getEmojiRate,
decimalRound,
getFee,
getUserAge
getUserAge,
} = require('../util');
const logger = require('../logger');

Expand Down
12 changes: 1 addition & 11 deletions bot/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ const OrdersModule = require('./modules/orders');
const UserModule = require('./modules/user');
const DisputeModule = require('./modules/dispute');
const {
takebuy,
takesell,
rateUser,
cancelAddInvoice,
addInvoice,
Expand Down Expand Up @@ -252,15 +250,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
CommunityModule.configure(bot);
LanguageModule.configure(bot);

bot.action('takesell', userMiddleware, async (ctx: MainContext) => {
await takesell(ctx, bot);
});

bot.action('takebuy', userMiddleware, async (ctx: MainContext) => {
await takebuy(ctx, bot);
});

bot.command('release', userMiddleware, async (ctx: MainContext) => {
bot.command('release', userMiddleware, async ctx => {
try {
if (!('message' in ctx.update) || !('text' in ctx.update.message)){
throw new Error(ctxUpdateAssertMsg);
Expand Down
6 changes: 3 additions & 3 deletions util/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -419,14 +419,14 @@ const holdInvoiceExpirationInSecs = () => {
};

// Returns the user age in days
const getUserAge = (user) => {
const getUserAge = user => {
const userCreationDate = new Date(user.created_at);
const today = new Date();
const ageInDays = Math.floor(
(today.getTime() - userCreationDate.getTime()) / (1000 * 3600 * 24)
);
return ageInDays
}
return ageInDays;
};

/**
* Returns order expiration time text
Expand Down

0 comments on commit f57ea9f

Please sign in to comment.