Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion bot/middleware/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ export const superAdminMiddleware = async (
ctx: CommunityContext,
next: () => void,
) => {
const admin = await validateSuperAdmin(ctx);
const tgId =
Comment thread
Luquitasjeffrey marked this conversation as resolved.
Outdated
'callback_query' in ctx.update
? ctx.update.callback_query.from.id.toString()
: undefined;
const admin = await validateSuperAdmin(ctx, tgId);
Comment thread
Matobi98 marked this conversation as resolved.
Outdated
if (!admin) return false;
ctx.i18n.locale(admin.lang);
ctx.admin = admin;
Expand Down
95 changes: 94 additions & 1 deletion bot/modules/community/commands.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable no-underscore-dangle */
import { logger } from '../../../logger';
import { showUserCommunitiesMessage } from './messages';
import { Community, Order } from '../../../models';
import { Community, Order, User } from '../../../models';
import { validateParams, validateObjectId } from '../../validations';
import { MainContext } from '../../start';
import { CommunityContext } from './communityContext';
Expand Down Expand Up @@ -241,6 +241,99 @@ export const deleteCommunity = async (ctx: CommunityContext) => {
}
};

export const closeCommunity = async (ctx: MainContext) => {
try {
const [input] = (await validateParams(
ctx,
2,
'\\<_community id \\| @groupUsername_\\>',
))!;
if (!input) return;

let community;
if (input[0] === '@') {
const regex = new RegExp(['^', input, '$'].join(''), 'i');
community = await Community.findOne({ group: regex });
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
} else {
if (!(await validateObjectId(ctx, input))) return;
community = await Community.findOne({ _id: input });
}

if (!community) {
return ctx.reply(ctx.i18n.t('community_not_found'));
}

const completedOrders = await Order.countDocuments({
community_id: community._id,
status: 'SUCCESS',
});

const creator = await User.findById(community.creator_id);
const creatorUsername = creator?.username || 'unknown';

const solversText =
community.solvers.length > 0
? community.solvers.map(s => `@${s.username}`).join(', ')
: '-';

const text = ctx.i18n.t('close_community_confirmation', {
communityName: community.name,
completedOrders,
creatorUsername,
solvers: solversText,
});

await ctx.reply(text, {
reply_markup: {
inline_keyboard: [
[
{
text: ctx.i18n.t('continue'),
callback_data: `closeCommunityConfirmBtn_${community._id}`,
},
{
text: ctx.i18n.t('cancel'),
callback_data: 'doNothingBtn',
},
],
],
},
});
} catch (error) {
logger.error(error);
}
};

export const closeCommunityConfirm = async (ctx: CommunityContext) => {
try {
ctx.deleteMessage();
const id = ctx.match?.[1];
if (!id) return;

if (!(await validateObjectId(ctx, id))) return;
const community = await Community.findById(id);
if (!community) {
return ctx.reply(ctx.i18n.t('community_not_found'));
}

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

await community.deleteOne();

if (creator) {
await ctx.telegram.sendMessage(
creator.tg_id,
ctx.i18n.t('community_closed_by_admin', { communityName }),
);
}

return ctx.reply(ctx.i18n.t('operation_successful'));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
} catch (error) {
logger.error(error);
}
};

