diff --git a/docs/arquitetura/PHPeste_Arquitetura.pdf b/docs/arquitetura/PHPeste_Arquitetura.pdf index 5da77ca..887444e 100644 Binary files a/docs/arquitetura/PHPeste_Arquitetura.pdf and b/docs/arquitetura/PHPeste_Arquitetura.pdf differ diff --git a/docs/arquitetura/README.md b/docs/arquitetura/README.md index 345d637..56a0c48 100644 --- a/docs/arquitetura/README.md +++ b/docs/arquitetura/README.md @@ -25,7 +25,7 @@ | 19 | Telas: organização (patrocinadores, fornecedores, finanças, tarefas, comunicação; cresce a cada tela do Marco 2) | | 20 | Onde estamos e o que falta | -Retrato de 26/11/2026, com a A23 (modelos de e-mail). +Retrato de 26/11/2026, com a P04 (checkout: escolha de ingressos e dados). ## Como atualizar diff --git a/docs/arquitetura/fonte/arquitetura.html b/docs/arquitetura/fonte/arquitetura.html index f80a84b..f8d3c2f 100644 --- a/docs/arquitetura/fonte/arquitetura.html +++ b/docs/arquitetura/fonte/arquitetura.html @@ -108,7 +108,7 @@

Conteúdo

chamada ou dependência assíncrono (evento, fila, webhook) - +
@@ -215,7 +215,7 @@

Visão geral do sistema

  • Painel e site são projetos separados (decisão: front-admin SPA, front-public SSR). O token é Bearer do Sanctum nos dois (ADR 0005).
  • Fila e agendador rodam a mesma imagem do backend (horizon e scheduler no infra/docker-compose.yml).
-
PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 2
+
PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 2
@@ -290,7 +290,7 @@

Tenancy: comunidade, edição e o que é global

community_id
  • Por que não um banco por comunidade: a mesma pessoa palestra no PHPeste de um ano e compra ingresso no outro, e o perfil dela é um só.
  • Dado de edição que vai para a próxima ("criar edição a partir da anterior") é copiado por um EditionCloner de cada módulo, nunca dado de pessoa.
-
PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 3
+
PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 3
@@ -358,7 +358,7 @@

Como uma requisição encontra a edição

O site chama /public/resolve com o host da requisição, recebe edition_id e o domínio principal e redireciona se for preciso (ADR 0008). O host é normalizado (minúsculas, sem porta, IDN em punycode) e nunca é usado para montar URL sem passar pela tabela edition_domains. -
PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 4
+
PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 4
@@ -424,7 +424,7 @@

Ciclo de vida da edição

palestrantes, patrocínio, fornecedores), pendências com caminho e filtro (propostas sem revisor, divergência na conciliação, entregas e despesas vencidas) e marcos. O Community filtra cada pendência pela permissão de quem vê: o voluntário não vê pendência de finanças. -
PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 5
+
PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 5
@@ -523,7 +523,7 @@

Os 15 módulos do backend

casca -
PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 6
+
PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 6
@@ -590,7 +590,7 @@

Como os módulos conversam

EditionMailer::send(...): todo e-mail, com o tema; ::preview mostra sem enviar
  • Ponto de extensão é registrado com $app->tag([...], Contrato::TAG): o Community não conhece os módulos, só a tag. Módulo novo aparece na Visão geral e na clonagem sem mexer no Community. O mesmo vale para TaskLinkProvider (Tasks): Suppliers e Sponsors registram o que uma tarefa pode apontar, e o Program vai registrar a sessão.
-
PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 7
+
PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 7
@@ -692,7 +692,7 @@

Banco de dados por domínio

cache · cache_locks sessions
  • Dinheiro sempre em centavos (inteiro). Dado sensível cifrado no banco: CPF de quem compra, credenciais do gateway, acessibilidade, corpo de webhook, linhas de importação. APP_PREVIOUS_KEYS + comandos *:reencrypt-* para trocar a chave.
  • Estoque e cupom nunca são lidos e depois gravados: UPDATE … WHERE allocated + q <= quantity. Testes com 12 processos simultâneos provam que não vende além do lote.
-
PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 8
+
PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 8
@@ -713,7 +713,7 @@

