POC dos Grupos de WhatsApp — Plano de implementação

TLDR: constrói o app groups (4 models, serviços, tasks, endpoints, admin), o EvolutionClient, os campos de WhatsApp no User e a Evolution no compose local (reaproveitando o Postgres e o Redis do Onion).

Spec: .project/docs/specs/20261118110412_whatsapp_groups_poc.md Branch: poc/WhatsappGroupFlow

Arquitetura: a regra de negócio vive em funções puras em apps/groups/services/, testadas sem I/O. As tasks Celery fazem a orquestração (cliente da Evolution + serviços). As views só validam a entrada e chamam os serviços. O webhook valida o token e enfileira process_evolution_event.

Stack: Django 5.2, DRF, Celery, requests (cliente HTTP, como o UnsplashClient), pytest-django com factories em função (tests/<app>/factories.py).

Restrições globais

  • Código em inglês; rótulos de admin e de choices em português.
  • Todos os models herdam BaseModel.
  • Testes atômicos, Triple-A com comentários # arrange / # act / # assert, cada branch com assert.
  • Cliente da Evolution sempre mockado nos testes (unittest.mock.patch).
  • Sem commit sem pedir ao usuário (memória do usuário). O plano lista os commits sugeridos.
  • Comando de teste local: make run.test path=tests/groups (ou uv run pytest tests/groups com DB_URL de um Postgres).

Task 1: Campos de WhatsApp no User

Files: - Modify: apps/accounts/models/user.py — whatsapp_phone, whatsapp_lid (CharField, único, null); limpar no delete() - Create: apps/accounts/migrations/00XX_user_whatsapp_phone_lid.py - Test: tests/accounts/test_user_whatsapp_fields.py

Interfaces: - Produces: User.whatsapp_phone: str | None, User.whatsapp_lid: str | None

  • [ ] Testes: delete() limpa os dois campos; whatsapp_phone duplicado gera IntegrityError.
  • [ ] Implementar, makemigrations accounts, rodar os testes.
  • [ ] Commit sugerido: feat: whatsapp phone and lid on user

Task 2: EvolutionClient

Files: - Create: apps/integrations/evolution.py - Modify: config/settings/base.py — EVOLUTION_API_URL, EVOLUTION_API_KEY, EVOLUTION_INSTANCE, EVOLUTION_BOT_PHONE, EVOLUTION_WEBHOOK_TOKEN - Test: tests/integrations/test_evolution_client.py

Interfaces: - Produces: - EvolutionClient(config: EvolutionConfig | None = None) - .create_group(subject: str, participants: list[str]) -> str (jid) - .update_participants(group_jid: str, action: str, participants: list[str]) -> dict - .invite_link(group_jid: str) -> str - .revoke_invite_link(group_jid: str) -> str (revoga e busca o link novo) - .participants(group_jid: str) -> list[dict] - .whatsapp_numbers(numbers: list[str]) -> list[dict] - EvolutionError(Exception)

  • [ ] Testes com requests mockado: URL, header apikey, corpo e parse de cada método; status HTTP de erro → EvolutionError.
  • [ ] Implementar e rodar.
  • [ ] Commit sugerido: feat: evolution api client

Task 3: App groups — models, migration, settings

Files: - Create: apps/groups/{__init__,apps}.py, apps/groups/models/{__init__,whatsapp_group,mentor_offer,group_membership,member_report}.py, apps/groups/migrations/0001_initial.py - Modify: config/settings/base.py — INSTALLED_APPS, WHATSAPP_GROUPS_* - Create: tests/groups/{__init__,factories}.py - Test: tests/groups/test_models.py

Interfaces: - Produces: - WhatsAppGroup (Gender, Region, StatusAdmin choices; save() deriva region de state; occupied_seats property; manager objects) - MentorOffer (Status: pending/accepted/declined/expired; is_expired property) - GroupMembership (Role: student/mentor/manager; LeftReason: left/removed_by_manager/removed_by_system/report; queryset .active()) - MemberReport (Status: pending/approved/declined; queryset .blocking(now)) - factories make_user, make_group, make_membership, make_offer, make_report

  • [ ] Testes: region derivada da UF; occupied_seats conta só alunos ativos; MentorOffer.is_expired; MemberReport.objects.blocking() inclui lifetime, inclui blocked_until futuro, exclui o passado, exclui pendente.
  • [ ] Commit sugerido: feat: whatsapp groups models

Task 4: Serviços puros — regiões, JIDs, status

Files: - Create: apps/groups/services/{__init__,regions,jids,status}.py - Test: tests/groups/test_regions.py, tests/groups/test_jids.py, tests/groups/test_status.py

Interfaces: - Produces: - regions.to_uf(value: str | None) -> str | None (sigla ou nome, sem acento/caixa) - regions.region_of(uf: str | None) -> str | None - jids.Participant(phone: str | None, lid: str | None); jids.parse_participant(raw: str | dict) -> Participant; jids.digits(jid) -> str - status.compute_status_admin(*, bot_present, mentor_present, manager_present) -> str; status.refresh_status_admin(group) -> str

  • [ ] Testes de cada branch (sigla, nome com acento, desconhecido, vazio; JID @s.whatsapp.net, @lid, dict com phoneNumber; as 5 saídas de status).
  • [ ] Commit sugerido: feat: groups region, jid and status helpers