export const changeVisibility = async (ctx: CommunityContext) => {
try {
ctx.deleteMessage();
Expand Down
9 changes: 8 additions & 1 deletion bot/modules/community/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Telegraf } from 'telegraf';
import { userMiddleware } from '../../middleware/user';
import { userMiddleware, superAdminMiddleware } from '../../middleware/user';
import * as actions from './actions';
import * as commands from './commands';
import {
Expand Down Expand Up @@ -65,6 +65,13 @@ export const configure = (bot: Telegraf<CommunityContext>) => {
},
);

bot.command('closecommunity', superAdminMiddleware, commands.closeCommunity);
bot.action(
/^closeCommunityConfirmBtn_([0-9a-f]{24})$/,
superAdminMiddleware,
commands.closeCommunityConfirm,
);

bot.command('findcomms', userMiddleware, commands.findCommunity);
bot.action(
/^communityInfo_([0-9a-f]{24})$/,
Expand Down
7 changes: 7 additions & 0 deletions locales/de.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -717,3 +717,10 @@ payment_methods_saved: "Zahlungsmethoden gespeichert ✅"
custom_payment_method: "✍️ Benutzerdefinierte Zahlungsmethode"
payment_methods_reset: "Zahlungsmethoden entfernt. Benutzer können jetzt beliebige Zahlungsmethoden frei eingeben."
payment_methods_wizard_commands: "/reset — alle Zahlungsmethoden entfernen und Standardverhalten wiederherstellen\n/exit — ohne Speichern beenden"
close_community_confirmation: |
Gemeinschaft ${communityName}
Abgeschlossene Bestellungen: ${completedOrders}
Ersteller: @${creatorUsername}
Löser: ${solvers}
Sind Sie sicher, dass Sie fortfahren möchten?
community_closed_by_admin: Ein Administrator hat Ihre Gemeinschaft @${communityName} geschlossen
7 changes: 7 additions & 0 deletions locales/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -722,3 +722,10 @@ payment_methods_saved: "Payment methods saved ✅"
custom_payment_method: "✍️ Custom payment method"
payment_methods_reset: "Payment methods removed. Users can now enter any payment method freely."
payment_methods_wizard_commands: "/reset — remove all payment methods and restore default behavior\n/exit — exit without saving"
close_community_confirmation: |
Community ${communityName}
Completed orders: ${completedOrders}
Creator: @${creatorUsername}
Solvers: ${solvers}
Are you sure you want to continue?
community_closed_by_admin: An administrator has closed your community @${communityName}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
7 changes: 7 additions & 0 deletions locales/es.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -719,3 +719,10 @@ payment_methods_saved: "Métodos de pago guardados ✅"
custom_payment_method: "✍️ Método de pago personalizado"
payment_methods_reset: "Métodos de pago eliminados. Los usuarios ahora pueden ingresar cualquier método de pago libremente."
payment_methods_wizard_commands: "/reset — eliminar todos los métodos de pago y restaurar el comportamiento predeterminado\n/exit — salir sin guardar"
close_community_confirmation: |
Comunidad ${communityName}
Ordenes completadas: ${completedOrders}
Creador: @${creatorUsername}
Solvers: ${solvers}
¿Está seguro que desea continuar?
community_closed_by_admin: Un administrador ha cerrado tu comunidad @${communityName}
7 changes: 7 additions & 0 deletions locales/fa.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -816,3 +816,10 @@ payment_methods_saved: "روش‌های پرداخت ذخیره شد ✅"
custom_payment_method: "✍️ روش پرداخت سفارشی"
payment_methods_reset: "روش‌های پرداخت حذف شدند. کاربران اکنون می‌توانند هر روش پرداختی را آزادانه وارد کنند."
payment_methods_wizard_commands: "/reset — حذف همه روش‌های پرداخت و بازگرداندن رفتار پیش‌فرض\n/exit — خروج بدون ذخیره"
close_community_confirmation: |
جامعه ${communityName}
سفارشات تکمیل‌شده: ${completedOrders}
سازنده: @${creatorUsername}
حل‌کنندگان: ${solvers}
آیا مطمئن هستید که می‌خواهید ادامه دهید؟
community_closed_by_admin: یک مدیر جامعه شما @${communityName} را بست
7 changes: 7 additions & 0 deletions locales/fr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -716,3 +716,10 @@ payment_methods_saved: "Méthodes de paiement enregistrées ✅"
custom_payment_method: "✍️ Méthode de paiement personnalisée"
payment_methods_reset: "Méthodes de paiement supprimées. Les utilisateurs peuvent désormais saisir n'importe quelle méthode de paiement librement."
payment_methods_wizard_commands: "/reset — supprimer toutes les méthodes de paiement et restaurer le comportement par défaut\n/exit — quitter sans enregistrer"
close_community_confirmation: |
Communauté ${communityName}
Commandes complétées: ${completedOrders}
Créateur: @${creatorUsername}
Solveurs: ${solvers}
Êtes-vous sûr de vouloir continuer?
community_closed_by_admin: Un administrateur a fermé votre communauté @${communityName}
7 changes: 7 additions & 0 deletions locales/it.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -714,3 +714,10 @@ payment_methods_saved: "Metodi di pagamento salvati ✅"
custom_payment_method: "✍️ Metodo di pagamento personalizzato"
payment_methods_reset: "Metodi di pagamento rimossi. Gli utenti possono ora inserire qualsiasi metodo di pagamento liberamente."
payment_methods_wizard_commands: "/reset — rimuovere tutti i metodi di pagamento e ripristinare il comportamento predefinito\n/exit — uscire senza salvare"
close_community_confirmation: |
Comunità ${communityName}
Ordini completati: ${completedOrders}
Creatore: @${creatorUsername}
Risolutori: ${solvers}
Sei sicuro di voler continuare?
community_closed_by_admin: Un amministratore ha chiuso la tua comunità @${communityName}
7 changes: 7 additions & 0 deletions locales/ko.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -714,3 +714,10 @@ payment_methods_saved: "결제 방법이 저장되었습니다 ✅"
custom_payment_method: "✍️ 사용자 지정 결제 방법"
payment_methods_reset: "결제 방법이 삭제되었습니다. 이제 사용자는 어떤 결제 방법이든 자유롭게 입력할 수 있습니다."
payment_methods_wizard_commands: "/reset — 모든 결제 방법을 삭제하고 기본 동작을 복원합니다\n/exit — 저장하지 않고 종료"
close_community_confirmation: |
커뮤니티 ${communityName}
완료된 주문: ${completedOrders}
생성자: @${creatorUsername}
해결사: ${solvers}
계속하시겠습니까?
community_closed_by_admin: 관리자가 귀하의 커뮤니티 @${communityName}을 폐쇄했습니다
7 changes: 7 additions & 0 deletions locales/pt.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -716,3 +716,10 @@ payment_methods_saved: "Métodos de pagamento salvos ✅"
custom_payment_method: "✍️ Método de pagamento personalizado"
payment_methods_reset: "Métodos de pagamento removidos. Os usuários agora podem inserir qualquer método de pagamento livremente."
payment_methods_wizard_commands: "/reset — remover todos os métodos de pagamento e restaurar o comportamento padrão\n/exit — sair sem salvar"
close_community_confirmation: |
Comunidade ${communityName}
Ordens concluídas: ${completedOrders}
Criador: @${creatorUsername}
Solvers: ${solvers}
Tem certeza que deseja continuar?
community_closed_by_admin: Um administrador fechou sua comunidade @${communityName}
7 changes: 7 additions & 0 deletions locales/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -717,3 +717,10 @@ payment_methods_saved: "Способы оплаты сохранены ✅"
custom_payment_method: "✍️ Пользовательский способ оплаты"
payment_methods_reset: "Способы оплаты удалены. Пользователи теперь могут свободно вводить любой способ оплаты."
payment_methods_wizard_commands: "/reset — удалить все способы оплаты и восстановить поведение по умолчанию\n/exit — выйти без сохранения"
close_community_confirmation: |
Сообщество ${communityName}
Выполненные заказы: ${completedOrders}
Создатель: @${creatorUsername}
Решатели: ${solvers}
Вы уверены, что хотите продолжить?
community_closed_by_admin: Администратор закрыл ваше сообщество @${communityName}
7 changes: 7 additions & 0 deletions locales/uk.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -713,3 +713,10 @@ payment_methods_saved: "Способи оплати збережено ✅"
custom_payment_method: "✍️ Власний спосіб оплати"
payment_methods_reset: "Способи оплати видалено. Користувачі тепер можуть вільно вводити будь-який спосіб оплати."
payment_methods_wizard_commands: "/reset — видалити всі способи оплати та відновити поведінку за замовчуванням\n/exit — вийти без збереження"
close_community_confirmation: |
Спільнота ${communityName}
Виконані замовлення: ${completedOrders}
Створив: @${creatorUsername}
Вирішувачі: ${solvers}
Ви впевнені, що хочете продовжити?
community_closed_by_admin: Адміністратор закрив вашу спільноту @${communityName}
Loading