Skip to content

Commit

Permalink
bot/modules/community: convert to TS (#623)
Browse files Browse the repository at this point in the history
Convert bot/modules/community module to TypeScript.
  • Loading branch information
webwarrior-ws authored Jan 23, 2025
1 parent 67cf255 commit 27d31b5
Show file tree
Hide file tree
Showing 7 changed files with 267 additions and 204 deletions.
Original file line number Diff line number Diff line change
@@ -1,28 +1,37 @@
const { Community, Order, User } = require('../../../models');
import { ExtraReplyMessage } from 'telegraf/typings/telegram-types';
import { Community, Order, User } from '../../../models';
import { MainContext } from '../../start';
import { CommunityContext } from './communityContext';

const getOrdersNDays = async (days, communityId) => {
interface OrderFilter {
status: string;
created_at: any;
community_id?: string;
}

const getOrdersNDays = async (days: number, communityId: (string | undefined)) => {
const yesterday = new Date();
yesterday.setHours(yesterday.getHours() - days * 24);
const filter = {
status: 'SUCCESS',
created_at: {
$gte: yesterday,
},
};
} as OrderFilter;
if (communityId) filter.community_id = communityId;

return Order.count(filter);
};

const getVolumeNDays = async (days, communityId) => {
const getVolumeNDays = async (days: number, communityId: (string | undefined)) => {
const yesterday = new Date();
yesterday.setHours(yesterday.getHours() - days * 24);
const filter = {
status: 'SUCCESS',
created_at: {
$gte: yesterday,
},
};
} as OrderFilter;
if (communityId) filter.community_id = communityId;
const [row] = await Order.aggregate([
{
Expand All @@ -42,14 +51,18 @@ const getVolumeNDays = async (days, communityId) => {
return row.amount;
};

exports.onCommunityInfo = async ctx => {
const commId = ctx.match[1];
export const onCommunityInfo = async (ctx: MainContext) => {
const commId = ctx.match?.[1];
const community = await Community.findById(commId);
if(community === null)
throw new Error("community not found");
const userCount = await User.count({ default_community_id: commId });
const orderCount = await getOrdersNDays(1, commId);
const volume = await getVolumeNDays(1, commId);

const creator = await User.findById(community.creator_id);
if(creator === null)
throw new Error("creator not found");

let orderChannelsText = '';
if (community.order_channels.length === 1) {
Expand All @@ -58,7 +71,7 @@ exports.onCommunityInfo = async ctx => {
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 options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'short', day: 'numeric' };
const formatDate = community.created_at.toLocaleDateString('en-US', options);

const rows = [];
Expand All @@ -84,22 +97,22 @@ exports.onCommunityInfo = async ctx => {
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 },
});
} as ExtraReplyMessage);
};

exports.onSetCommunity = async ctx => {
const tgId = ctx.update.callback_query.from.id;
const defaultCommunityId = ctx.match[1];
export const onSetCommunity = async (ctx: CommunityContext) => {
const tgId = (ctx.update as any).callback_query.from.id;
const defaultCommunityId = ctx.match?.[1];
await User.findOneAndUpdate(
{ tg_id: tgId },
{ default_community_id: defaultCommunityId }
);
await ctx.reply(ctx.i18n.t('operation_successful'));
};

exports.withdrawEarnings = async ctx => {
export const withdrawEarnings = async (ctx: CommunityContext) => {
ctx.deleteMessage();
const community = await Community.findById(ctx.match[1]);
const community = await Community.findById(ctx.match?.[1]);
ctx.scene.enter('ADD_EARNINGS_INVOICE_WIZARD_SCENE_ID', {
community,
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
/* eslint-disable no-underscore-dangle */
// @ts-check
const { logger } = require('../../../logger');
const { showUserCommunitiesMessage } = require('./messages');
const { Community, Order } = require('../../../models');
const { validateParams, validateObjectId } = require('../../validations');

async function getOrderCountByCommunity() {
import { logger } from '../../../logger';
import { showUserCommunitiesMessage } from './messages';
import { Community, Order } from '../../../models';
import { validateParams, validateObjectId } from '../../validations';
import { MainContext } from '../../start';
import { CommunityContext } from './communityContext';
import { Telegraf } from 'telegraf';

async function getOrderCountByCommunity(): Promise<number[]> {
const data = await Order.aggregate([
{ $group: { _id: '$community_id', total: { $count: {} } } },
]);
Expand All @@ -15,7 +18,7 @@ async function getOrderCountByCommunity() {
}, {});
}

async function findCommunities(currency) {
async function findCommunities(currency: string) {
const communities = await Community.find({
currencies: currency,
public: true,
Expand All @@ -28,21 +31,18 @@ async function findCommunities(currency) {
});
}

exports.setComm = async ctx => {
export const setComm = async (ctx: MainContext) => {
try {
const { user } = ctx;

const [groupName] = await validateParams(
const [groupName] = (await validateParams(
ctx,
2,
'\\<_@communityGroupName \\| telegram\\-group\\-id / off_\\>'
);
if (!groupName) {
return;
}
))!;

if (groupName === 'off') {
user.default_community_id = null;
user.default_community_id = undefined;
await user.save();
return await ctx.reply(ctx.i18n.t('no_default_community'));
}
Expand All @@ -67,15 +67,14 @@ exports.setComm = async ctx => {
}
};

exports.communityAdmin = async ctx => {
export const communityAdmin = async (ctx: CommunityContext) => {
try {
const [group] = await validateParams(ctx, 2, '\\<_community_\\>');
if (!group) return;
const [group] = (await validateParams(ctx, 2, '\\<_community_\\>'))!;
const creator_id = ctx.user.id;
const [community] = await Community.find({ group, creator_id });
if (!community) throw new Error('CommunityNotFound');
await ctx.scene.enter('COMMUNITY_ADMIN', { community });
} catch (err) {
} catch (err: any) {
switch (err.message) {
case 'CommunityNotFound': {
return ctx.reply(ctx.i18n.t('community_not_found'));
Expand All @@ -87,7 +86,7 @@ exports.communityAdmin = async ctx => {
}
};

exports.myComms = async ctx => {
export const myComms = async (ctx: MainContext) => {
try {
const { user } = ctx;

Expand All @@ -102,10 +101,9 @@ exports.myComms = async ctx => {
}
};

exports.findCommunity = async ctx => {
export const findCommunity = async (ctx: CommunityContext) => {
try {
const [fiatCode] = await validateParams(ctx, 2, '\\<_fiat code_\\>');
if (!fiatCode) return;
const [fiatCode] = (await validateParams(ctx, 2, '\\<_fiat code_\\>'))!;

const communities = await findCommunities(fiatCode.toUpperCase());
if (!communities.length) {
Expand All @@ -132,11 +130,11 @@ exports.findCommunity = async ctx => {
}
};

exports.updateCommunity = async (ctx, id, field, bot) => {
export const updateCommunity = async (ctx: CommunityContext, id: string, field: string, bot?: Telegraf<CommunityContext>) => {
try {
ctx.deleteMessage();
if (!id) return;
const tgUser = ctx.update.callback_query.from;
const tgUser = (ctx.update as any).callback_query.from;
if (!tgUser) return;
const { user } = ctx;

Expand Down Expand Up @@ -203,10 +201,12 @@ exports.updateCommunity = async (ctx, id, field, bot) => {
}
};

exports.deleteCommunity = async ctx => {
export const deleteCommunity = async (ctx: CommunityContext) => {
try {
ctx.deleteMessage();
const id = ctx.match[1];
const id = ctx.match?.[1];
if(id === undefined)
throw new Error("id is undefined");

if (!(await validateObjectId(ctx, id))) return;
const community = await Community.findOne({
Expand All @@ -225,10 +225,12 @@ exports.deleteCommunity = async ctx => {
}
};

exports.changeVisibility = async ctx => {
export const changeVisibility = async (ctx: CommunityContext) => {
try {
ctx.deleteMessage();
const id = ctx.match[1];
const id = ctx.match?.[1];
if(id === undefined)
throw new Error("id is undefined");

if (!(await validateObjectId(ctx, id))) return;
const community = await Community.findOne({
Expand Down
35 changes: 35 additions & 0 deletions bot/modules/community/communityContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { MainContext } from '../../start';
import { SceneContextScene, WizardContextWizard, WizardSessionData } from 'telegraf/typings/scenes';
import { Update, Message } from 'telegraf/typings/core/types/typegram';
import { Scenes, Telegraf } from 'telegraf';
import { ICommunity, IOrderChannel, IUsernameId } from '../../../models/community';

export interface CommunityContext extends MainContext {
scene: SceneContextScene<CommunityContext, WizardSessionData>;
wizard: CommunityWizard;
message: (Update.New & Update.NonChannel & Message.TextMessage) | undefined;
}

export interface CommunityWizardState {
name: string;
currencies: any;
group: any;
channels: IOrderChannel[];
fee: number;
solvers: IUsernameId[];
disputeChannel: any;
user: any;
statusMessage: any;
currentStatusText: string;
community: ICommunity;
bot: Telegraf<CommunityContext>;
message: Message.TextMessage | undefined;
error?: any;
updateUI: (() => Promise<void>);
handler?: ((ctx: CommunityContext) => Promise<any>);
}

export interface CommunityWizard extends WizardContextWizard<CommunityContext> {
state: CommunityWizardState;
bot: Telegraf<CommunityContext>;
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
// @ts-check
import { Telegraf } from 'telegraf';
const { userMiddleware } = require('../../middleware/user');
const actions = require('./actions');
const commands = require('./commands');
const {
earningsMessage,
updateCommunityMessage,
sureMessage,
} = require('./messages');
exports.Scenes = require('./scenes');
import * as actions from './actions';
import * as commands from './commands';
import { earningsMessage, updateCommunityMessage, sureMessage } from './messages';
import { CommunityContext } from './communityContext';
import * as Scenes from './scenes';

exports.configure = bot => {
export const configure = (bot: Telegraf<CommunityContext>) => {
bot.command('mycomm', userMiddleware, commands.communityAdmin);
bot.command('mycomms', userMiddleware, commands.myComms);
bot.command('community', userMiddleware, async ctx => {
Expand Down Expand Up @@ -89,3 +87,5 @@ exports.configure = bot => {
commands.changeVisibility
);
};

export { Scenes };
Loading

0 comments on commit 27d31b5

Please sign in to comment.