Allow community admins to configure payment methods for order wizard - Issue292#786
Allow community admins to configure payment methods for order wizard - Issue292#786Matobi98 wants to merge 5 commits intolnp2pBot:mainfrom
Conversation
|
Warning Rate limit exceeded
To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (18)
WalkthroughThis PR introduces community payment methods management to the bot, enabling communities to configure accepted payment methods via a new wizard scene. It integrates payment method selection into the orders flow with interactive toggle buttons, updates pending payment failure messaging, and adds localization strings across 10 languages. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 11
🧹 Nitpick comments (2)
models/community.ts (1)
87-90: Consider a schema-level cap onpayment_methods.The sibling
currenciesfield enforcescurrencyLimits, butpayment_methodshas no schema validator. The wizard reportedly enforces a max of 20, yet any other write path (admin scripts, future callers, direct DB ops) could insert unbounded arrays and inflate every order’s inline keyboard. A lightweightvalidatemirroringcurrencyLimitskeeps the schema self-defending.Proposed change
+const paymentMethodsLimits = (val: string[]): boolean => val.length <= 20; + // ... payment_methods: { type: [String], default: [], + validate: [paymentMethodsLimits, '{PATH} exceeds the allowed limit'], },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@models/community.ts` around lines 87 - 90, The payment_methods array in the Community schema has no schema-level limit, so add a validator like the existing currencyLimits used by currencies: update the payment_methods field definition (payment_methods) to include a validate or maxlength rule that enforces the same cap (e.g., 20 items) and an error message; implement the check as a synchronous validator function (or equivalent mongoose array limit option) so any writes (admin scripts, direct DB edits, etc.) are rejected at the schema layer rather than relying solely on the wizard.bot/modules/community/scenes.ts (1)
937-963: Consider rejecting empty payment-method input instead of silently saving[].If the admin sends whitespace/commas only (or an empty message),
methodsbecomes[]and the wizard silently overwritescommunity.payment_methodswith an empty array and repliespayment_methods_saved. This is misleading UX — the admin thinks they saved methods but effectively cleared them, and the orders flow will then fall back to free-text input.Since a similar validation pattern exists at
bot/modules/orders/scenes.tslines 207–210 (no_payment_method_selected), consider mirroring it here. If clearing is intentional, it could be a separate explicit action (e.g.,/clear) for discoverability.♻️ Suggested adjustment
const text = ctx.message.text.trim(); const methods = text .split(',') .map(m => m.trim()) .filter(m => m.length > 0); + if (methods.length === 0) { + return await ctx.reply(ctx.i18n.t('no_payment_method_selected')); + } + const max = 20; if (methods.length > max) { return await ctx.reply(ctx.i18n.t('max_allowed', { max })); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@bot/modules/community/scenes.ts` around lines 937 - 963, The handler that parses and saves payment methods currently allows an empty methods array and overwrites community.payment_methods with []; update the validation in the async scene callback so that if methods.length === 0 you do NOT assign or save to community.payment_methods, instead reply with the existing i18n key used elsewhere (e.g., 'no_payment_method_selected') and return without saving; keep the max-length check (max = 20) and the rest of the happy-path unchanged, and consider adding a separate explicit command (like '/clear') to intentionally clear community.payment_methods if clearing is desired.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@bot/modules/orders/scenes.ts`:
- Around line 201-244: The handler assigned to ctx.wizard.state
(ctx.wizard.state.handler) should guard the call to
ctx.telegram.editMessageReplyMarkup with a try/catch to swallow transient
Telegram errors (e.g., "message is not modified") so the wizard step does not
bubble the exception and prematurely exit the scene; wrap the
editMessageReplyMarkup(...) call (the one using prompt.chat.id,
prompt.message_id and buildKeyboard(selected).reply_markup) in a try/catch and
log/debug the error but continue flow, and also change the parseInt call that
builds methodIdx (currently parseInt(data.slice('pm_toggle_'.length))) to
parseInt(..., 10) to provide an explicit radix as required by ESLint.
In `@locales/de.yaml`:
- Around line 711-717: Replace the English placeholder values for the keys
community_payment_methods, enter_community_payment_methods,
current_payment_methods, select_payment_methods, confirm_payment_methods,
no_payment_method_selected, and payment_methods_saved in de.yaml with proper
German translations (e.g., "Zahlungsmethoden", "Gib die in deiner Community
akzeptierten Zahlungsmethoden ein, getrennt durch Kommas (z. B.:
Banküberweisung, Bargeld, PayPal)", "Aktuelle Zahlungsmethoden: ${methods}",
"Wähle eine oder mehrere Zahlungsmethoden:", "✅ Bestätigen", "Bitte wähle
mindestens eine Zahlungsmethode aus", "Zahlungsmethoden gespeichert ✅"); then
scan the other non-English locale files for the same keys and replace any
remaining English placeholders with appropriate translations for those
languages.
In `@locales/es.yaml`:
- Around line 713-719: The listed UI strings in locales/es.yaml are still in
English; update the values for keys community_payment_methods,
enter_community_payment_methods, current_payment_methods,
select_payment_methods, confirm_payment_methods, no_payment_method_selected, and
payment_methods_saved with Spanish translations (e.g., "Métodos de pago",
"Introduzca los métodos de pago aceptados en su comunidad, separados por comas
(p. ej.: Transferencia bancaria, Efectivo, PayPal)", "Métodos de pago actuales:
${methods}", "Seleccione uno o más métodos de pago:", "✅ Confirmar", "Por favor
seleccione al menos un método de pago", "Métodos de pago guardados ✅") so the
community admin/order UI shows consistent Spanish text.
In `@locales/fa.yaml`:
- Around line 810-816: The Persian locale file contains new payment-method keys
with English strings; update locales/fa.yaml by providing proper Persian
translations for the keys community_payment_methods,
enter_community_payment_methods, current_payment_methods,
select_payment_methods, confirm_payment_methods, no_payment_method_selected, and
payment_methods_saved so Persian users see localized UI text (or if intended,
add a comment and document fallback behavior); locate these keys in the file and
replace the English values with verified Persian translations for each key.
In `@locales/fr.yaml`:
- Around line 710-716: The French locale file contains new payment-method keys
still in English; update the values for community_payment_methods,
enter_community_payment_methods, current_payment_methods,
select_payment_methods, confirm_payment_methods, no_payment_method_selected, and
payment_methods_saved with proper French translations so the community
admin/order UI displays consistent French text (replace the English strings with
their French equivalents while keeping the key names unchanged).
In `@locales/it.yaml`:
- Around line 708-714: The listed localization keys (community_payment_methods,
enter_community_payment_methods, current_payment_methods,
select_payment_methods, confirm_payment_methods, no_payment_method_selected,
payment_methods_saved) are still in English; update their values with proper
Italian translations so the community admin and order flows display consistent
Italian text (replace each English string with the corresponding Italian phrase
for the label, placeholder/instruction, current methods text including the
${methods} interpolation, selection prompt, confirm button, validation message,
and saved confirmation). Ensure you keep the ${methods} interpolation intact and
preserve punctuation/emojis like "✅" where present.
In `@locales/ko.yaml`:
- Around line 708-714: Replace the English UI strings for the payment-method
keys with Korean translations: update community_payment_methods to "결제 수단",
enter_community_payment_methods to "쉼표로 구분하여 커뮤니티에서 허용하는 결제 수단을 입력하세요(예: 계좌이체,
현금, PayPal)", current_payment_methods to "현재 결제 수단: ${methods}",
select_payment_methods to "하나 이상의 결제 수단을 선택하세요:", confirm_payment_methods to "✅
확인", no_payment_method_selected to "최소 하나의 결제 수단을 선택하세요", and
payment_methods_saved to "결제 수단이 저장되었습니다 ✅".
In `@locales/pt.yaml`:
- Around line 710-716: Replace the English payment-method UI strings in pt.yaml
with Portuguese translations for the keys community_payment_methods,
enter_community_payment_methods, current_payment_methods,
select_payment_methods, confirm_payment_methods, no_payment_method_selected, and
payment_methods_saved; e.g., use "Métodos de pagamento", "Insira os métodos de
pagamento aceitos na sua comunidade, separados por vírgula (ex.: Transferência
bancária, Dinheiro, PayPal)", "Métodos de pagamento atuais: ${methods}",
"Selecione um ou mais métodos de pagamento:", "✅ Confirmar", "Por favor
selecione pelo menos um método de pagamento" and "Métodos de pagamento salvos ✅"
(or equivalent natural Portuguese) so the UI is fully localized.
In `@locales/ru.yaml`:
- Around line 711-717: The listed UI keys (community_payment_methods,
enter_community_payment_methods, current_payment_methods,
select_payment_methods, confirm_payment_methods, no_payment_method_selected,
payment_methods_saved) are still in English; update their values in ru.yaml to
Russian translations so the community admin/order flows aren't
mixed-language—replace each English string with an appropriate Russian
equivalent (e.g., "Способы оплаты", "Введите способы оплаты, принятые в
сообществе, через запятую (например: Банковский перевод, Наличные, PayPal)",
"Текущие способы оплаты: ${methods}", "Выберите один или несколько способов
оплаты:", "✅ Подтвердить", "Пожалуйста, выберите хотя бы один способ оплаты",
"Способы оплаты сохранены ✅").
In `@locales/uk.yaml`:
- Around line 707-713: Translate the new payment-method UI keys in uk.yaml from
English to Ukrainian: replace the values for community_payment_methods,
enter_community_payment_methods, current_payment_methods,
select_payment_methods, confirm_payment_methods, no_payment_method_selected, and
payment_methods_saved with accurate Ukrainian strings so the community
admin/order flows are fully localized (ensure placeholders like ${methods}
remain unchanged and the confirm checkmark stays appropriate).
In `@package.json`:
- Line 68: Update tests to use the new server.config.apiURL property instead of
the removed server.ApiURL; locate the test referencing server.ApiURL (e.g., the
variable named server in tests that calls ApiURL) and change that access to
server.config.apiURL, and adjust any mocks/initializations that set ApiURL so
they set config.apiURL instead (ensure the object named server has a config
object with an apiURL field).
---
Nitpick comments:
In `@bot/modules/community/scenes.ts`:
- Around line 937-963: The handler that parses and saves payment methods
currently allows an empty methods array and overwrites community.payment_methods
with []; update the validation in the async scene callback so that if
methods.length === 0 you do NOT assign or save to community.payment_methods,
instead reply with the existing i18n key used elsewhere (e.g.,
'no_payment_method_selected') and return without saving; keep the max-length
check (max = 20) and the rest of the happy-path unchanged, and consider adding a
separate explicit command (like '/clear') to intentionally clear
community.payment_methods if clearing is desired.
In `@models/community.ts`:
- Around line 87-90: The payment_methods array in the Community schema has no
schema-level limit, so add a validator like the existing currencyLimits used by
currencies: update the payment_methods field definition (payment_methods) to
include a validate or maxlength rule that enforces the same cap (e.g., 20 items)
and an error message; implement the check as a synchronous validator function
(or equivalent mongoose array limit option) so any writes (admin scripts, direct
DB edits, etc.) are rejected at the schema layer rather than relying solely on
the wizard.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 5d0c7034-f7d8-49a1-b3c5-c43c424dfc02
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (20)
bot/middleware/stage.tsbot/modules/community/commands.tsbot/modules/community/communityContext.tsbot/modules/community/index.tsbot/modules/community/messages.tsbot/modules/community/scenes.tsbot/modules/orders/scenes.tsjobs/pending_payments.tslocales/de.yamllocales/en.yamllocales/es.yamllocales/fa.yamllocales/fr.yamllocales/it.yamllocales/ko.yamllocales/pt.yamllocales/ru.yamllocales/uk.yamlmodels/community.tspackage.json
Summary
payment_methodsfield (array of strings) to theCommunitymodel, analogous tocommunity.currenciesUPDATE_PAYMENT_METHODS_COMMUNITY_WIZARD_SCENE_ID) accessible from the community admin panel/buyor/sell) in a community that has payment methods configured, the order wizard replaces the free-text payment method input with an inline keyboard allowing selection of one or more methods; thefinal value is stored as a comma-joined string
Test plan
/setcommand run/buy— verify the payment method step shows buttons instead of free-text input,/buywithout a default community (or with a community that has no payment methods) — verify the free-text input still works as beforeSummary by CodeRabbit