feat: add configurable user requirements for community creation#841
feat: add configurable user requirements for community creation#841Luquitasjeffrey wants to merge 6 commits into
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (12)
✅ Files skipped from review due to trivial changes (4)
🚧 Files skipped from review as they are similar to previous changes (6)
WalkthroughAdds optional minimum-threshold gating for community creation. Four new ChangesCommunity Creation Minimum Requirements Gating
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 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.
Code Review Summary
Verdict: Approve
Looks Good
- The previous fail-open config issue is fixed: invalid or negative threshold values are now rejected instead of silently disabling enforcement.
- The new eligibility gate is scoped to
/communityand the locale/config updates are complete for the touched surface.
grunch
left a comment
There was a problem hiding this comment.
Review estricto del PR. La funcionalidad es correcta y está bien estructurada (fail-closed en config inválida, i18n completo en los 10 idiomas, campos del modelo User verificados: trades_completed, volume_traded, total_rating —promedio 0–5— y created_at).
El único cambio recomendado antes de merge es el nivel de log (comentario 1). El resto son mejoras opcionales/no bloqueantes. Dejo sugerencias de código inline para que las apliques tú.
| (minReputation === null || user.total_rating >= minReputation); | ||
|
|
||
| if (!meetsRequirements) { | ||
| logger.error( |
There was a problem hiding this comment.
Nivel de log incorrecto (recomendado antes de merge). Que un usuario no cumpla los requisitos es comportamiento esperado enforced por los umbrales, no un error de sistema. Usar logger.error contamina los logs de error, distorsiona alertas/métricas y registra PII (tg_id, volume_traded) en cada intento fallido. Mejor logger.warn (o logger.info).
| logger.error( | |
| logger.warn( |
| const daysUsing = Math.floor( | ||
| (Date.now() - new Date(user.created_at).getTime()) / 86400000, | ||
| ); |
There was a problem hiding this comment.
Guard opcional para created_at (no bloqueante). Si created_at fuese inválido/ausente, getTime() devuelve NaN y daysUsing queda NaN; la comparación NaN >= minDays falla cerrado (correcto), pero el modo de fallo es implícito y difícil de depurar. En la práctica created_at tiene default: Date.now, así que el riesgo real es bajo. Si quieres hacerlo explícito:
| const daysUsing = Math.floor( | |
| (Date.now() - new Date(user.created_at).getTime()) / 86400000, | |
| ); | |
| const createdAtTime = new Date(user.created_at).getTime(); | |
| if (!Number.isFinite(createdAtTime)) { | |
| logger.error( | |
| `User ${user.tg_id} has invalid created_at timestamp: ${user.created_at}`, | |
| ); | |
| return ctx.reply(ctx.i18n.t('generic_error')); | |
| } | |
| const daysUsing = Math.floor( | |
| (Date.now() - createdAtTime) / 86400000, | |
| ); |
| return { value: null, isValid: false }; | ||
| }; | ||
|
|
||
| const thresholdResults = { |
There was a problem hiding this comment.
Validación en runtime + lógica inline (no bloqueante, decisión de diseño). Estos ~50 líneas se parsean y evalúan en cada invocación de /community, y una configuración inválida solo se detecta cuando un usuario ejecuta el comando (recibe generic_error). Dos mejoras a considerar:
- Parsear/validar los umbrales una vez al arranque (en
start.ts) para que un despliegue mal configurado falle al boot, no ante el usuario. - Extraer
parseOptionalNumbery la evaluación demeetsRequirementsa un helper enutil/para legibilidad y para poder testearlos de forma aislada.
There was a problem hiding this comment.
1 - Ahora se parsean unicamente al inicializar el modulo que declara el comando /community
2 - Debido a que meetsRequirements y parseOptionalNumber solo son usados dentro de community/index.ts me pareció mas propicio dejarlas en el archivo community/index.ts ya que son funciones helper solo usadas internamente en ese modulo
| # COMMUNITY_CREATION_MIN_ORDERS=100 | ||
| # COMMUNITY_CREATION_MIN_VOLUME=10000000 | ||
| # COMMUNITY_CREATION_MIN_DAYS_USING_BOT=365 | ||
| # COMMUNITY_CREATION_MIN_REPUTATION=4.8 |
There was a problem hiding this comment.
Nota sobre MIN_REPUTATION. total_rating es un promedio que parte de 0 y puede inflarse con una sola reseña de 5★ (1 review = 5.0), por lo que por sí solo es gameable. Queda mitigado al combinarlo con MIN_ORDERS. Quizá valga la pena un comentario aquí recomendando usar reputación junto a un mínimo de órdenes.
…osed configuration checks, improved error logging levels, added explicit user date validation, and updated all locales to provide detailed feedback to the user on unmet requirements.
Closes #838
Continues #840
Add environment-based minimum requirements to the /community command so only users who meet configurable thresholds can create a community
If any requirement is not met, the bot replies with a short error message and exits — no scene is entered
If an env var is not set, that restriction is simply not applied
Summary by CodeRabbit
New Features
Documentation
.env-sample) with documented, optional community-creation minimum requirement settings.Localization