Skip to content

Commit

Permalink
Merge branch 'main' into publish-on-nostr-only-basic-order-status
Browse files Browse the repository at this point in the history
  • Loading branch information
grunch authored Oct 18, 2024
2 parents 370b8d2 + 5672c6f commit 1a64951
Show file tree
Hide file tree
Showing 39 changed files with 5,235 additions and 2,689 deletions.
17 changes: 15 additions & 2 deletions bot/modules/community/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ exports.onCommunityInfo = async ctx => {
const orderCount = await getOrdersNDays(1, commId);
const volume = await getVolumeNDays(1, commId);

const creator = await User.findById(community.creator_id);

let orderChannelsText = '';
if (community.order_channels.length === 1) {
orderChannelsText = `${community.order_channels[0].name} (${community.order_channels[0].type})`;
} else if (community.order_channels.length === 2) {
orderChannelsText = `${community.order_channels[0].name} (${community.order_channels[0].type}) ${community.order_channels[1].name} (${community.order_channels[1].type})`;
}

const options = { year: 'numeric', month: 'short', day: 'numeric' };
const formatDate = community.created_at.toLocaleDateString('en-US', options);

const rows = [];
rows.push([
{ text: ctx.i18n.t('orders') + ' 24hs', callback_data: 'none' },
Expand All @@ -62,13 +74,14 @@ exports.onCommunityInfo = async ctx => {
{ text: ctx.i18n.t('users'), callback_data: 'none' },
{ text: userCount, callback_data: 'none' },
]);

rows.push([
{
text: ctx.i18n.t('use_default'),
callback_data: `setCommunity_${commId}`,
},
]);
const text = `${community.name}\n${community.group}`;
const text = `${community.name}: ${community.group} \nCreator: @${creator.username} \nOrder Channels: ${orderChannelsText} \nFee: ${community.fee} \nCreated At: ${formatDate}`;
await ctx.reply(text, {
reply_markup: { inline_keyboard: rows },
});
Expand All @@ -90,4 +103,4 @@ exports.withdrawEarnings = async ctx => {
ctx.scene.enter('ADD_EARNINGS_INVOICE_WIZARD_SCENE_ID', {
community,
});
};
};
45 changes: 28 additions & 17 deletions bot/modules/dispute/messages.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
const { getDisputeChannel, getDetailedOrder } = require('../../../util');
const {
getDisputeChannel,
getDetailedOrder,
sanitizeMD,
} = require('../../../util');
const { logger } = require('../../../logger');

exports.beginDispute = async (ctx, initiator, order, buyer, seller) => {
Expand Down Expand Up @@ -87,22 +91,29 @@ exports.disputeData = async (
}

const detailedOrder = getDetailedOrder(ctx.i18n, order, buyer, seller);
await ctx.telegram.sendMessage(
solver.tg_id,
ctx.i18n.t('dispute_started_channel', {
initiatorUser,
counterPartyUser,
buyer,
seller,
buyerDisputes,
sellerDisputes,
detailedOrder,
type,
sellerToken: order.seller_dispute_token,
buyerToken: order.buyer_dispute_token,
}),
{ parse_mode: 'MarkdownV2' }
);

// Fix Issue 543: Escape underscores in usernames
const escapedInitiatorUsername = sanitizeMD(initiatorUser.username);
const escapedCounterPartyUsername = sanitizeMD(counterPartyUser.username);

const message = ctx.i18n.t('dispute_started_channel', {
initiatorUser: escapedInitiatorUsername,
initiatorTgId: initiatorUser.tg_id,
counterPartyUser: escapedCounterPartyUsername,
counterPartyUserTgId: counterPartyUser.tg_id,
buyer,
seller,
buyerDisputes,
sellerDisputes,
detailedOrder,
type,
sellerToken: order.seller_dispute_token,
buyerToken: order.buyer_dispute_token,
});
console.log(`Contens of message:\n${message}`);
await ctx.telegram.sendMessage(solver.tg_id, message, {
parse_mode: 'MarkdownV2',
});
// message to both parties letting them know the dispute
// has been taken by a solver
await ctx.telegram.sendMessage(
Expand Down
73 changes: 40 additions & 33 deletions bot/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,17 @@ import { Message } from 'typegram'
import { UserDocument } from '../models/user'
import { FilterQuery } from 'mongoose';
const OrderEvents = require('./modules/events/orders');

const { limit } = require('@grammyjs/ratelimiter');
import { limit } from "@grammyjs/ratelimiter"
const schedule = require('node-schedule');
const {
import {
Order,
User,
PendingPayment,
Community,
Dispute,
Config,
} = require('../models');
const { getCurrenciesWithPrice, deleteOrderFromChannel, removeAtSymbol } = require('../util');
} from '../models';
import { getCurrenciesWithPrice, deleteOrderFromChannel, removeAtSymbol } from '../util';
const {
commandArgsMiddleware,
stageMiddleware,
Expand Down Expand Up @@ -55,32 +54,34 @@ const {
validateLightningAddress,
} = require('./validations');
import * as messages from './messages';
const {
import {
attemptPendingPayments,
cancelOrders,
deleteOrders,
calculateEarnings,
attemptCommunitiesPendingPayments,
deleteCommunity,
nodeInfo,
} = require('../jobs');
const { logger } = require('../logger');
} from '../jobs';
import { logger } from "../logger";
import { ICommunity, IUsernameId } from '../models/community';

export interface MainContext extends Context {
match: Array<string> | null;
i18n: I18nContext;
user: UserDocument;
admin: UserDocument;
}

interface OrderQuery {
export interface OrderQuery {
status?: string;
buyer_id?: string;
seller_id?: string;
}

const askForConfirmation = async (user: UserDocument, command: string) => {
try {
let orders = [];
let orders: any[] = [];
if (command === '/cancel') {
const where: FilterQuery<OrderQuery> = {
$and: [
Expand Down Expand Up @@ -133,6 +134,7 @@ const askForConfirmation = async (user: UserDocument, command: string) => {
return orders;
} catch (error) {
logger.error(error);
return null;
}
};

Expand All @@ -145,7 +147,7 @@ has the same condition.
The problem mentioned above is similar to this issue:
https://github.com/telegraf/telegraf/issues/1319#issuecomment-766360594
*/
const ctxUpdateAssertMsg = "ctx.update.message.text is not available.";
export const ctxUpdateAssertMsg = "ctx.update.message.text is not available.";

const initialize = (botToken: string, options: Partial<Telegraf.Options<MainContext>>): Telegraf<MainContext> => {
const i18n = new I18n({
Expand Down Expand Up @@ -215,7 +217,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
const [val] = await validateParams(ctx, 2, '\\<_on/off_\\>');
if (!val) return;
let config = await Config.findOne();
if (!config) {
if (config === null) {
config = new Config();
}
config.maintenance = false;
Expand Down Expand Up @@ -262,11 +264,11 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
throw new Error(ctxUpdateAssertMsg);
}
const params = ctx.update.message.text.split(' ');
const [command, orderId] = params.filter((el) => el);
const [command, orderId] = params.filter((el: string) => el);

if (!orderId) {
const orders = await askForConfirmation(ctx.user, command);
if (!orders.length) return await ctx.reply(`${command} <order Id>`);
if (orders === null || orders.length === 0) return await ctx.reply(`${command} <order Id>`);

return await messages.showConfirmationButtons(ctx, orders, command);
} else if (!(await validateObjectId(ctx, orderId))) {
Expand Down Expand Up @@ -324,7 +326,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
if (!(await validateObjectId(ctx, orderId))) return;
const order = await Order.findOne({ _id: orderId });

if (!order) return;
if (order === null) return;

// We look for a dispute for this order
const dispute = await Dispute.findOne({ order_id: order._id });
Expand Down Expand Up @@ -366,11 +368,12 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont

order.status = 'CANCELED_BY_ADMIN';
order.canceled_by = ctx.admin._id;
const buyer = await User.findOne({ _id: order.buyer_id });
const seller = await User.findOne({ _id: order.seller_id });
await order.save();
order.status = 'CANCELED';
OrderEvents.orderUpdated(order);
const buyer = await User.findOne({ _id: order.buyer_id });
const seller = await User.findOne({ _id: order.seller_id });
if (buyer === null || seller === null) throw Error("buyer and/or seller were not found in DB");
// we sent a private message to the admin
await messages.successCancelOrderMessage(ctx, ctx.admin, order, ctx.i18n);
// we sent a private message to the seller
Expand All @@ -390,11 +393,11 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
throw new Error(ctxUpdateAssertMsg);
}
const params = ctx.update.message.text.split(' ');
const [command, orderId] = params.filter((el) => el);
const [command, orderId] = params.filter((el: string) => el);

if (!orderId) {
const orders = await askForConfirmation(ctx.user, command);
if (!orders.length) return await ctx.reply(`${command} <order Id>`);
if (orders === null || orders.length === 0) return await ctx.reply(`${command} <order Id>`);

return await messages.showConfirmationButtons(ctx, orders, command);
} else if (!(await validateObjectId(ctx, orderId))) {
Expand Down Expand Up @@ -445,7 +448,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
await order.save();
OrderEvents.orderUpdated(order);
// We delete the messages related to that order from the channel
await deleteOrderFromChannel(order, bot.telegram);
await deleteOrderFromChannel(order, bot.telegram as any);
}
// we sent a private message to the user
await messages.successCancelAllOrdersMessage(ctx);
Expand All @@ -462,7 +465,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
if (!(await validateObjectId(ctx, orderId))) return;

const order = await Order.findOne({ _id: orderId });
if (!order) return;
if (order === null) return;

// Check if the order status is already PAID_HOLD_INVOICE
if (order.status === 'PAID_HOLD_INVOICE') {
Expand Down Expand Up @@ -498,9 +501,10 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
}

order.status = 'COMPLETED_BY_ADMIN';
await order.save();
const buyer = await User.findOne({ _id: order.buyer_id });
const seller = await User.findOne({ _id: order.seller_id });
await order.save();
if (buyer === null || seller === null) throw Error("buyer and/or seller were not found in DB");
// we sent a private message to the admin
await messages.successCompleteOrderMessage(ctx, order);
// we sent a private message to the seller
Expand All @@ -524,11 +528,11 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
if (!(await validateObjectId(ctx, orderId))) return;
const order = await Order.findOne({ _id: orderId });

if (!order) return;
if (order === null) return;

const buyer = await User.findOne({ _id: order.buyer_id });
const seller = await User.findOne({ _id: order.seller_id });

if (buyer === null || seller === null) throw Error("buyer and/or seller were not found in DB");
await messages.checkOrderMessage(ctx, order, buyer, seller);
} catch (error) {
logger.error(error);
Expand All @@ -542,7 +546,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
if (!(await validateObjectId(ctx, orderId))) return;
const order = await Order.findOne({ _id: orderId });

if (!order) return;
if (order === null) return;
if (!order.hash) return;

const invoice = await getInvoice({ hash: order.hash });
Expand All @@ -566,7 +570,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont

const order = await Order.findOne({ hash });

if (!order) return;
if (order === null) return;
await subscribeInvoice(bot, hash, true);
ctx.reply(`hash resubscribed`);
} catch (error: any) {
Expand Down Expand Up @@ -605,11 +609,11 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
throw new Error(ctxUpdateAssertMsg);
}
const params = ctx.update.message.text.split(' ');
const [command, orderId] = params.filter((el) => el);
const [command, orderId] = params.filter((el: string) => el);

if (!orderId) {
const orders = await askForConfirmation(ctx.user, command);
if (!orders.length) return await ctx.reply(`${command} <order Id>`);
if (orders === null || orders.length === 0) return await ctx.reply(`${command} <order Id>`);

return await messages.showConfirmationButtons(ctx, orders, command);
} else if (!(await validateObjectId(ctx, orderId))) {
Expand All @@ -636,7 +640,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
const user = await User.findOne({
$or: [{ username }, { tg_id: username }],
});
if (!user) {
if (user === null) {
await messages.notFoundUserMessage(ctx);
return;
}
Expand All @@ -647,6 +651,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
const community = await Community.findById(
ctx.admin.default_community_id
);
if (community === null) throw Error("Community was not found in DB");
community.banned_users.push({
id: user._id,
username: user.username,
Expand Down Expand Up @@ -679,7 +684,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
const user = await User.findOne({
$or: [{ username }, { tg_id: username }],
});
if (!user) {
if (user === null) {
await messages.notFoundUserMessage(ctx);
return;
}
Expand All @@ -690,8 +695,9 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
const community = await Community.findById(
ctx.admin.default_community_id
);
community.banned_users = community.banned_users.filter(
(el: any) => el.id !== user.id
if (community === null) throw Error("Community was not found in DB");
community.banned_users = community.banned_users.toObject().filter(
(el: IUsernameId) => el.id !== user.id
);
await community.save();
} else {
Expand Down Expand Up @@ -738,7 +744,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
try {
const command = '/setinvoice';
const orders = await askForConfirmation(ctx.user, command);
if (!orders.length) return await ctx.reply(ctx.i18n.t('setinvoice_no_response'));
if (orders === null || !orders.length) return await ctx.reply(ctx.i18n.t('setinvoice_no_response'));

return await messages.showConfirmationButtons(ctx, orders, command);
} catch (error) {
Expand Down Expand Up @@ -858,6 +864,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
bot.command('info', userMiddleware, async (ctx: MainContext) => {
try {
const config = await Config.findOne({});
if (config === null) throw Error("Config was not found in DB");
await messages.showInfoMessage(ctx, ctx.user, config);
} catch (error) {
logger.error(error);
Expand Down
Loading

0 comments on commit 1a64951

Please sign in to comment.