Como funciona

  • Palestrante e participante não têm papel: entram pelas rotas de edição publicada.
  • -
    PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 9
    +
    PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 9
    @@ -732,9 +732,9 @@

    Ingresso: da compra ao QR

    Fila e rotinas -Escolhe ingressos -tipo, lote, cupom, -participantes +/ingressos +lote, cupom na hora, +quem vai e perguntas PlaceOrder reserva estoque e cupom @@ -786,8 +786,8 @@

    Ingresso: da compra ao QR

    Rotinas que fecham as pontas ticketing:expire-orders (1/min) devolve estoque de reserva vencida · ticketing:rotate-batches abre o próximo lote payments:retry-webhooks (1, 5, 15, 60 min) · ticketing:reconcile (diário) grava divergência com o gateway -
    • Reembolso: PaymentLedger::refund reserva o valor antes de chamar o gateway (dois reembolsos ao mesmo tempo nunca passam do pago). Pedido importado de outra plataforma entra pago, sem cobrança, e não passa por reembolso nem conciliação. Pagamento recebido fora do gateway é marcado à mão pela organização (MarkOrderPaid), com justificativa na auditoria, emissão dos ingressos e cancelamento da cobrança aberta.
    -
    PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 10
    +
    • No site, /ingressos confere o cupom na hora e valida os dados de cada participante antes de reservar; a mesma tentativa repete a mesma Idempotency-Key. A reserva aparece em /checkout/pedido/{id} com contagem regressiva (o token do pedido fica só no navegador de quem comprou); ao expirar, volta para a escolha com a mensagem e a escolha anterior.
    • Reembolso: PaymentLedger::refund reserva o valor antes de chamar o gateway (dois reembolsos ao mesmo tempo nunca passam do pago). Pedido importado de outra plataforma entra pago, sem cobrança, e não passa por reembolso nem conciliação. Pagamento recebido fora do gateway é marcado à mão pela organização (MarkOrderPaid), com justificativa na auditoria, emissão dos ingressos e cancelamento da cobrança aberta.
    +
    PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 10
    @@ -863,7 +863,7 @@

    CFP: da proposta à grade

    Configurar CFP (A10) · Avaliar propostas com teclado (A11) · Palestrantes: lista, cobertura e detalhe (A12) · no site público: formulário de proposta e área do palestrante com entrar pelo GitHub (P03, P11). -
    PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 11
    +
    PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 11
    @@ -916,7 +916,7 @@

    Dinheiro: patrocínio, fornecedores e finanças

    ADR 0009: a plataforma não recebe nem repassa dinheiro Cada edição cadastra a conta do próprio gateway; a API valida as chaves e um webhook assinado antes de abrir vendas. Credenciais cifradas; a API só mostra os 4 últimos caracteres. -
    PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 12
    +
    PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 12
    @@ -946,7 +946,7 @@

    Auditoria

  • Segredo removido, dado pessoal mascarado; o model recusa update e delete.
  • -
    PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 13
    +
    PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 13
    @@ -956,7 +956,7 @@

    Segurança

    TemaComo está
    AutenticaçãoSanctum Bearer, um token por dispositivo com expiração (SANCTUM_EXPIRATION_MINUTES); revogar é imediato. Senha mínima de 10 e checagem de vazamento.
    IsolamentoEscopo global por edição; outra comunidade recebe 404; arch test impede módulo de depender de App\ e controller de usar $request->all().
    Rate limitLimiters nomeados: login, password-reset, checkout, webhooks, configuráveis por .env.
    Headers e CORSCSP, HSTS, nosniff, Referrer-Policy, Permissions-Policy. CORS por ambiente e, em /public/*, só a origem do site próprio da edição.
    Dados sensíveisCifrados no banco (CPF, credenciais, acessibilidade, webhooks). Logs JSON com password, token, secret e cartão redigidos automaticamente.
    ArquivosDisco privado; download só por URL assinada que expira (10 min), sempre como anexo, com nosniff e CSP sandbox. SVG sanitizado.
    PagamentoSem dado de cartão na API; webhook com assinatura do driver e reconsulta ao gateway; idempotência no banco (unique(edition_id, idempotency_key)).
    SegredosADR 0006: nada de segredo no repositório; APP_PREVIOUS_KEYS para trocar a chave sem perder o que já foi cifrado.
    LGPDEncarregado e política por edição, anonimização após o evento (B43 em aberto). Decisão em aberto: comunidade controladora, PHPeste operador.
    -
    PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 14
    +
    PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 14
    @@ -1031,7 +1031,7 @@

    Desenvolvimento, CI e deploy

    Em aberto para o evento teste de carga, backups, runbook do dia do evento (B45) · dados de demonstração e documentação publicada (B46) -
    PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 15
    +
    PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 15
    @@ -1044,7 +1044,7 @@

    Telas: o design do painel

    Tokens do tema Sertão
    Design: tokens do tema Sertão
    -
    PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 16
    +
    PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 16
    @@ -1058,7 +1058,7 @@

    Telas: o painel em uso

    Login
    Entrar com e-mail e senha ou GitHub
    -
    PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 17
    +
    PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 17
    @@ -1068,7 +1068,7 @@

    Telas: vendas

    Ingressos: tipos e lotes com o preço, o que a edição recebe depois da taxa do gateway, vendidos e situação. Cupons e regras da venda nas outras abas.
    Pedidos: números da edição no topo (pagos, aguardando, reembolsos, taxa do gateway), busca e filtro por situação, e o detalhe com itens, pagamento, reembolsos e histórico (auditoria). Reembolso com aviso de taxa e confirmação explícita; marcar como pago exige justificativa.
    Pagamentos (só a organização): gateway da comunidade com chave mascarada, etapas para abrir vendas e Testar conexão, prévia do recebedor no checkout, métodos aceitos, webhook com o último evento e os últimos eventos do gateway com reprocessar.
    Participantes (só a organização): uma linha por ingresso com crachá, acessibilidade (só a organização vê) e camiseta, filtros de dados faltando e transferidos, edição registrada na auditoria, cobrança de dados com prévia do e-mail e CSV dos crachás.
    -
    PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 18
    +
    PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 18
    @@ -1078,7 +1078,7 @@

    Telas: organização

    Patrocinadores (só a organização): meta, fechado, pago e em negociação, funil com o último contato de cada empresa, mover que desfaz se a API recusa e pede confirmação de cota sem vaga, e as cotas. O detalhe tem acordo, pagamentos, entregas, histórico e anexos por URL assinada.
    Fornecedores (só a organização): orçado e contratado da lista filtrada, que batem com o total no pé da tabela, filtros, contato restrito e trazer de outra edição da comunidade. O detalhe tem orçamentos, contratar e recusar, anexos e histórico.
    Finanças (organização e financeiro): receita, despesas pagas, saldo e previsão, orçamento por categoria com barra e texto equivalente, receita por origem e por conta com as taxas do gateway, despesas com comprovante por URL assinada e exportação em planilha.
    Tarefas (toda a equipe vê; o responsável move a própria): colunas com contagem, filtros, atrasada em destaque e mover com o mouse ou Alt + setas, anunciado e desfeito se a API recusa.
    Comunicação (só a organização): modelos de e-mail com gatilho e último envio, variável desconhecida bloqueia salvar, prévia gerada pelo backend com o tema e os dados de exemplo, teste para si mesmo e restaurar o padrão.
    -
    PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 19
    +
    PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 19
    @@ -1086,8 +1086,8 @@

    Telas: organização

    Onde estamos e o que falta

    Os milestones do GitHub e o board PHPeste Platform são a fonte da verdade do andamento; esta página é o retrato no dia da geração.

    -
    MarcoSituaçãoO que tem
    Marco 0 · FundaçãoConcluídoesqueleto Laravel 13, módulos, Docker, convenções de API, segurança base, painel e componentes
    Marco 1 · Núcleo e CFPBackend concluídoIdentity, Community, Branding, Notifications, CFP inteiro, Audit; telas A05–A12, A24, A25; site P01, P03
    Marco 2 · IngressosBackend concluído, telas em andamentobackend: ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas, webhooks do Resend; telas prontas: A14 (ingressos), A15 (pedidos e reembolso), A16 (pagamentos e gateway), A17 (participantes), A19 (patrocinadores), A20 (fornecedores), A21 (finanças), A22 (tarefas), A23 (modelos de e-mail); faltam A18 e P04–P06
    Marco 3 · Evento prontoA fazergrade e programação (B35–B37), check-in com modo offline (B38–B39), push (B40), API pública e checkout embutível (B41), site da edição (P02, P07–P09)
    Marco 4 · OperaçãoA fazerengajamento (B42), LGPD (B43), relatórios (B44), carga, backups e runbook (B45), dados de demonstração (B46), acessibilidade e e2e (A26, A27)
    +
    MarcoSituaçãoO que tem
    Marco 0 · FundaçãoConcluídoesqueleto Laravel 13, módulos, Docker, convenções de API, segurança base, painel e componentes
    Marco 1 · Núcleo e CFPBackend concluídoIdentity, Community, Branding, Notifications, CFP inteiro, Audit; telas A05–A12, A24, A25; site P01, P03
    Marco 2 · IngressosBackend concluído, telas em andamentobackend: ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas, webhooks do Resend; telas prontas: A14 (ingressos), A15 (pedidos e reembolso), A16 (pagamentos e gateway), A17 (participantes), A19 (patrocinadores), A20 (fornecedores), A21 (finanças), A22 (tarefas), A23 (modelos de e-mail); no site, P04 (escolha de ingressos e dados); faltam A18, P05 e P06
    Marco 3 · Evento prontoA fazergrade e programação (B35–B37), check-in com modo offline (B38–B39), push (B40), API pública e checkout embutível (B41), site da edição (P02, P07–P09)
    Marco 4 · OperaçãoA fazerengajamento (B42), LGPD (B43), relatórios (B44), carga, backups e runbook (B45), dados de demonstração (B46), acessibilidade e e2e (A26, A27)
    -
    PHPeste Platform · Arquitetura26/11/2026 · A23 (modelos de e-mail) · página 20
    +
    PHPeste Platform · Arquitetura26/11/2026 · P04 (checkout: escolha e dados) · página 20
    diff --git a/docs/arquitetura/fonte/gerar.py b/docs/arquitetura/fonte/gerar.py index f4603f5..48a33b8 100644 --- a/docs/arquitetura/fonte/gerar.py +++ b/docs/arquitetura/fonte/gerar.py @@ -13,7 +13,7 @@ from pathlib import Path OUT = Path(__file__).with_name("arquitetura.html") -RETRATO = "26/11/2026 · A23 (modelos de e-mail)" +RETRATO = "26/11/2026 · P04 (checkout: escolha e dados)" # ---------------------------------------------------------------- estilo --- # Cores do tema Sertão (front-admin) para o que é da plataforma, e neutras @@ -402,7 +402,7 @@ def legend(): b.append(f'') b.append(t(20, y + 16, label, size=10.5, weight=700, color=K[kind][1])) flow = [ - (0, 30, "Escolhe ingressos", ["tipo, lote, cupom,", "participantes"]), + (0, 30, "/ingressos", ["lote, cupom na hora,", "quem vai e perguntas"]), (1, 180, "PlaceOrder", ["reserva estoque e cupom", "numa transação", "Idempotency-Key"]), (0, 330, "Pix ou cartão", ["sem dado de cartão", "na nossa API"]), (2, 330, "ChargeService", ["cobrança na conta da", "edição · trava clique duplo"]), @@ -428,7 +428,8 @@ def legend(): pages.append(page(10, "Fluxo", "Ingresso: da compra ao QR", "O pedido nasce reservando estoque; o pagamento só confirma quando a API consulta o gateway. Evento falso, repetido ou fora de ordem não muda pedido.", svg("\n".join(b), h=540), - ["Reembolso: PaymentLedger::refund reserva o valor antes de chamar o gateway (dois reembolsos ao mesmo tempo nunca passam do pago). Pedido importado de outra plataforma entra pago, sem cobrança, e não passa por reembolso nem conciliação. Pagamento recebido fora do gateway é marcado à mão pela organização (MarkOrderPaid), com justificativa na auditoria, emissão dos ingressos e cancelamento da cobrança aberta."])) + ["No site, /ingressos confere o cupom na hora e valida os dados de cada participante antes de reservar; a mesma tentativa repete a mesma Idempotency-Key. A reserva aparece em /checkout/pedido/{id} com contagem regressiva (o token do pedido fica só no navegador de quem comprou); ao expirar, volta para a escolha com a mensagem e a escolha anterior.", + "Reembolso: PaymentLedger::refund reserva o valor antes de chamar o gateway (dois reembolsos ao mesmo tempo nunca passam do pago). Pedido importado de outra plataforma entra pago, sem cobrança, e não passa por reembolso nem conciliação. Pagamento recebido fora do gateway é marcado à mão pela organização (MarkOrderPaid), com justificativa na auditoria, emissão dos ingressos e cancelamento da cobrança aberta."])) # ================================================== 11 CFP b = [] @@ -585,7 +586,7 @@ def legend(): status = [ ("Marco 0 · Fundação", "Concluído", "esqueleto Laravel 13, módulos, Docker, convenções de API, segurança base, painel e componentes"), ("Marco 1 · Núcleo e CFP", "Backend concluído", "Identity, Community, Branding, Notifications, CFP inteiro, Audit; telas A05–A12, A24, A25; site P01, P03"), - ("Marco 2 · Ingressos", "Backend concluído, telas em andamento", "backend: ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas, webhooks do Resend; telas prontas: A14 (ingressos), A15 (pedidos e reembolso), A16 (pagamentos e gateway), A17 (participantes), A19 (patrocinadores), A20 (fornecedores), A21 (finanças), A22 (tarefas), A23 (modelos de e-mail); faltam A18 e P04–P06"), + ("Marco 2 · Ingressos", "Backend concluído, telas em andamento", "backend: ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas, webhooks do Resend; telas prontas: A14 (ingressos), A15 (pedidos e reembolso), A16 (pagamentos e gateway), A17 (participantes), A19 (patrocinadores), A20 (fornecedores), A21 (finanças), A22 (tarefas), A23 (modelos de e-mail); no site, P04 (escolha de ingressos e dados); faltam A18, P05 e P06"), ("Marco 3 · Evento pronto", "A fazer", "grade e programação (B35–B37), check-in com modo offline (B38–B39), push (B40), API pública e checkout embutível (B41), site da edição (P02, P07–P09)"), ("Marco 4 · Operação", "A fazer", "engajamento (B42), LGPD (B43), relatórios (B44), carga, backups e runbook (B45), dados de demonstração (B46), acessibilidade e e2e (A26, A27)"), ] diff --git a/front-public/CLAUDE.md b/front-public/CLAUDE.md index f51875a..dc76e7e 100644 --- a/front-public/CLAUDE.md +++ b/front-public/CLAUDE.md @@ -25,6 +25,13 @@ HTML nunca fica em cache (o mesmo caminho serve edições diferentes por host). | `/palestrante/propostas` | Propostas da pessoa na edição, com status, decisão e confirmação | | `/palestrante/propostas/{id}` | Detalhe (link dos e-mails de aprovação, lembrete e convite): confirmar ou recusar a participação, editar ou retirar enquanto o CFP está aberto | +## Checkout (`app/modules/checkout/`) + +| Página | O quê | +| --- | --- | +| `/ingressos` | Passo 1: tipos com preço, lote, quanto resta e próximo lote; quantidade entre o mínimo e o máximo do tipo; cupom conferido na hora (`POST /public/editions/{id}/coupons/check`) e de novo quando a quantidade muda; resumo com subtotal, desconto e taxa "calculada ao reservar" nos tipos com `pass_fee_to_buyer`. Passo 2: quem paga (CPF só quando há valor, com máscara e dígitos conferidos) e um bloco por ingresso com as perguntas do tipo; erros num resumo com links para o campo, inclusive os 422 do backend (`items.{i}.attendees.{j}.…`). Reservar manda `Idempotency-Key`, repetida enquanto o corpo for o mesmo. `?reserva=expirada` ou `cancelada` mostra o aviso e recupera a última escolha (`phpeste.checkout.cart.{edição}`) | +| `/checkout/pedido/{id}` | O mesmo caminho que o backend usa na volta do gateway e no lembrete de Pix. Lê o pedido com o token guardado no navegador na reserva (`phpeste.checkout.order.{id}`, header `X-Order-Token`); sem ele, mostra "não encontramos este pedido neste navegador". Contagem regressiva (`role="timer"`, aviso falado com 5 e com 1 minuto), itens, desconto, taxa e total do backend, desistir da reserva. Reserva expirada (no backend ou com o tempo zerado na tela) ou cancelada volta para `/ingressos` | + Componente que depende da sessão observa `isAuthenticated` em vez de esperar um evento do `AuthPanel`: o painel some assim que a sessão existe, e um evento emitido depois disso se perde. Páginas de conta, palestrante e checkout rodam só no navegador (`routeRules`). ## Comandos diff --git a/front-public/app/application/locales/pt-br/index.ts b/front-public/app/application/locales/pt-br/index.ts index 1336d92..63e1963 100644 --- a/front-public/app/application/locales/pt-br/index.ts +++ b/front-public/app/application/locales/pt-br/index.ts @@ -1,9 +1,11 @@ import login from '../../../modules/login/locales/pt-br' import proposals from '../../../modules/proposals/locales/pt-br' +import checkout from '../../../modules/checkout/locales/pt-br' // Every module's locale is registered here — see docs/ARCHITECTURE.md, // "Registro obrigatório". Add one import + one key per new module. export default { login, proposals, + checkout, } diff --git a/front-public/app/application/locales/pt-br/site.ts b/front-public/app/application/locales/pt-br/site.ts index e34cd35..2155b5c 100644 --- a/front-public/app/application/locales/pt-br/site.ts +++ b/front-public/app/application/locales/pt-br/site.ts @@ -13,6 +13,7 @@ export default { retry: 'Tentar de novo', homeLead: 'Área de palestrantes e participantes', homeText: 'Envie e acompanhe suas propostas, confirme sua palestra e cuide da sua viagem.', + homeTickets: 'Comprar ingresso', homeCfp: 'Enviar proposta', homeMine: 'Minhas propostas', } diff --git a/front-public/app/modules/checkout/components/CheckoutComponents.test.ts b/front-public/app/modules/checkout/components/CheckoutComponents.test.ts new file mode 100644 index 0000000..dbbe68d --- /dev/null +++ b/front-public/app/modules/checkout/components/CheckoutComponents.test.ts @@ -0,0 +1,61 @@ +import { mountSuspended } from '@nuxt/test-utils/runtime' +import { reactive } from 'vue' +import { describe, expect, it } from 'vitest' +import DataStep from './DataStep.vue' +import OrderSummary from './OrderSummary.vue' +import TicketPicker from './TicketPicker.vue' +import { translateTicket } from '../composables/translate' +import { ticketPayload } from '../composables/fixtures' + +const flat = (text: string) => text.replace(/\s/g, ' ') +const inteira = translateTicket(ticketPayload('t-1', 'Inteira', 15000, { pass_fee_to_buyer: true, questions: [ + { id: 'camiseta', label: 'Tamanho da camiseta', type: 'select', required: true, options: ['P', 'M'] }, + { id: 'primeira_vez', label: 'Primeira vez no evento?', type: 'boolean', required: false, options: [] }, +], batch: { id: 'b-1', name: '1º lote', price: { amount: 15000, currency: 'BRL' }, ends_at: null, remaining: 1 } })) +const agendado = translateTicket(ticketPayload('t-3', 'Estudante', 7500, { status: 'scheduled', status_label: 'Agendado', batch: null, next_batch: { name: '2º lote', price: { amount: 9000, currency: 'BRL' }, opens_at: '2027-05-01T12:00:00Z' } })) + +describe('TicketPicker', () => { + it('preço, lote, o que resta e quantidade com rótulo; agendado sem seletor', async () => { + const wrapper = await mountSuspended(TicketPicker, { props: { tickets: [inteira, agendado], quantities: {}, options: () => [0, 1], errors: {} } }) + const items = wrapper.findAll('li') + expect(flat(items[0]!.text())).toContain('R$ 150,00') + expect(items[0]!.text()).toContain('Resta 1') + expect(wrapper.find('label[for="qty-t-1"]').text()).toBe('Quantidade de Inteira') + expect(items[1]!.find('select').exists()).toBe(false) + expect(flat(items[1]!.text())).toMatch(/2º lote abre em 1 de maio.* por R\$ 90,00/) + + await wrapper.find('select').setValue('1') + expect(wrapper.emitted('change')).toEqual([['t-1', 1]]) + }) +}) + +describe('OrderSummary', () => { + it('desconto do cupom e taxa só na reserva', async () => { + const wrapper = await mountSuspended(OrderSummary, { props: { lines: [{ type: inteira, quantity: 2, subtotalCents: 30000 }], subtotalCents: 30000, discountCents: 3000, couponCode: 'SERTAO10', totalCents: 27000, feePending: true } }) + const text = flat(wrapper.text()) + expect(text).toContain('2 × Inteira') + expect(text).toContain('Desconto (SERTAO10)') + expect(text).toContain('calculada ao reservar') + expect(text).toContain('Total sem a taxa') + expect(flat(wrapper.find('[data-testid="summary-total"]').text())).toBe('R$ 270,00') + }) +}) + +describe('DataStep', () => { + it('um bloco por ingresso com as perguntas da edição, ids que o resumo de erros encontra e CPF com máscara', async () => { + const attendees = reactive({ 't-1': [{ name: '', email: '', answers: {} }] }) + const buyer = reactive({ name: '', email: '', document: '' }) + const wrapper = await mountSuspended(DataStep, { + props: { lines: [{ type: inteira, quantity: 1, subtotalCents: 15000 }], attendees, errors: { 'items.0.attendees.0.answers.camiseta': 'Responda "Tamanho da camiseta".' }, requiresPayment: true, buyer }, + }) + expect(wrapper.find('legend').text()).toBe('Quem paga') + expect(wrapper.find('[data-testid="attendee-1"] legend').text()).toBe('Ingresso 1 · Inteira') + expect(wrapper.find('#checkout-items-0-attendees-0-answers-camiseta').attributes('aria-invalid')).toBe('true') + expect(wrapper.find('[data-testid="checkout-errors"]').text()).toContain('Ingresso 1 · Inteira: Tamanho da camiseta') + expect(wrapper.findAll('input[type="radio"]')).toHaveLength(2) + + await wrapper.find('#checkout-buyer-document').setValue('52998224725') + expect(buyer.document).toBe('529.982.247-25') + expect((wrapper.find('#checkout-buyer-document').element as HTMLInputElement).value).toBe('529.982.247-25') + }) +}) diff --git a/front-public/app/modules/checkout/components/CheckoutField.vue b/front-public/app/modules/checkout/components/CheckoutField.vue new file mode 100644 index 0000000..838df1e --- /dev/null +++ b/front-public/app/modules/checkout/components/CheckoutField.vue @@ -0,0 +1,30 @@ + + + diff --git a/front-public/app/modules/checkout/components/CheckoutFlow.vue b/front-public/app/modules/checkout/components/CheckoutFlow.vue new file mode 100644 index 0000000..30f27e8 --- /dev/null +++ b/front-public/app/modules/checkout/components/CheckoutFlow.vue @@ -0,0 +1,88 @@ + + + diff --git a/front-public/app/modules/checkout/components/CouponField.vue b/front-public/app/modules/checkout/components/CouponField.vue new file mode 100644 index 0000000..aa6b16c --- /dev/null +++ b/front-public/app/modules/checkout/components/CouponField.vue @@ -0,0 +1,33 @@ + + + diff --git a/front-public/app/modules/checkout/components/DataStep.vue b/front-public/app/modules/checkout/components/DataStep.vue new file mode 100644 index 0000000..e6e272c --- /dev/null +++ b/front-public/app/modules/checkout/components/DataStep.vue @@ -0,0 +1,70 @@ + + + diff --git a/front-public/app/modules/checkout/components/ErrorSummary.vue b/front-public/app/modules/checkout/components/ErrorSummary.vue new file mode 100644 index 0000000..41c3f16 --- /dev/null +++ b/front-public/app/modules/checkout/components/ErrorSummary.vue @@ -0,0 +1,30 @@ + + + diff --git a/front-public/app/modules/checkout/components/OrderDetail.vue b/front-public/app/modules/checkout/components/OrderDetail.vue new file mode 100644 index 0000000..8341d40 --- /dev/null +++ b/front-public/app/modules/checkout/components/OrderDetail.vue @@ -0,0 +1,102 @@ + + + diff --git a/front-public/app/modules/checkout/components/OrderSummary.vue b/front-public/app/modules/checkout/components/OrderSummary.vue new file mode 100644 index 0000000..b9106b4 --- /dev/null +++ b/front-public/app/modules/checkout/components/OrderSummary.vue @@ -0,0 +1,37 @@ + + + diff --git a/front-public/app/modules/checkout/components/QuestionField.vue b/front-public/app/modules/checkout/components/QuestionField.vue new file mode 100644 index 0000000..07b7c2a --- /dev/null +++ b/front-public/app/modules/checkout/components/QuestionField.vue @@ -0,0 +1,39 @@ + + + diff --git a/front-public/app/modules/checkout/components/TicketPicker.vue b/front-public/app/modules/checkout/components/TicketPicker.vue new file mode 100644 index 0000000..ac221c2 --- /dev/null +++ b/front-public/app/modules/checkout/components/TicketPicker.vue @@ -0,0 +1,56 @@ + + + diff --git a/front-public/app/modules/checkout/composables/failure.ts b/front-public/app/modules/checkout/composables/failure.ts new file mode 100644 index 0000000..8ad430e --- /dev/null +++ b/front-public/app/modules/checkout/composables/failure.ts @@ -0,0 +1,15 @@ +import { CheckoutError } from '../services/checkoutError' +import locale from '../locales/pt-br' + +const ALIASES: Record = { buyer_document: 'buyer.document' } + +export interface Failure { message: string, fieldErrors: Record } + +export function failure(error: unknown): Failure { + if (error instanceof CheckoutError && error.statusCode === 422 && error.fieldErrors) { + const fieldErrors = Object.fromEntries(Object.entries(error.fieldErrors).map(([key, messages]) => [ALIASES[key] ?? key, messages[0] ?? ''])) + return { message: Object.values(fieldErrors)[0] || locale.genericError, fieldErrors } + } + if (error instanceof CheckoutError && error.statusCode === null) return { message: locale.offline, fieldErrors: {} } + return { message: locale.genericError, fieldErrors: {} } +} diff --git a/front-public/app/modules/checkout/composables/fixtures.ts b/front-public/app/modules/checkout/composables/fixtures.ts new file mode 100644 index 0000000..6a73001 --- /dev/null +++ b/front-public/app/modules/checkout/composables/fixtures.ts @@ -0,0 +1,45 @@ +import type { OrderPayload, TicketTypePayload } from '../services/checkoutService' + +const money = (amount: number) => ({ amount, currency: 'BRL' }) + +export const ticketPayload = (id: string, name: string, price: number, extra: Partial = {}): TicketTypePayload => ({ + id, + name, + description: null, + min_per_order: 1, + max_per_order: 5, + pass_fee_to_buyer: false, + questions: [], + status: 'on_sale', + status_label: 'À venda', + batch: { id: `b-${id}`, name: '1º lote', price: money(price), ends_at: null, remaining: null }, + next_batch: null, + ...extra, +}) + +export const catalogPayload = (types: TicketTypePayload[], soldOut = false) => ({ data: { sold_out: soldOut, unlocked: false, ticket_types: types } }) + +export const quotePayload = (code: string, subtotal: number, discount: number) => ({ + data: { code, subtotal: money(subtotal), discount: money(discount), total: money(subtotal - discount), requires_payment: subtotal - discount > 0, lines: [] }, +}) + +export const orderPayload = (extra: Partial = {}): OrderPayload => ({ + id: 'o-1', + number: 42, + status: 'awaiting_payment', + status_label: 'Aguardando pagamento', + buyer: { name: 'Ada Lovelace', email: 'ada@x.dev', document: '***.456.789-**' }, + subtotal: money(30000), + discount: money(3000), + fee: money(1080), + total: money(28080), + requires_payment: true, + coupon_code: 'SERTAO10', + expires_at: '2027-03-10T12:30:00Z', + paid_at: null, + items: [ + { id: 'i-1', ticket_type_id: 't-1', ticket_type_name: 'Inteira', batch_name: '1º lote', unit_price: money(15000), discount: money(1500), fee: money(540), total: money(14040), attendee: { name: 'Ada Lovelace', email: 'ada@x.dev' } }, + { id: 'i-2', ticket_type_id: 't-1', ticket_type_name: 'Inteira', batch_name: '1º lote', unit_price: money(15000), discount: money(1500), fee: money(540), total: money(14040), attendee: { name: 'Grace Hopper', email: 'grace@x.dev' } }, + ], + ...extra, +}) diff --git a/front-public/app/modules/checkout/composables/format.test.ts b/front-public/app/modules/checkout/composables/format.test.ts new file mode 100644 index 0000000..8d3531e --- /dev/null +++ b/front-public/app/modules/checkout/composables/format.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { formatCents, formatCountdown, isCpf, isEmail, maskCpf } from './format' + +const flat = (text: string) => text.replace(/\s/g, ' ') + +describe('format', () => { + it('reais, contagem e e-mail', () => { + expect(flat(formatCents(15000))).toBe('R$ 150,00') + expect(formatCountdown(845)).toBe('14:05') + expect(formatCountdown(-3)).toBe('00:00') + expect(isEmail('ada@x.dev')).toBe(true) + expect(isEmail('ada@x')).toBe(false) + }) + + it('CPF: confere os dígitos e põe a máscara enquanto digita', () => { + expect(isCpf('529.982.247-25')).toBe(true) + expect(isCpf('529.982.247-24')).toBe(false) + expect(isCpf('111.111.111-11')).toBe(false) + expect(maskCpf('5299822')).toBe('529.982.2') + expect(maskCpf('52998224725999')).toBe('529.982.247-25') + }) +}) diff --git a/front-public/app/modules/checkout/composables/format.ts b/front-public/app/modules/checkout/composables/format.ts new file mode 100644 index 0000000..7d9ae4f --- /dev/null +++ b/front-public/app/modules/checkout/composables/format.ts @@ -0,0 +1,41 @@ +const brl = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }) + +/** 15000 → "R$ 150,00". */ +export const formatCents = (cents: number) => brl.format(cents / 100) + +const dateTime = new Intl.DateTimeFormat('pt-BR', { day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit' }) + +/** ISO → "10 de junho, 09:00". */ +export const formatDateTime = (iso: string) => dateTime.format(new Date(iso)) + +const clock = new Intl.DateTimeFormat('pt-BR', { hour: '2-digit', minute: '2-digit' }) + +export const formatClock = (iso: string) => clock.format(new Date(iso)) + +/** Segundos → "14:05". */ +export function formatCountdown(seconds: number): string { + const safe = Math.max(0, Math.floor(seconds)) + return `${String(Math.floor(safe / 60)).padStart(2, '0')}:${String(safe % 60).padStart(2, '0')}` +} + +export const digits = (text: string) => text.replace(/\D/g, '') + +/** CPF com os dois dígitos verificadores certos. */ +export function isCpf(text: string): boolean { + const value = digits(text) + if (value.length !== 11 || /^(\d)\1{10}$/.test(value)) return false + const check = (length: number) => { + const sum = [...value.slice(0, length)].reduce((total, digit, index) => total + Number(digit) * (length + 1 - index), 0) + const rest = (sum * 10) % 11 + return rest === 10 ? 0 : rest + } + return check(9) === Number(value[9]) && check(10) === Number(value[10]) +} + +/** "12345678909" → "123.456.789-09", enquanto a pessoa digita. */ +export function maskCpf(text: string): string { + const value = digits(text).slice(0, 11) + return value.replace(/^(\d{3})(\d)/, '$1.$2').replace(/^(\d{3})\.(\d{3})(\d)/, '$1.$2.$3').replace(/\.(\d{3})(\d{1,2})$/, '.$1-$2') +} + +export const isEmail = (text: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text.trim()) diff --git a/front-public/app/modules/checkout/composables/storage.ts b/front-public/app/modules/checkout/composables/storage.ts new file mode 100644 index 0000000..820d135 --- /dev/null +++ b/front-public/app/modules/checkout/composables/storage.ts @@ -0,0 +1,35 @@ +const tokenKey = (orderId: string) => `phpeste.checkout.order.${orderId}` +const cartKey = (editionId: string) => `phpeste.checkout.cart.${editionId}` + +export interface SavedCart { quantities: Record, coupon: string } + +function read(key: string): string | null { + try { + return localStorage.getItem(key) + } catch { + return null + } +} + +function write(key: string, value: string) { + try { + localStorage.setItem(key, value) + } catch { + return + } +} + +export const saveOrderToken = (orderId: string, token: string) => write(tokenKey(orderId), token) + +export const orderToken = (orderId: string) => read(tokenKey(orderId)) + +export const saveCart = (editionId: string, cart: SavedCart) => write(cartKey(editionId), JSON.stringify(cart)) + +export function savedCart(editionId: string): SavedCart | null { + try { + const value = JSON.parse(read(cartKey(editionId)) ?? 'null') as SavedCart | null + return value && typeof value.quantities === 'object' ? { quantities: value.quantities, coupon: typeof value.coupon === 'string' ? value.coupon : '' } : null + } catch { + return null + } +} diff --git a/front-public/app/modules/checkout/composables/translate.ts b/front-public/app/modules/checkout/composables/translate.ts new file mode 100644 index 0000000..9e94a03 --- /dev/null +++ b/front-public/app/modules/checkout/composables/translate.ts @@ -0,0 +1,51 @@ +import type { OrderPayload, QuotePayload, TicketTypePayload } from '../services/checkoutService' +import type { Order, Quote, TicketOption } from '../types' + +export const translateTicket = (payload: TicketTypePayload): TicketOption => ({ + id: payload.id, + name: payload.name, + description: payload.description, + min: payload.min_per_order, + max: payload.max_per_order, + passFee: payload.pass_fee_to_buyer, + questions: payload.questions.map((question) => ({ ...question, options: question.options ?? [] })), + onSale: payload.status === 'on_sale' && payload.batch !== null, + statusLabel: payload.status_label, + batchName: payload.batch?.name ?? null, + priceCents: payload.batch?.price.amount ?? null, + remaining: payload.batch?.remaining ?? null, + endsAt: payload.batch?.ends_at ?? null, + nextBatch: payload.next_batch ? { name: payload.next_batch.name, priceCents: payload.next_batch.price.amount, opensAt: payload.next_batch.opens_at } : null, +}) + +export const translateQuote = (payload: QuotePayload): Quote => ({ + code: payload.code, + subtotalCents: payload.subtotal.amount, + discountCents: payload.discount.amount, + totalCents: payload.total.amount, +}) + +export const translateOrder = (payload: OrderPayload): Order => ({ + id: payload.id, + number: payload.number, + status: payload.status, + statusLabel: payload.status_label, + buyer: { name: payload.buyer.name, email: payload.buyer.email }, + subtotalCents: payload.subtotal.amount, + discountCents: payload.discount.amount, + feeCents: payload.fee.amount, + totalCents: payload.total.amount, + requiresPayment: payload.requires_payment, + couponCode: payload.coupon_code, + expiresAt: payload.expires_at, + items: payload.items.map((item) => ({ + id: item.id, + ticketTypeName: item.ticket_type_name, + batchName: item.batch_name, + unitPriceCents: item.unit_price.amount, + discountCents: item.discount.amount, + feeCents: item.fee.amount, + totalCents: item.total.amount, + attendee: { name: item.attendee.name, email: item.attendee.email }, + })), +}) diff --git a/front-public/app/modules/checkout/composables/useCheckout.test.ts b/front-public/app/modules/checkout/composables/useCheckout.test.ts new file mode 100644 index 0000000..4b9dc6a --- /dev/null +++ b/front-public/app/modules/checkout/composables/useCheckout.test.ts @@ -0,0 +1,140 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import checkoutService from '../services/checkoutService' +import { CheckoutError } from '../services/checkoutError' +import { useCheckout } from './useCheckout' +import { saveCart } from './storage' +import { catalogPayload, orderPayload, quotePayload, ticketPayload } from './fixtures' + +vi.mock('../services/checkoutService', () => ({ default: { catalog: vi.fn(), checkCoupon: vi.fn(), placeOrder: vi.fn(), order: vi.fn(), cancel: vi.fn() } })) + +const shirt = { id: 'camiseta', label: 'Tamanho da camiseta', type: 'select' as const, required: true, options: ['P', 'M', 'G'] } + +beforeEach(() => { + vi.clearAllMocks() + localStorage.clear() + vi.mocked(checkoutService.catalog).mockResolvedValue(catalogPayload([ + ticketPayload('t-1', 'Inteira', 15000, { pass_fee_to_buyer: true, questions: [shirt], batch: { id: 'b-1', name: '1º lote', price: { amount: 15000, currency: 'BRL' }, ends_at: null, remaining: 3 } }), + ticketPayload('t-2', 'Caravana', 10000, { min_per_order: 5, max_per_order: 10 }), + ticketPayload('t-3', 'Estudante', 7500, { status: 'scheduled', status_label: 'Agendado', batch: null, next_batch: { name: '2º lote', price: { amount: 9000, currency: 'BRL' }, opens_at: '2027-05-01T03:00:00Z' } }), + ])) +}) + +async function ready() { + const checkout = useCheckout('ed-1') + await checkout.load() + return checkout +} + +describe('useCheckout', () => { + it('quantidade respeita mínimo, máximo e o que resta; agendado não entra no pedido', async () => { + const checkout = await ready() + expect(checkout.quantityOptions(checkout.tickets.value[0]!)).toEqual([0, 1, 2, 3]) + expect(checkout.quantityOptions(checkout.tickets.value[1]!)).toEqual([0, 5, 6, 7, 8, 9, 10]) + expect(checkout.tickets.value[2]).toMatchObject({ onSale: false, nextBatch: { name: '2º lote', priceCents: 9000 } }) + + checkout.setQuantity('t-1', 2) + expect(checkout.subtotalCents.value).toBe(30000) + expect(checkout.feePending.value).toBe(true) + expect(checkout.requiresPayment.value).toBe(true) + }) + + it('sem ingresso não avança; com ingresso abre um participante por ingresso', async () => { + const checkout = await ready() + expect(checkout.next()).toBe(false) + expect(checkout.message.value).toBe('Escolha pelo menos um ingresso.') + + checkout.setQuantity('t-1', 2) + expect(checkout.next()).toBe(true) + expect(checkout.step.value).toBe(2) + expect(checkout.attendees.value['t-1']).toHaveLength(2) + }) + + it('cupom é conferido na hora e refeito quando a quantidade muda', async () => { + const checkout = await ready() + checkout.couponInput.value = 'sertao10' + expect(await checkout.applyCoupon()).toBe(false) + expect(checkout.couponError.value).toBe('Escolha os ingressos antes de aplicar o cupom.') + + checkout.setQuantity('t-1', 1) + vi.mocked(checkoutService.checkCoupon).mockResolvedValueOnce(quotePayload('SERTAO10', 15000, 1500)) + expect(await checkout.applyCoupon()).toBe(true) + expect(checkoutService.checkCoupon).toHaveBeenLastCalledWith('ed-1', 'SERTAO10', [{ ticket_type_id: 't-1', quantity: 1 }]) + expect(checkout.totalCents.value).toBe(13500) + + vi.mocked(checkoutService.checkCoupon).mockResolvedValueOnce(quotePayload('SERTAO10', 30000, 3000)) + checkout.setQuantity('t-1', 2) + await vi.waitFor(() => expect(checkout.discountCents.value).toBe(3000)) + + vi.mocked(checkoutService.checkCoupon).mockRejectedValueOnce(new CheckoutError('x', 422, { coupon: ['Cupom esgotado.'] })) + checkout.removeCoupon() + checkout.couponInput.value = 'ESGOTADO' + expect(await checkout.applyCoupon()).toBe(false) + expect(checkout.couponError.value).toBe('Cupom esgotado.') + expect(checkout.discountCents.value).toBe(0) + }) + + it('valida comprador, CPF quando há pagamento e perguntas obrigatórias antes de chamar a API', async () => { + const checkout = await ready() + checkout.setQuantity('t-1', 1) + checkout.next() + checkout.buyer.value = { name: 'Ada Lovelace', email: 'ada@x', document: '529.982.247-24' } + + expect(await checkout.reserve()).toBeNull() + expect(checkout.errors.value).toEqual({ + 'buyer.email': 'Confira o e-mail: falta algo como nome@exemplo.com.', + 'buyer.document': 'Confira o CPF: os números não batem.', + 'items.0.attendees.0.name': 'Preencha este campo.', + 'items.0.attendees.0.email': 'Preencha este campo.', + 'items.0.attendees.0.answers.camiseta': 'Responda "Tamanho da camiseta".', + }) + expect(checkoutService.placeOrder).not.toHaveBeenCalled() + }) + + it('reserva, guarda o token e repete a mesma chave numa nova tentativa igual', async () => { + const checkout = await ready() + checkout.setQuantity('t-1', 1) + checkout.next() + checkout.buyer.value = { name: 'Ada Lovelace', email: 'ada@x.dev', document: '529.982.247-25' } + checkout.copyBuyer('t-1', 0) + checkout.attendees.value['t-1']![0]!.answers.camiseta = 'M' + + vi.mocked(checkoutService.placeOrder).mockRejectedValueOnce(new CheckoutError('offline')) + expect(await checkout.reserve()).toBeNull() + expect(checkout.message.value).toBe('Sem conexão com a internet. Confira e tente de novo.') + + vi.mocked(checkoutService.placeOrder).mockResolvedValueOnce({ data: orderPayload({ access_token: 'tok-1' }) }) + expect(await checkout.reserve()).toBe('o-1') + const [first, second] = vi.mocked(checkoutService.placeOrder).mock.calls + expect(first![2]).toBe(second![2]) + expect(second![1]).toEqual({ + buyer: { name: 'Ada Lovelace', email: 'ada@x.dev', document: '529.982.247-25' }, + coupon: null, + items: [{ ticket_type_id: 't-1', attendees: [{ name: 'Ada Lovelace', email: 'ada@x.dev', answers: { camiseta: 'M' } }] }], + }) + expect(localStorage.getItem('phpeste.checkout.order.o-1')).toBe('tok-1') + }) + + it('erro do backend vai para o campo certo, inclusive o CPF', async () => { + const checkout = await ready() + checkout.setQuantity('t-1', 1) + checkout.next() + checkout.buyer.value = { name: 'Ada Lovelace', email: 'ada@x.dev', document: '529.982.247-25' } + checkout.copyBuyer('t-1', 0) + checkout.attendees.value['t-1']![0]!.answers.camiseta = 'M' + vi.mocked(checkoutService.placeOrder).mockRejectedValueOnce(new CheckoutError('x', 422, { buyer_document: ['Informe o CPF de quem paga.'], items: ['Cada pessoa compra no máximo 2 ingressos nesta edição.'] })) + + expect(await checkout.reserve()).toBeNull() + expect(checkout.errors.value).toEqual({ 'buyer.document': 'Informe o CPF de quem paga.' }) + expect(checkout.message.value).toBe('Cada pessoa compra no máximo 2 ingressos nesta edição.') + }) + + it('depois de uma reserva expirada, volta com a escolha anterior', async () => { + saveCart('ed-1', { quantities: { 't-1': 2, 't-3': 1 }, coupon: 'SERTAO10' }) + vi.mocked(checkoutService.checkCoupon).mockResolvedValue(quotePayload('SERTAO10', 30000, 3000)) + const checkout = useCheckout('ed-1') + await checkout.load(true) + + expect(checkout.quantities.value).toEqual({ 't-1': 2 }) + expect(checkout.quote.value?.code).toBe('SERTAO10') + }) +}) diff --git a/front-public/app/modules/checkout/composables/useCheckout.ts b/front-public/app/modules/checkout/composables/useCheckout.ts new file mode 100644 index 0000000..5dc5b57 --- /dev/null +++ b/front-public/app/modules/checkout/composables/useCheckout.ts @@ -0,0 +1,259 @@ +import { computed, ref } from 'vue' +import checkoutService, { type PlaceOrderBody } from '../services/checkoutService' +import locale from '../locales/pt-br' +import { failure } from './failure' +import { isCpf, isEmail } from './format' +import { saveCart, saveOrderToken, savedCart } from './storage' +import { translateQuote, translateTicket } from './translate' +import type { AttendeeForm, BuyerForm, Quote, SelectedLine, TicketOption } from '../types' + +const FIELD_PREFIX = 'checkout-' + +/** "items.0.attendees.1.name" → "checkout-items-0-attendees-1-name". */ +export const fieldId = (path: string) => `${FIELD_PREFIX}${path.replace(/\./g, '-')}` + +const newKey = () => (globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`) + +export function useCheckout(editionId: string) { + const tickets = ref([]) + const soldOut = ref(false) + const state = ref<'loading' | 'ready' | 'error'>('loading') + const step = ref<1 | 2>(1) + const quantities = ref>({}) + const couponInput = ref('') + const quote = ref(null) + const couponError = ref(null) + const couponBusy = ref(false) + const buyer = ref({ name: '', email: '', document: '' }) + const attendees = ref>({}) + const errors = ref>({}) + const message = ref(null) + const busy = ref(false) + let quoteRequest = 0 + let idempotency: { body: string, key: string } | null = null + + const lines = computed(() => tickets.value + .filter((ticket) => ticket.onSale && (quantities.value[ticket.id] ?? 0) > 0) + .map((ticket) => { + const quantity = quantities.value[ticket.id] ?? 0 + return { type: ticket, quantity, subtotalCents: (ticket.priceCents ?? 0) * quantity } + })) + const count = computed(() => lines.value.reduce((sum, line) => sum + line.quantity, 0)) + const subtotalCents = computed(() => lines.value.reduce((sum, line) => sum + line.subtotalCents, 0)) + const discountCents = computed(() => quote.value?.discountCents ?? 0) + const totalCents = computed(() => Math.max(0, subtotalCents.value - discountCents.value)) + const feePending = computed(() => totalCents.value > 0 && lines.value.some((line) => line.type.passFee)) + const requiresPayment = computed(() => totalCents.value > 0) + + const minErrors = computed(() => Object.fromEntries(lines.value + .filter((line) => line.quantity < line.type.min) + .map((line) => [line.type.id, locale.minError.replace('{min}', String(line.type.min)).replace('{nome}', line.type.name)]))) + + /** Opções de quantidade: zero e o intervalo do tipo, sem passar do que resta. */ + const quantityOptions = (ticket: TicketOption) => { + const max = Math.min(ticket.max, ticket.remaining ?? ticket.max, 50) + return [0, ...Array.from({ length: Math.max(0, max - ticket.min + 1) }, (_, index) => ticket.min + index)] + } + + async function load(restore = false) { + state.value = 'loading' + try { + const catalog = (await checkoutService.catalog(editionId)).data + tickets.value = catalog.ticket_types.map(translateTicket) + soldOut.value = catalog.sold_out + state.value = 'ready' + } catch { + state.value = 'error' + return + } + if (!restore) return + const cart = savedCart(editionId) + if (!cart) return + const next: Record = {} + for (const ticket of tickets.value) { + const wanted = cart.quantities[ticket.id] ?? 0 + if (ticket.onSale && wanted > 0 && quantityOptions(ticket).includes(wanted)) next[ticket.id] = wanted + } + quantities.value = next + if (cart.coupon && Object.keys(next).length) { + couponInput.value = cart.coupon + await applyCoupon() + } + } + + async function requote() { + const code = quote.value?.code + if (!code) return + if (!lines.value.length) { + quote.value = null + return + } + const request = ++quoteRequest + try { + const response = await checkoutService.checkCoupon(editionId, code, lines.value.map((line) => ({ ticket_type_id: line.type.id, quantity: line.quantity }))) + if (request === quoteRequest) quote.value = translateQuote(response.data) + } catch (error) { + if (request !== quoteRequest) return + quote.value = null + couponError.value = failure(error).fieldErrors.coupon ?? locale.couponInvalid + } + } + + function setQuantity(ticketId: string, quantity: number) { + quantities.value = { ...quantities.value, [ticketId]: quantity } + message.value = null + void requote() + } + + async function applyCoupon() { + const code = couponInput.value.trim().toUpperCase() + couponError.value = null + if (!code) { + couponError.value = locale.requiredField + return false + } + if (!lines.value.length) { + couponError.value = locale.couponNeedsTickets + return false + } + couponBusy.value = true + const request = ++quoteRequest + try { + const response = await checkoutService.checkCoupon(editionId, code, lines.value.map((line) => ({ ticket_type_id: line.type.id, quantity: line.quantity }))) + if (request !== quoteRequest) return false + quote.value = translateQuote(response.data) + couponInput.value = quote.value.code + return true + } catch (error) { + if (request !== quoteRequest) return false + const result = failure(error) + quote.value = null + couponError.value = result.fieldErrors.code ?? result.fieldErrors.coupon ?? result.fieldErrors.items ?? result.message + return false + } finally { + couponBusy.value = false + } + } + + function removeCoupon() { + quoteRequest++ + quote.value = null + couponInput.value = '' + couponError.value = null + } + + function syncAttendees() { + const next: Record = {} + for (const line of lines.value) { + const current = attendees.value[line.type.id] ?? [] + next[line.type.id] = Array.from({ length: line.quantity }, (_, index) => current[index] ?? { name: '', email: '', answers: {} }) + } + attendees.value = next + } + + function next(): boolean { + message.value = null + if (!lines.value.length) { + message.value = locale.chooseFirst + return false + } + if (Object.keys(minErrors.value).length) { + message.value = Object.values(minErrors.value)[0]! + return false + } + syncAttendees() + errors.value = {} + step.value = 2 + return true + } + + function back() { + errors.value = {} + message.value = null + step.value = 1 + } + + function copyBuyer(ticketId: string, index: number) { + const list = attendees.value[ticketId] + if (!list?.[index]) return + list[index] = { ...list[index]!, name: buyer.value.name, email: buyer.value.email } + } + + function validate(): Record { + const found: Record = {} + const person = (prefix: string, value: { name: string, email: string }) => { + if (value.name.trim() === '') found[`${prefix}.name`] = locale.requiredField + else if (value.name.trim().length < 2) found[`${prefix}.name`] = locale.nameShort + if (value.email.trim() === '') found[`${prefix}.email`] = locale.requiredField + else if (!isEmail(value.email)) found[`${prefix}.email`] = locale.emailInvalid + } + person('buyer', buyer.value) + if (requiresPayment.value) { + if (buyer.value.document.trim() === '') found['buyer.document'] = locale.requiredField + else if (!isCpf(buyer.value.document)) found['buyer.document'] = locale.cpfInvalid + } else if (buyer.value.document.trim() !== '' && !isCpf(buyer.value.document)) { + found['buyer.document'] = locale.cpfInvalid + } + lines.value.forEach((line, itemIndex) => { + ;(attendees.value[line.type.id] ?? []).forEach((attendee, position) => { + const prefix = `items.${itemIndex}.attendees.${position}` + person(prefix, attendee) + for (const question of line.type.questions) { + const answer = attendee.answers[question.id] + if (question.required && (answer === undefined || (typeof answer === 'string' && answer.trim() === ''))) { + found[`${prefix}.answers.${question.id}`] = locale.answerRequired.replace('{pergunta}', question.label) + } + } + }) + }) + return found + } + + const body = (): PlaceOrderBody => ({ + buyer: { name: buyer.value.name.trim(), email: buyer.value.email.trim(), document: buyer.value.document.trim() === '' ? null : buyer.value.document }, + coupon: quote.value?.code ?? null, + items: lines.value.map((line) => ({ + ticket_type_id: line.type.id, + attendees: (attendees.value[line.type.id] ?? []).map((attendee) => ({ + name: attendee.name.trim(), + email: attendee.email.trim(), + answers: Object.fromEntries(line.type.questions + .map((question) => [question.id, attendee.answers[question.id]] as const) + .filter((entry): entry is readonly [string, string | boolean] => entry[1] !== undefined && entry[1] !== '')), + })), + })), + }) + + /** Cria a reserva. A mesma tentativa repete a mesma Idempotency-Key, para não reservar duas vezes. */ + async function reserve(): Promise { + message.value = null + errors.value = validate() + if (Object.keys(errors.value).length) return null + const payload = body() + const serialized = JSON.stringify(payload) + if (idempotency?.body !== serialized) idempotency = { body: serialized, key: newKey() } + busy.value = true + try { + const order = (await checkoutService.placeOrder(editionId, payload, idempotency.key)).data + if (order.access_token) saveOrderToken(order.id, order.access_token) + saveCart(editionId, { quantities: Object.fromEntries(lines.value.map((line) => [line.type.id, line.quantity])), coupon: quote.value?.code ?? '' }) + return order.id + } catch (error) { + const result = failure(error) + const fields = Object.fromEntries(Object.entries(result.fieldErrors).filter(([key]) => key.startsWith('buyer.') || /^items\.\d+\.attendees\./.test(key))) + errors.value = fields + const general = Object.entries(result.fieldErrors).find(([key]) => !(key in fields)) + message.value = general ? general[1] : (Object.keys(fields).length ? null : result.message) + if (general && /^items|coupon/.test(general[0])) idempotency = null + return null + } finally { + busy.value = false + } + } + + return { + tickets, soldOut, state, step, quantities, couponInput, quote, couponError, couponBusy, buyer, attendees, errors, message, busy, + lines, count, subtotalCents, discountCents, totalCents, feePending, requiresPayment, minErrors, + quantityOptions, load, setQuantity, applyCoupon, removeCoupon, next, back, copyBuyer, reserve, + } +} diff --git a/front-public/app/modules/checkout/composables/useOrder.test.ts b/front-public/app/modules/checkout/composables/useOrder.test.ts new file mode 100644 index 0000000..3da7276 --- /dev/null +++ b/front-public/app/modules/checkout/composables/useOrder.test.ts @@ -0,0 +1,70 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import checkoutService from '../services/checkoutService' +import { CheckoutError } from '../services/checkoutError' +import { useOrder } from './useOrder' +import { saveOrderToken } from './storage' +import { orderPayload } from './fixtures' + +vi.mock('../services/checkoutService', () => ({ default: { catalog: vi.fn(), checkCoupon: vi.fn(), placeOrder: vi.fn(), order: vi.fn(), cancel: vi.fn() } })) + +beforeEach(() => { + vi.clearAllMocks() + localStorage.clear() +}) + +afterEach(() => vi.useRealTimers()) + +describe('useOrder', () => { + it('sem o token deste navegador o pedido não é encontrado', async () => { + const order = useOrder('ed-1', 'o-1') + await order.load() + expect(order.state.value).toBe('not_found') + expect(checkoutService.order).not.toHaveBeenCalled() + }) + + it('conta o tempo da reserva e marca expirada quando zera', async () => { + saveOrderToken('o-1', 'tok') + vi.mocked(checkoutService.order).mockResolvedValue({ data: orderPayload() }) + vi.useFakeTimers() + vi.setSystemTime(new Date('2027-03-10T12:28:00Z')) + const order = useOrder('ed-1', 'o-1') + await order.load() + + expect(checkoutService.order).toHaveBeenCalledWith('ed-1', 'o-1', 'tok') + expect(order.order.value).toMatchObject({ number: 42, feeCents: 1080, totalCents: 28080 }) + expect(order.secondsLeft.value).toBe(120) + expect(order.lapsed.value).toBeNull() + + await vi.advanceTimersByTimeAsync(120_000) + expect(order.secondsLeft.value).toBe(0) + expect(order.lapsed.value).toBe('expired') + order.stop() + }) + + it('expirado no backend ou cancelado pela pessoa', async () => { + saveOrderToken('o-1', 'tok') + vi.mocked(checkoutService.order).mockResolvedValue({ data: orderPayload({ status: 'expired' }) }) + const expired = useOrder('ed-1', 'o-1') + await expired.load() + expect(expired.lapsed.value).toBe('expired') + + vi.mocked(checkoutService.order).mockResolvedValue({ data: orderPayload({ expires_at: '2999-01-01T00:00:00Z' }) }) + vi.mocked(checkoutService.cancel).mockResolvedValue({ data: orderPayload({ status: 'cancelled' }) }) + const order = useOrder('ed-1', 'o-1') + await order.load() + expect(await order.cancel()).toBeNull() + expect(order.lapsed.value).toBe('cancelled') + }) + + it('404 vira pedido não encontrado; outros erros, erro com tentar de novo', async () => { + saveOrderToken('o-1', 'tok') + vi.mocked(checkoutService.order).mockRejectedValueOnce(new CheckoutError('x', 404)) + const order = useOrder('ed-1', 'o-1') + await order.load() + expect(order.state.value).toBe('not_found') + + vi.mocked(checkoutService.order).mockRejectedValueOnce(new CheckoutError('x', 500)) + await order.load() + expect(order.state.value).toBe('error') + }) +}) diff --git a/front-public/app/modules/checkout/composables/useOrder.ts b/front-public/app/modules/checkout/composables/useOrder.ts new file mode 100644 index 0000000..811b7b3 --- /dev/null +++ b/front-public/app/modules/checkout/composables/useOrder.ts @@ -0,0 +1,77 @@ +import { computed, ref } from 'vue' +import checkoutService from '../services/checkoutService' +import { CheckoutError } from '../services/checkoutError' +import { failure } from './failure' +import { orderToken } from './storage' +import { translateOrder } from './translate' +import type { Order } from '../types' + +const HOLDING = ['created', 'awaiting_payment'] + +export function useOrder(editionId: string, orderId: string, clock: () => number = Date.now) { + const order = ref(null) + const state = ref<'loading' | 'ready' | 'not_found' | 'error'>('loading') + const now = ref(clock()) + const busy = ref(false) + const token = orderToken(orderId) + let timer: ReturnType | null = null + + const holding = computed(() => !!order.value && HOLDING.includes(order.value.status)) + const secondsLeft = computed(() => { + const expiresAt = order.value?.expiresAt + if (!holding.value || !expiresAt) return null + return Math.max(0, Math.floor((new Date(expiresAt).getTime() - now.value) / 1000)) + }) + /** Reserva que acabou: expirou no backend ou o tempo zerou na tela. */ + const lapsed = computed<'expired' | 'cancelled' | null>(() => { + if (order.value?.status === 'expired') return 'expired' + if (order.value?.status === 'cancelled') return 'cancelled' + return secondsLeft.value === 0 ? 'expired' : null + }) + + function tick() { + now.value = clock() + } + + function start() { + stop() + timer = setInterval(tick, 1000) + } + + function stop() { + if (timer) clearInterval(timer) + timer = null + } + + async function load() { + if (!token) { + state.value = 'not_found' + return + } + state.value = 'loading' + try { + order.value = translateOrder((await checkoutService.order(editionId, orderId, token)).data) + tick() + state.value = 'ready' + if (holding.value) start() + } catch (error) { + state.value = error instanceof CheckoutError && error.statusCode === 404 ? 'not_found' : 'error' + } + } + + async function cancel(): Promise { + if (!token) return null + busy.value = true + try { + order.value = translateOrder((await checkoutService.cancel(editionId, orderId, token)).data) + stop() + return null + } catch (error) { + return failure(error).message + } finally { + busy.value = false + } + } + + return { order, state, busy, holding, secondsLeft, lapsed, load, cancel, tick, stop } +} diff --git a/front-public/app/modules/checkout/locales/pt-br/index.ts b/front-public/app/modules/checkout/locales/pt-br/index.ts new file mode 100644 index 0000000..933c6ed --- /dev/null +++ b/front-public/app/modules/checkout/locales/pt-br/index.ts @@ -0,0 +1,92 @@ +export default { + title: 'Ingressos', + intro: 'Escolha os ingressos, preencha os dados de quem vai e garanta sua vaga.', + steps: ['', 'Escolha', 'Seus dados'] as string[], + stepOf: 'Passo {n} de 2: {nome}', + loadError: 'Não deu para carregar os ingressos.', + retry: 'Tentar de novo', + genericError: 'Não deu para concluir agora. Tente de novo em instantes.', + offline: 'Sem conexão com a internet. Confira e tente de novo.', + + soldOut: 'Ingressos esgotados para esta edição.', + noTickets: 'Nenhum ingresso à venda agora.', + expired: 'Sua reserva expirou e os ingressos voltaram para a venda. Escolha de novo para garantir os seus.', + cancelled: 'Você desistiu da reserva e os ingressos voltaram para a venda.', + + ticketsLabel: 'Ingressos à venda', + quantity: 'Quantidade de {nome}', + remaining: 'Restam {n}', + remainingOne: 'Resta 1', + batchUntil: '{lote}, até {data}', + opensAt: '{lote} abre em {data} por {preco}', + perOrder: 'De {min} a {max} por pedido', + upTo: 'Até {max} por pedido', + minError: 'Escolha pelo menos {min} de "{nome}" ou deixe em zero.', + free: 'Gratuito', + + coupon: 'Cupom de desconto', + couponApply: 'Aplicar', + couponRemove: 'Remover cupom', + couponApplied: 'Cupom {codigo} aplicado: {valor} de desconto.', + couponNeedsTickets: 'Escolha os ingressos antes de aplicar o cupom.', + couponInvalid: 'Este cupom não vale para os ingressos escolhidos.', + + summary: 'Resumo do pedido', + line: '{qtd} × {nome}', + subtotal: 'Subtotal', + discount: 'Desconto ({codigo})', + fee: 'Taxa de serviço', + feeLater: 'calculada ao reservar', + total: 'Total', + totalBeforeFee: 'Total sem a taxa', + nothingSelected: 'Nenhum ingresso escolhido ainda.', + continue: 'Continuar', + chooseFirst: 'Escolha pelo menos um ingresso.', + back: 'Voltar para a escolha', + + buyerTitle: 'Quem paga', + buyerHint: 'Enviamos o pedido e os ingressos para este e-mail.', + name: 'Nome completo', + email: 'E-mail', + cpf: 'CPF', + cpfHint: 'Exigido pelo meio de pagamento.', + attendeesTitle: 'Quem vai', + attendeesHint: 'Cada ingresso é de uma pessoa: o nome vai no crachá e o QR code chega no e-mail dela.', + attendee: 'Ingresso {n} · {tipo}', + useBuyer: 'Usar os dados de quem paga', + yes: 'Sim', + no: 'Não', + required: '(obrigatório)', + + requiredField: 'Preencha este campo.', + nameShort: 'Escreva o nome completo.', + emailInvalid: 'Confira o e-mail: falta algo como nome@exemplo.com.', + cpfInvalid: 'Confira o CPF: os números não batem.', + answerRequired: 'Responda "{pergunta}".', + errorsTitle: 'Falta corrigir {n} campos antes de reservar.', + errorsTitleOne: 'Falta corrigir 1 campo antes de reservar.', + + reserve: 'Reservar e ir para o pagamento', + reserveFree: 'Confirmar inscrição', + reserveHint: 'Os ingressos ficam reservados para você por alguns minutos enquanto paga.', + reserving: 'Reservando…', + + orderTitle: 'Pedido #{numero}', + orderLoading: 'Carregando o pedido…', + orderNotFound: 'Não encontramos este pedido neste navegador. Abra o link do e-mail do pedido ou comece de novo.', + startOver: 'Escolher ingressos', + reservedUntil: 'Ingressos reservados até {hora}', + timeLeft: 'Tempo para pagar', + timeLeftLabel: '{tempo} para pagar antes de a reserva expirar', + minutesLeft: 'Faltam {n} minutos para a reserva expirar.', + oneMinuteLeft: 'Falta 1 minuto para a reserva expirar.', + paid: 'Inscrição confirmada', + paidText: 'Enviamos os ingressos para o e-mail de cada participante.', + awaiting: 'Pedido reservado', + awaitingText: 'O pagamento confirma a compra. Se a reserva expirar, os ingressos voltam para a venda.', + buyerLine: '{nome} ({email})', + itemsTitle: 'Ingressos', + cancel: 'Desistir e liberar os ingressos', + cancelConfirm: 'Desistir da reserva? Os ingressos voltam para a venda.', + keep: 'Manter a reserva', +} diff --git a/front-public/app/modules/checkout/router/index.ts b/front-public/app/modules/checkout/router/index.ts new file mode 100644 index 0000000..3d6a2d5 --- /dev/null +++ b/front-public/app/modules/checkout/router/index.ts @@ -0,0 +1,11 @@ +import type { RouteRecordRaw } from 'vue-router' + +const CheckoutView = () => import('../views/CheckoutView.vue') +const OrderView = () => import('../views/OrderView.vue') + +export const checkoutRoutes: RouteRecordRaw[] = [ + { path: '/ingressos', name: 'checkout', component: CheckoutView }, + { path: '/checkout/pedido/:id', name: 'checkout-order', component: OrderView }, +] + +export default checkoutRoutes diff --git a/front-public/app/modules/checkout/services/checkoutError.ts b/front-public/app/modules/checkout/services/checkoutError.ts new file mode 100644 index 0000000..e3ad8c2 --- /dev/null +++ b/front-public/app/modules/checkout/services/checkoutError.ts @@ -0,0 +1,11 @@ +export class CheckoutError extends Error { + statusCode: number | null + fieldErrors: Record | null + + constructor(message: string, statusCode: number | null = null, fieldErrors: Record | null = null) { + super(message) + this.name = 'CheckoutError' + this.statusCode = statusCode + this.fieldErrors = fieldErrors + } +} diff --git a/front-public/app/modules/checkout/services/checkoutService.test.ts b/front-public/app/modules/checkout/services/checkoutService.test.ts new file mode 100644 index 0000000..d22f9b4 --- /dev/null +++ b/front-public/app/modules/checkout/services/checkoutService.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it, vi } from 'vitest' +import { httpClient, HttpClientError } from '@/infrastructure/http/HttpClient' +import checkoutService from './checkoutService' +import { CheckoutError } from './checkoutError' + +vi.mock('@/infrastructure/http/HttpClient', () => ({ + httpClient: { get: vi.fn(), post: vi.fn() }, + HttpClientError: class extends Error { + statusCode: number | null + fieldErrors: Record | null + + constructor(message: string, statusCode: number | null = null, fieldErrors: Record | null = null) { + super(message) + this.statusCode = statusCode + this.fieldErrors = fieldErrors + } + }, +})) + +describe('checkoutService', () => { + it('chama as rotas públicas e do checkout com a chave de idempotência e o token do pedido', async () => { + vi.mocked(httpClient.get).mockResolvedValue({ data: {} }) + vi.mocked(httpClient.post).mockResolvedValue({ data: {} }) + const body = { buyer: { name: 'Ada', email: 'ada@x.dev', document: null }, coupon: null, items: [] } + + await checkoutService.catalog('ed-1') + await checkoutService.checkCoupon('ed-1', 'SERTAO10', [{ ticket_type_id: 't-1', quantity: 2 }]) + await checkoutService.placeOrder('ed-1', body, 'key-1') + await checkoutService.order('ed-1', 'o-1', 'tok') + await checkoutService.cancel('ed-1', 'o-1', 'tok') + + expect(httpClient.get).toHaveBeenCalledWith('/public/editions/ed-1/tickets') + expect(httpClient.post).toHaveBeenCalledWith('/public/editions/ed-1/coupons/check', { body: { code: 'SERTAO10', items: [{ ticket_type_id: 't-1', quantity: 2 }] } }) + expect(httpClient.post).toHaveBeenCalledWith('/checkout/editions/ed-1/orders', { body, headers: { 'Idempotency-Key': 'key-1' } }) + expect(httpClient.get).toHaveBeenCalledWith('/checkout/editions/ed-1/orders/o-1', { headers: { 'X-Order-Token': 'tok' } }) + expect(httpClient.post).toHaveBeenCalledWith('/checkout/editions/ed-1/orders/o-1/cancel', { headers: { 'X-Order-Token': 'tok' } }) + }) + + it('troca o erro HTTP pelo erro do módulo', async () => { + vi.mocked(httpClient.post).mockRejectedValue(new HttpClientError('x', 422, { coupon: ['Cupom não encontrado.'] })) + await expect(checkoutService.checkCoupon('ed-1', 'X', [])).rejects.toMatchObject({ name: 'CheckoutError', statusCode: 422, fieldErrors: { coupon: ['Cupom não encontrado.'] } }) + vi.mocked(httpClient.get).mockRejectedValue(new Error('offline')) + await expect(checkoutService.catalog('ed-1')).rejects.toBeInstanceOf(CheckoutError) + }) +}) diff --git a/front-public/app/modules/checkout/services/checkoutService.ts b/front-public/app/modules/checkout/services/checkoutService.ts new file mode 100644 index 0000000..f33f991 --- /dev/null +++ b/front-public/app/modules/checkout/services/checkoutService.ts @@ -0,0 +1,80 @@ +import { httpClient, HttpClientError } from '@/infrastructure/http/HttpClient' +import { CheckoutError } from './checkoutError' + +export interface Money { amount: number, currency: string } + +export interface QuestionPayload { id: string, label: string, type: 'text' | 'select' | 'boolean', required: boolean, options: string[] } + +export interface TicketTypePayload { + id: string + name: string + description: string | null + min_per_order: number + max_per_order: number + pass_fee_to_buyer: boolean + questions: QuestionPayload[] + status: 'scheduled' | 'on_sale' | 'sold_out' | 'ended' + status_label: string + batch: { id: string, name: string, price: Money, ends_at: string | null, remaining: number | null } | null + next_batch: { name: string, price: Money, opens_at: string | null } | null +} + +export interface CatalogPayload { sold_out: boolean, unlocked: boolean, ticket_types: TicketTypePayload[] } + +export interface QuotePayload { + code: string + subtotal: Money + discount: Money + total: Money + requires_payment: boolean + lines: Array<{ ticket_type_id: string, quantity: number, discount: Money, total: Money }> +} + +export interface OrderPayload { + id: string + number: number + status: 'created' | 'awaiting_payment' | 'paid' | 'expired' | 'cancelled' | 'refunded' + status_label: string + buyer: { name: string, email: string, document: string | null } + subtotal: Money + discount: Money + fee: Money + total: Money + requires_payment: boolean + coupon_code: string | null + expires_at: string | null + paid_at: string | null + items: Array<{ id: string, ticket_type_id: string, ticket_type_name: string, batch_name: string | null, unit_price: Money, discount: Money, fee: Money, total: Money, attendee: { name: string, email: string } }> + access_token?: string +} + +export interface PlaceOrderBody { + buyer: { name: string, email: string, document: string | null } + coupon: string | null + items: Array<{ ticket_type_id: string, attendees: Array<{ name: string, email: string, answers: Record }> }> +} + +async function call(request: () => Promise): Promise { + try { + return await request() + } catch (error) { + if (error instanceof HttpClientError) { + throw new CheckoutError(error.message, error.statusCode, error.fieldErrors) + } + throw new CheckoutError('Request failed') + } +} + +const orders = (editionId: string) => `/checkout/editions/${editionId}/orders` + +export default { + catalog: (editionId: string) => call(() => httpClient.get<{ data: CatalogPayload }>(`/public/editions/${editionId}/tickets`)), + checkCoupon: (editionId: string, code: string, items: Array<{ ticket_type_id: string, quantity: number }>) => + call(() => httpClient.post<{ data: QuotePayload }>(`/public/editions/${editionId}/coupons/check`, { body: { code, items } })), + placeOrder: (editionId: string, body: PlaceOrderBody, idempotencyKey: string) => + call(() => httpClient.post<{ data: OrderPayload }>(orders(editionId), { body, headers: { 'Idempotency-Key': idempotencyKey } })), + order: (editionId: string, orderId: string, token: string) => + call(() => httpClient.get<{ data: OrderPayload }>(`${orders(editionId)}/${orderId}`, { headers: { 'X-Order-Token': token } })), + cancel: (editionId: string, orderId: string, token: string) => + call(() => httpClient.post<{ data: OrderPayload }>(`${orders(editionId)}/${orderId}/cancel`, { headers: { 'X-Order-Token': token } })), +} diff --git a/front-public/app/modules/checkout/types/index.ts b/front-public/app/modules/checkout/types/index.ts new file mode 100644 index 0000000..17eeb60 --- /dev/null +++ b/front-public/app/modules/checkout/types/index.ts @@ -0,0 +1,50 @@ +export interface Question { id: string, label: string, type: 'text' | 'select' | 'boolean', required: boolean, options: string[] } + +export interface TicketOption { + id: string + name: string + description: string | null + min: number + max: number + passFee: boolean + questions: Question[] + onSale: boolean + statusLabel: string + batchName: string | null + priceCents: number | null + remaining: number | null + endsAt: string | null + nextBatch: { name: string, priceCents: number, opensAt: string | null } | null +} + +export interface Quote { code: string, subtotalCents: number, discountCents: number, totalCents: number } + +export type Answer = string | boolean + +export interface Person { name: string, email: string } + +export interface AttendeeForm extends Person { answers: Record } + +export interface BuyerForm extends Person { document: string } + +export interface SelectedLine { type: TicketOption, quantity: number, subtotalCents: number } + +export interface OrderItem { id: string, ticketTypeName: string, batchName: string | null, unitPriceCents: number, discountCents: number, feeCents: number, totalCents: number, attendee: Person } + +export type OrderStatus = 'created' | 'awaiting_payment' | 'paid' | 'expired' | 'cancelled' | 'refunded' + +export interface Order { + id: string + number: number + status: OrderStatus + statusLabel: string + buyer: Person + subtotalCents: number + discountCents: number + feeCents: number + totalCents: number + requiresPayment: boolean + couponCode: string | null + expiresAt: string | null + items: OrderItem[] +} diff --git a/front-public/app/modules/checkout/views/CheckoutView.vue b/front-public/app/modules/checkout/views/CheckoutView.vue new file mode 100644 index 0000000..c9d6659 --- /dev/null +++ b/front-public/app/modules/checkout/views/CheckoutView.vue @@ -0,0 +1,17 @@ + + + diff --git a/front-public/app/modules/checkout/views/OrderView.vue b/front-public/app/modules/checkout/views/OrderView.vue new file mode 100644 index 0000000..547fd17 --- /dev/null +++ b/front-public/app/modules/checkout/views/OrderView.vue @@ -0,0 +1,16 @@ + + + diff --git a/front-public/app/pages/checkout/pedido/[id].vue b/front-public/app/pages/checkout/pedido/[id].vue new file mode 100644 index 0000000..3e721a0 --- /dev/null +++ b/front-public/app/pages/checkout/pedido/[id].vue @@ -0,0 +1,7 @@ + + + diff --git a/front-public/app/pages/index.vue b/front-public/app/pages/index.vue index a12009c..abe1188 100644 --- a/front-public/app/pages/index.vue +++ b/front-public/app/pages/index.vue @@ -11,7 +11,8 @@ const { edition } = useCurrentEdition()

    {{ edition?.name }}

    {{ locale.homeText }}

    - {{ locale.homeCfp }} + {{ locale.homeTickets }} + {{ locale.homeCfp }} {{ locale.homeMine }}
    diff --git a/front-public/app/pages/ingressos/index.vue b/front-public/app/pages/ingressos/index.vue new file mode 100644 index 0000000..407ae8c --- /dev/null +++ b/front-public/app/pages/ingressos/index.vue @@ -0,0 +1,7 @@ + + + diff --git a/front-public/e2e/checkout.spec.ts b/front-public/e2e/checkout.spec.ts new file mode 100644 index 0000000..fdac654 --- /dev/null +++ b/front-public/e2e/checkout.spec.ts @@ -0,0 +1,214 @@ +import { expect, test } from '@nuxt/test-utils/playwright' +import type { Page } from '@playwright/test' + +const money = (amount: number) => ({ amount, currency: 'BRL' }) +const ticket = (id: string, name: string, price: number, extra: Record = {}) => ({ + id, name, description: null, min_per_order: 1, max_per_order: 4, pass_fee_to_buyer: true, questions: [], status: 'on_sale', status_label: 'À venda', + batch: { id: `b-${id}`, name: '1º lote', price: money(price), ends_at: null, remaining: null }, next_batch: null, ...extra, +}) +const TICKETS = [ + ticket('t-1', 'Inteira', 15000, { questions: [{ id: 'camiseta', label: 'Tamanho da camiseta', type: 'select', required: true, options: ['P', 'M', 'G'] }], batch: { id: 'b-1', name: '1º lote', price: money(15000), ends_at: null, remaining: 12 } }), + ticket('t-2', 'Meia', 7500), + ticket('t-3', 'Estudante', 6000, { status: 'scheduled', status_label: 'Agendado', batch: null, next_batch: { name: '2º lote', price: money(9000), opens_at: '2027-05-01T12:00:00Z' } }), +] + +interface Call { method: string, path: string, body: unknown, headers: Record } +interface Options { expiresInSeconds?: number, orderStatus?: string, placeError?: Record } + +async function mockApi(page: Page, options: Options = {}) { + const calls: Call[] = [] + let order: Record | null = null + await page.route('**/api/v1/public/editions/ed-a/**', async (route) => { + const request = route.request() + const path = new URL(request.url()).pathname.replace('/api/v1/public/editions/ed-a', '') + calls.push({ method: request.method(), path, body: request.postDataJSON?.() ?? null, headers: request.headers() }) + if (path === '/tickets') return route.fulfill({ json: { data: { sold_out: false, unlocked: false, ticket_types: TICKETS } } }) + if (path === '/coupons/check') { + const body = request.postDataJSON() as { code: string, items: Array<{ ticket_type_id: string, quantity: number }> } + if (body.code !== 'SERTAO10') return route.fulfill({ status: 422, json: { code: 'validation_error', message: 'x', errors: { coupon: ['Cupom não encontrado.'] } } }) + const subtotal = body.items.reduce((sum, item) => sum + item.quantity * (item.ticket_type_id === 't-1' ? 15000 : 7500), 0) + return route.fulfill({ json: { data: { code: 'SERTAO10', subtotal: money(subtotal), discount: money(subtotal / 10), total: money(subtotal * 0.9), requires_payment: true, lines: [] } } }) + } + return route.fulfill({ status: 404, json: {} }) + }) + await page.route('**/api/v1/checkout/editions/ed-a/orders**', async (route) => { + const request = route.request() + const path = new URL(request.url()).pathname.replace('/api/v1/checkout/editions/ed-a/orders', '') + calls.push({ method: request.method(), path, body: request.postDataJSON?.() ?? null, headers: request.headers() }) + if (request.method() === 'POST' && path === '') { + if (options.placeError) return route.fulfill({ status: 422, json: { code: 'validation_error', message: 'x', errors: options.placeError } }) + const body = request.postDataJSON() as { buyer: { name: string, email: string }, coupon: string | null, items: Array<{ ticket_type_id: string, attendees: Array<{ name: string, email: string }> }> } + const items = body.items.flatMap((item) => item.attendees.map((attendee, index) => ({ + id: `i-${item.ticket_type_id}-${index}`, ticket_type_id: item.ticket_type_id, ticket_type_name: item.ticket_type_id === 't-1' ? 'Inteira' : 'Meia', batch_name: '1º lote', + unit_price: money(item.ticket_type_id === 't-1' ? 15000 : 7500), discount: money(0), fee: money(0), total: money(0), attendee: { name: attendee.name, email: attendee.email }, + }))) + const subtotal = items.reduce((sum, item) => sum + item.unit_price.amount, 0) + const discount = body.coupon ? subtotal / 10 : 0 + const fee = Math.round((subtotal - discount) * 0.0399) + order = { + id: 'o-1', number: 42, status: options.orderStatus ?? 'created', status_label: 'Criado', buyer: { ...body.buyer, document: '***.982.247-**' }, + subtotal: money(subtotal), discount: money(discount), fee: money(fee), total: money(subtotal - discount + fee), refunded: money(0), gateway_fee: money(0), requires_payment: true, + coupon_code: body.coupon, payment_account_id: 'acc-1', expires_at: new Date(Date.now() + (options.expiresInSeconds ?? 1800) * 1000).toISOString(), paid_at: null, created_at: new Date().toISOString(), items, + } + return route.fulfill({ status: 201, json: { data: { ...order, access_token: 'tok-1' } } }) + } + if (request.headers()['x-order-token'] !== 'tok-1' || !order) return route.fulfill({ status: 404, json: { code: 'not_found', message: 'x' } }) + if (path === '/o-1/cancel') { + order = { ...order, status: 'cancelled', status_label: 'Cancelado' } + return route.fulfill({ json: { data: order } }) + } + return route.fulfill({ json: { data: order } }) + }) + return calls +} + +async function fillAndReserve(page: Page) { + await page.getByLabel('Quantidade de Inteira').selectOption('1') + await page.getByRole('button', { name: 'Continuar' }).click() + const buyer = page.getByRole('group', { name: 'Quem paga' }) + await buyer.getByLabel('Nome completo').fill('Ada Lovelace') + await buyer.getByLabel('E-mail').fill('ada@x.dev') + await buyer.getByLabel('CPF').fill('52998224725') + const first = page.getByRole('group', { name: 'Ingresso 1 · Inteira' }) + await first.getByRole('button', { name: 'Usar os dados de quem paga' }).click() + await first.getByLabel('Tamanho da camiseta').selectOption('M') + await page.getByRole('button', { name: 'Reservar e ir para o pagamento' }).click() +} + +test.describe('Checkout: escolha e dados', () => { + test('escolhe, aplica cupom, preenche quem vai e reserva; o pedido mostra a contagem e as taxas', async ({ page, goto }) => { + const calls = await mockApi(page) + await goto('/ingressos', { waitUntil: 'hydration' }) + + await expect(page.getByTestId('ticket-t-1')).toContainText('Restam 12') + await expect(page.getByTestId('ticket-t-3')).toContainText('2º lote abre em') + await expect(page.getByLabel('Quantidade de Estudante')).toHaveCount(0) + + await page.getByLabel('Quantidade de Inteira').selectOption('1') + await page.getByLabel('Quantidade de Meia').selectOption('1') + await page.getByLabel('Cupom de desconto').fill('errado') + await page.getByRole('button', { name: 'Aplicar' }).click() + await expect(page.locator('#checkout-coupon-status')).toHaveText('Cupom não encontrado.') + await page.getByLabel('Cupom de desconto').fill('sertao10') + await page.getByRole('button', { name: 'Aplicar' }).click() + await expect(page.locator('#checkout-coupon-status')).toContainText('Cupom SERTAO10 aplicado') + await expect(page.getByTestId('summary-total')).toHaveText(/R\$\s202,50/) + await expect(page.getByTestId('order-summary')).toContainText('calculada ao reservar') + + await page.getByRole('button', { name: 'Continuar' }).click() + await expect(page.getByRole('heading', { name: 'Ingressos', level: 1 })).toBeFocused() + const buyer = page.getByRole('group', { name: 'Quem paga' }) + await buyer.getByLabel('Nome completo').fill('Ada Lovelace') + await buyer.getByLabel('E-mail').fill('ada@x.dev') + await buyer.getByLabel('CPF').fill('52998224725') + await expect(buyer.getByLabel('CPF')).toHaveValue('529.982.247-25') + const first = page.getByRole('group', { name: 'Ingresso 1 · Inteira' }) + await first.getByRole('button', { name: 'Usar os dados de quem paga' }).click() + await first.getByLabel('Tamanho da camiseta').selectOption('G') + const second = page.getByRole('group', { name: 'Ingresso 2 · Meia' }) + await second.getByLabel('Nome completo').fill('Grace Hopper') + await second.getByLabel('E-mail').fill('grace@x.dev') + await page.getByRole('button', { name: 'Reservar e ir para o pagamento' }).click() + + await expect(page).toHaveURL(/\/checkout\/pedido\/o-1$/) + await expect(page.getByRole('timer')).toHaveText(/^(29|30):\d{2}$/) + await expect(page.getByTestId('order-totals')).toContainText('Desconto (SERTAO10)') + await expect(page.getByTestId('order-totals')).toContainText(/Taxa de serviço\s*R\$\s8,08/) + await expect(page.getByTestId('order-totals')).toContainText(/Total\s*R\$\s210,58/) + + const placed = calls.find((call) => call.method === 'POST' && call.path === '')! + expect(placed.headers['idempotency-key']).toMatch(/.{8,}/) + expect(placed.body).toEqual({ + buyer: { name: 'Ada Lovelace', email: 'ada@x.dev', document: '529.982.247-25' }, + coupon: 'SERTAO10', + items: [ + { ticket_type_id: 't-1', attendees: [{ name: 'Ada Lovelace', email: 'ada@x.dev', answers: { camiseta: 'G' } }] }, + { ticket_type_id: 't-2', attendees: [{ name: 'Grace Hopper', email: 'grace@x.dev', answers: {} }] }, + ], + }) + }) + + test('campos com erro aparecem num resumo com links, e o erro do backend vai para o campo', async ({ page, goto }) => { + await mockApi(page, { placeError: { buyer_document: ['Informe o CPF de quem paga.'] } }) + await goto('/ingressos', { waitUntil: 'hydration' }) + await page.getByLabel('Quantidade de Inteira').selectOption('1') + await page.getByRole('button', { name: 'Continuar' }).click() + await page.getByRole('button', { name: 'Reservar e ir para o pagamento' }).click() + + const summary = page.getByTestId('checkout-errors') + await expect(summary).toBeFocused() + await expect(summary).toContainText('Falta corrigir 6 campos antes de reservar.') + await summary.getByRole('link', { name: 'Ingresso 1 · Inteira: Tamanho da camiseta' }).click() + await expect(page.getByRole('group', { name: 'Ingresso 1 · Inteira' }).getByLabel('Tamanho da camiseta')).toBeFocused() + + await page.getByRole('button', { name: 'Voltar para a escolha' }).click() + await fillAndReserve(page) + await expect(page.getByTestId('checkout-errors')).toContainText('Quem paga: CPF: Informe o CPF de quem paga.') + await expect(page).toHaveURL(/\/ingressos$/) + }) + + test('reserva expirada volta para a escolha com a mensagem e a escolha anterior', async ({ page, goto }) => { + await mockApi(page, { expiresInSeconds: 3 }) + await goto('/ingressos', { waitUntil: 'hydration' }) + await fillAndReserve(page) + + await expect(page.getByRole('timer')).toBeVisible() + await expect(page).toHaveURL(/\/ingressos\?reserva=expirada$/, { timeout: 10_000 }) + await expect(page.getByTestId('checkout-notice')).toHaveText('Sua reserva expirou e os ingressos voltaram para a venda. Escolha de novo para garantir os seus.') + await expect(page.getByLabel('Quantidade de Inteira')).toHaveValue('1') + }) + + test('desistir libera os ingressos e volta para a escolha', async ({ page, goto }) => { + const calls = await mockApi(page) + await goto('/ingressos', { waitUntil: 'hydration' }) + await fillAndReserve(page) + await page.getByRole('button', { name: 'Desistir e liberar os ingressos' }).click() + await page.getByRole('group', { name: /Desistir da reserva/ }).getByRole('button', { name: 'Desistir e liberar os ingressos' }).click() + + await expect(page).toHaveURL(/\/ingressos\?reserva=cancelada$/) + await expect(page.getByTestId('checkout-notice')).toContainText('Você desistiu da reserva') + expect(calls.some((call) => call.path === '/o-1/cancel')).toBe(true) + }) + + test('só com teclado em 360 px, sem rolagem lateral', async ({ page, goto }) => { + await page.setViewportSize({ width: 360, height: 740 }) + await mockApi(page) + await goto('/ingressos', { waitUntil: 'hydration' }) + const noSideScroll = () => page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth) + expect(await noSideScroll()).toBe(true) + + await page.getByLabel('Quantidade de Inteira').focus() + await page.keyboard.press('1') + await expect(page.getByLabel('Quantidade de Inteira')).toHaveValue('1') + await page.getByRole('button', { name: 'Continuar' }).focus() + await page.keyboard.press('Enter') + await expect(page.getByRole('heading', { name: 'Ingressos', level: 1 })).toBeFocused() + expect(await noSideScroll()).toBe(true) + + const typeInto = async (label: string, text: string) => { + while (!(await page.evaluate((name) => document.activeElement?.id !== '' && document.querySelector(`label[for="${document.activeElement?.id}"]`)?.textContent?.trim().startsWith(name), label))) { + await page.keyboard.press('Tab') + } + await page.keyboard.type(text) + } + await typeInto('Nome completo', 'Ada Lovelace') + await typeInto('E-mail', 'ada@x.dev') + await typeInto('CPF', '52998224725') + await page.keyboard.press('Tab') + await expect(page.getByRole('button', { name: 'Usar os dados de quem paga' })).toBeFocused() + await page.keyboard.press('Enter') + await page.keyboard.press('Tab') + await page.keyboard.press('Tab') + await page.keyboard.press('Tab') + await expect(page.getByLabel('Tamanho da camiseta')).toBeFocused() + await page.keyboard.press('M') + await expect(page.getByLabel('Tamanho da camiseta')).toHaveValue('M') + await page.keyboard.press('Tab') + await expect(page.getByRole('button', { name: 'Reservar e ir para o pagamento' })).toBeFocused() + await page.keyboard.press('Enter') + + await expect(page).toHaveURL(/\/checkout\/pedido\/o-1$/) + await expect(page.getByRole('timer')).toBeVisible() + expect(await noSideScroll()).toBe(true) + }) +}) diff --git a/front-public/nuxt.config.ts b/front-public/nuxt.config.ts index c13a983..a21685f 100644 --- a/front-public/nuxt.config.ts +++ b/front-public/nuxt.config.ts @@ -20,6 +20,7 @@ export default defineNuxtConfig({ '/conta/**': { ssr: false }, '/ingressos/**': { ssr: false }, '/pedidos/**': { ssr: false }, + '/checkout/**': { ssr: false }, '/**': { headers: { 'Cache-Control': 'private, no-store' } }, }, vite: { diff --git a/front-public/shared/edition/index.test.ts b/front-public/shared/edition/index.test.ts index 0d54d62..f07df09 100644 --- a/front-public/shared/edition/index.test.ts +++ b/front-public/shared/edition/index.test.ts @@ -28,6 +28,8 @@ describe('route', () => { expect(route(external, '/programacao')).toMatchObject({ kind: 'redirect' }) expect(route(external, '/cfp')).toEqual({ kind: 'render' }) expect(route(external, '/palestrante/propostas/abc')).toEqual({ kind: 'render' }) + expect(route(external, '/ingressos')).toEqual({ kind: 'render' }) + expect(route(external, '/checkout/pedido/abc')).toEqual({ kind: 'render' }) }) it('no site da plataforma, renderiza tudo', () => { diff --git a/front-public/shared/edition/index.ts b/front-public/shared/edition/index.ts index eddc263..3579b26 100644 --- a/front-public/shared/edition/index.ts +++ b/front-public/shared/edition/index.ts @@ -17,7 +17,7 @@ export interface ResolvedEdition { theme: EditionTheme | null } -export const AREA_PREFIXES = ['/cfp', '/palestrante', '/entrar', '/login', '/conta', '/ingressos', '/pedidos', '/redefinir-senha'] +export const AREA_PREFIXES = ['/cfp', '/palestrante', '/entrar', '/login', '/conta', '/ingressos', '/pedidos', '/checkout', '/redefinir-senha'] const TOKEN_NAMES: Record = { support: 'terra' } const COLOR = /^#[0-9a-fA-F]{6}$/