Task 5: Elegibilidade e indicação

Files: - Create: apps/groups/services/{eligibility,recommendation}.py - Test: tests/groups/test_eligibility.py, tests/groups/test_recommendation.py

Interfaces: - Produces: - eligibility.age_on(birthdate, today) -> int - eligibility.is_blocked(user, now=None) -> bool - eligibility.ineligibility_reasons(user, now=None) -> list[str] (inactive, missing_birthdate, underage, no_active_subscription, onboarding_pending, missing_whatsapp_phone, too_recent, blocked) - recommendation.group_gender_for(user_gender) -> str - recommendation.recommend_group(user, now=None) -> WhatsAppGroup | None

  • [ ] Testes: um por motivo + elegível; indicação devolve o grupo atual; filtra gênero, idade, lotação, sem mentor, untracked_bot, inativo; cascata UF → região → país; desempate pelo mais cheio.
  • [ ] Commit sugerido: feat: group eligibility and recommendation

Task 6: Processamento do webhook

Files: - Create: apps/groups/services/events.py - Test: tests/groups/test_events.py

Interfaces: - Consumes: jids, status.refresh_status_admin, eligibility.is_blocked - Produces: events.handle_participants_update(payload: dict) -> list[Action], com Action(kind: "promote"|"remove", group_id: int, target: str), que as tasks executam

  • [ ] Testes: grupo desconhecido ignora; add cria membership de aluno, mentor (+ promote) e manager; grava o LID; sem conta / inativo / bloqueado → remove; idempotente; o bot é ignorado. remove: left, removed_by_manager com removed_by, removed_by_system, report; saída do mentor zera group.mentor; saída do bot → untracked_bot; status_admin recalculado.
  • [ ] Commit sugerido: feat: process evolution participant events

Task 7: Ofertas ao mentor e denúncias

Files: - Create: apps/groups/services/{mentor_offers,reports,phones}.py - Test: tests/groups/test_mentor_offers.py, tests/groups/test_reports.py, tests/groups/test_phones.py

Interfaces: - Produces: - mentor_offers.validate_new_offer(group, mentor, now=None) → ValidationError - mentor_offers.accept_offer(offer, now=None) -> WhatsAppGroup / decline_offer(offer, now=None); OfferConflict(Exception) com code - reports.create_report(*, reporter, membership, reason) -> MemberReport; ReportNotAllowed - reports.approve_report(report, reviewer, now=None), reports.decline_report(report, reviewer, now=None) - phones.register_whatsapp_phone(user, phone, client=None) -> str; PhoneNotOnWhatsApp, PhoneAlreadyInUse

  • [ ] Testes de cada validação e conflito; blocked_until com 14 dias e vazio em lifetime.
  • [ ] Commit sugerido: feat: mentor offers, reports and phone registration

Task 8: Tasks Celery e beat

Files: - Create: apps/groups/tasks.py - Modify: config/celery_defaults.py — reconcile-whatsapp-groups às 04:00 - Test: tests/groups/test_tasks.py

Interfaces: - Produces: create_whatsapp_group(group_id), process_evolution_event(payload), promote_participant(group_id, target), remove_participant(group_id, target), apply_member_report(report_id), reconcile_whatsapp_groups()

  • [ ] Testes com EvolutionClient mockado: criação grava jid/link e a membership do gestor; o evento dispara promote/remove; a denúncia remove e troca o link; a conferência marca untracked_bot; beat registrado.
  • [ ] Commit sugerido: feat: whatsapp groups celery tasks

Task 9: Endpoints e rotas

Files: - Create: apps/groups/{serializers,views,urls}.py - Modify: routes/api.py - Test: tests/groups/test_views.py

  • [ ] Testes por endpoint: auth obrigatória; whatsapp-phone 200/400/409; recommendation 200/403/404; ofertas list/accept/decline 200/404/409; mentor/members 200/403; reports 201/403; webhook 401 com token inválido, 202 enfileirando.
  • [ ] Commit sugerido: feat: whatsapp groups endpoints

Task 10: Admin

Files: - Create: apps/groups/admin.py - Test: tests/groups/test_admin.py

  • [ ] Testes: salvar um grupo novo enfileira create_whatsapp_group; o form recusa gestor sem whatsapp_phone; o form da oferta aplica validate_new_offer e preenche expires_at; as ações aprovar/recusar denúncia.
  • [ ] Commit sugerido: feat: whatsapp groups admin

Task 11: Compose, env, seed e docs

Files: - Modify: .project/docker/compose/services.yml, .env.example, apps/common/management/commands/seed.py - Create: .project/docs/rules/groups/whatsapp_groups.md - Modify: .project/docs/RULES.md, .project/docs/README.md

  • [ ] Seed idempotente (get_or_create): 1 gestor, 1 mentor, 2 grupos (com e sem mentor), 1 oferta pendente, memberships, 1 denúncia pendente.
  • [ ] docker compose config válido.
  • [ ] Commit sugerido: chore: evolution api on local compose e docs: whatsapp groups rules

Verificação final

  • make run.test (suíte inteira) e make run.lint sem regressões.
  • make run.seed duas vezes.