From 9aa183b5d6215bfcbed8dda976c2f5472a6b8446 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Tue, 13 Oct 2026 19:01:05 -0300 Subject: [PATCH 01/60] docs: define no-Calendly email scheduling flow --- ...endamento-sem-calendly-por-email-design.md | 236 ++++++++++++++++++ 1 file changed, 236 insertions(+) create mode 100644 docs/superpowers/specs/2026-10-13-agendamento-sem-calendly-por-email-design.md diff --git a/docs/superpowers/specs/2026-10-13-agendamento-sem-calendly-por-email-design.md b/docs/superpowers/specs/2026-10-13-agendamento-sem-calendly-por-email-design.md new file mode 100644 index 0000000..d546c06 --- /dev/null +++ b/docs/superpowers/specs/2026-10-13-agendamento-sem-calendly-por-email-design.md @@ -0,0 +1,236 @@ +# Agendamento sem Calendly por e-mail + +## Contexto e problema + +Quando o especialista não tem uma integração ativa com o Calendly, a página de produto oferece hoje dois fluxos incompatíveis: + +- o fluxo por e-mail cria um agendamento `PENDING/EMAIL` sem data e abre um `mailto:`; +- o fluxo pela plataforma coleta data e hora, mas cria um agendamento `SCHEDULED/PLATFORM`, pulando a confirmação do especialista e sem abrir o cliente de e-mail. + +O backend reforça essa divisão ao rejeitar data em agendamentos `EMAIL`. Além disso, o especialista não vê o telefone do cliente enquanto o pedido está pendente, a disponibilidade de Calendly é inferida de fontes diferentes no frontend e no backend, e existem respostas públicas que expõem dados pessoais além do necessário. + +## Objetivo + +Unificar o caso sem Calendly em um único pedido de reunião: o cliente propõe data e hora, o sistema registra o pedido pendente, oferece a composição de um e-mail ao especialista e mantém o processo rastreável. O especialista recebe os contatos do cliente, podendo confirmar a sugestão ou alterar a data e confirmar. + +## Fora de escopo + +- enviar e-mail pelo servidor ou garantir que o usuário concluiu o envio no aplicativo externo; +- sincronizar reuniões por e-mail com calendários externos; +- criar novos estados ou novas tabelas para o agendamento; +- implementar expiração automática dos pedidos pendentes; +- alterar o fluxo já conectado ao Calendly, exceto por tornar a detecção da conexão consistente; +- refatorações sem relação direta com privacidade ou com esse fluxo. + +## Decisão de produto + +Na ausência de Calendly, haverá uma única ação, **Solicitar reunião**. Ela abre o seletor de data e hora e, após a confirmação do cliente: + +1. cria atomicamente o `Appointment` com `status=PENDING`, `scheduling_method=EMAIL` e `appointment_datetime` preenchido; +2. cria o `Process` associado no estágio `SCHEDULING`; +3. apresenta o sucesso dentro da aplicação e tenta abrir o cliente padrão com um `mailto:`; +4. mantém alternativas visíveis para abrir novamente o cliente padrão, abrir o Gmail Web, copiar o e-mail do especialista e acompanhar o processo, inclusive após recarregar ou revisitar a página. + +O horário pendente é uma proposta, não uma reserva. Ele não bloqueia o horário do especialista. Somente a confirmação transforma a proposta em compromisso e deve validar conflitos novamente. + +## Fluxo do cliente + +### Especialista com Calendly ativo + +O comportamento permanece o atual: a interface oferece o fluxo Calendly e o backend só aceita `scheduling_method=CALENDLY` se a capacidade estiver ativa para o especialista. + +### Especialista sem Calendly ativo + +1. O cliente autenticado seleciona um produto e aciona **Solicitar reunião**. +2. O modal exige uma data/hora futura e exibe o fuso horário local usado na apresentação. +3. O frontend envia a data em ISO 8601 para `POST /appointments/pending` com `scheduling_method=EMAIL`. +4. Após `201`, a página mostra o estado de sucesso antes de iniciar a navegação externa. O painel também é reconstruído após reload ou revisita quando a consulta autenticada encontra o próprio pedido `PENDING/EMAIL` com data. +5. O e-mail pré-preenchido contém: + - destinatário: e-mail profissional do especialista; + - assunto: interesse no produto e nome do produto; + - corpo: nome do cliente, produto, data/hora sugerida com fuso e um texto editável de interesse. +6. A tentativa automática de `mailto:` é complementar e ocorre no máximo uma vez para o appointment recém-criado, controlada pelo ID em memória/sessão. Ela nunca se repete por rerender, reload, retorno do histórico ou recuperação de duplicidade. O pedido criado continua válido se o navegador bloquear a navegação ou se não houver aplicativo padrão configurado. +7. A tela mantém as ações de fallback **Abrir aplicativo de e-mail**, **Abrir no Gmail**, **Copiar e-mail** e **Acompanhar processo**. O Gmail usa `https://mail.google.com/mail/?view=cm&fs=1...` em nova aba com `noopener noreferrer`; não há tentativa de detectar o provedor do usuário. + +Erros de criação nunca abrem o cliente de e-mail. Um `409` só é tratado como pedido já existente quando o backend devolver o código de erro específico desse caso. Nesse caso, a resposta autorizada traz o snapshot mínimo do próprio pedido e a UI recupera o painel de sucesso, sem autoabrir o e-mail. Um processo ativo de outro método ou estágio apenas orienta o cliente a acompanhá-lo. Conflitos genéricos continuam sendo exibidos como erro. + +O assunto e o corpo são sugestões editáveis somente no compositor externo; a aplicação não captura nem persiste esse texto. Um helper puro monta os links, remove CR/LF de destinatário e assunto, limita o comprimento dos valores e aplica percent-encoding separado. O corpo preserva as quebras de linha intencionais. + +## Fluxo do especialista + +No card do processo em `SCHEDULING`, o especialista atribuído vê: + +- data e hora propostas pelo cliente; +- e-mail do cliente; +- telefone do cliente, quando preenchido; +- atalho para WhatsApp somente quando o telefone puder ser normalizado para um número válido; +- ação **Confirmar horário**; +- ação **Alterar e confirmar** com seletor de data/hora. + +As duas ações usam o endpoint canônico de confirmação do processo. Confirmar a sugestão envia a própria `appointment_datetime`; alterar e confirmar envia o novo horário. Em ambos os casos, o `Appointment` é atualizado para `SCHEDULED`, enquanto o `Process` permanece em `SCHEDULING`. Esse estado é necessário para iniciar ou entrar na reunião; o processo só avança no fluxo já existente após a conversa/reunião e a associação de produto quando ela for exigida. + +A alteração feita antes da primeira confirmação não consome nem preenche os campos de uma remarcação posterior. Os campos de auditoria de remarcação passam a ser usados apenas depois de um horário já confirmado. Se a data for alterada na confirmação, a proposta original e o horário confirmado são anexados ao histórico/notas do processo; a UI do cliente passa a mostrar o horário efetivamente confirmado. + +## Modelo de dados e regras + +Não haverá migração. O modelo existente representa o fluxo: + +- `Appointment.status = PENDING`; +- `Appointment.scheduling_method = EMAIL`; +- `Appointment.appointment_datetime = horário proposto`; +- `Process.status = SCHEDULING`. + +Para novos pedidos `EMAIL` com produto, `appointment_datetime` é obrigatório, deve ser uma data ISO válida e futura. Em consultoria sem produto ele permanece opcional e deve ser informado pelo especialista na confirmação. Registros legados `EMAIL` sem data continuam legíveis e aparecem ao especialista como pedido sem horário definido, exigindo **Alterar e confirmar**. + +Um único helper de domínio define compromissos que ocupam agenda e é usado na criação direta, confirmação, callback Calendly e reagendamento. Pedidos `PENDING/EMAIL` não entram nesse predicado porque são propostas não confirmadas. Continuam ocupando agenda: + +- agendamentos `SCHEDULED`; +- agendamentos `PENDING/CALENDLY` com `calendly_sync_status=SYNCED` e horário; +- registros legados pendentes com horário e sem método definido, preservando compatibilidade. + +Na confirmação, o backend adquire o lock já usado para a agenda do especialista, relê o compromisso dentro da transação, valida conflito para o horário escolhido e só então atualiza agendamento e processo. Respostas de conflito não retornam IDs de clientes, processos ou agendamentos concorrentes. + +O campo existente `pending_expires_at` continua sendo preenchido, mas a expiração automática e seus efeitos sobre `Appointment` e `Process` permanecem fora desta entrega porque não existe estado de processo expirado. O risco conhecido é que pedidos abandonados continuam ativos até cancelamento/recusa. O plano não deve sugerir que sete dias já sejam aplicados como regra de negócio. + +## Contratos de API + +### Criar pedido pendente + +`POST /appointments/pending` + +- `EMAIL` com produto: exige `appointment_datetime` válido e futuro; consultoria sem produto preserva o campo opcional; +- `CALENDLY`: exige que o especialista possua capacidade Calendly ativa; +- `EMAIL` com produto é aceito somente quando a capacidade Calendly estiver inativa; `CALENDLY` é aceito somente quando ela estiver ativa; +- `CALENDLY` rejeita `appointment_datetime` enviado pelo cliente; apenas callback/webhook sincronizado pode preenchê-lo; +- a criação do agendamento e do processo é atômica; +- a resposta retorna o appointment e seu `process_id`, ambos pertencentes ao cliente autenticado, sem dados de terceiros. + +O caminho direto `POST /appointments`, hoje usado para criar `SCHEDULED/PLATFORM`, deixa de aceitar esse cenário para cliente e produto. Um cliente HTTP sem Calendly deve usar o pedido pendente `EMAIL`; ele não pode contornar a confirmação do especialista criando um compromisso direto. + +### Confirmar pelo processo + +`POST /processes/:processId/confirm-appointment` + +- permitido somente ao especialista atribuído; administradores podem inspecionar conforme as permissões existentes, mas não confirmam em nome dele; +- aceita o horário sugerido ou um novo horário futuro; +- confirma o appointment sob lock e mantém o processo em `SCHEDULING`; +- não registra a primeira alteração como remarcação. + +O endpoint alternativo de confirmação direta de appointment não será usado pelo frontend desse fluxo, evitando semânticas diferentes para o avanço do processo. + +### Consultar pedido existente + +`GET /appointments/check` é uma consulta de pedido existente, não de disponibilidade de horário, aceita somente `CUSTOMER` e deixa de receber `client_id`. O cliente vem exclusivamente do JWT e a consulta aceita apenas especialista e produto. A resposta discriminada é: + +- `{ exists: false }`; ou +- `{ exists: true, appointment_id, process_id, appointment_status, scheduling_method, appointment_datetime }` para um appointment pertencente ao próprio cliente. + +Ela não contém nomes, e-mails, telefones nem IDs de outros clientes. Esses dados são suficientes para a página escolher entre o CTA, o aviso de processo existente e a recuperação do painel de e-mail. + +### Projeção pública do especialista + +A página de produto usa `GET /specialists/:id/public-profile`, uma projeção dedicada com apenas os campos necessários para exibição e contato comercial. Antes de endurecer o endpoint genérico, seus consumidores de exibição de especialista, incluindo o modal de abertura de processo, migram para essa projeção. As listagens públicas `GET /specialists` e `GET /specialists/grouped-by-category` reutilizam o mesmo serializer seguro e deixam de selecionar CPF/CNPJ e RG. `GET /users/:id`, que hoje pode devolver CPF, RG, telefone e estado civil, passa a aceitar somente o próprio usuário ou `ADMIN`; os demais recebem `403`. + +Como a remoção da URL do Calendly passa por `PATCH /users/:id`, esse endpoint também deve validar o alvo: somente o próprio usuário ou um `ADMIN` pode alterá-lo. Além disso, somente usuários `SPECIALIST` podem definir `calendly_url`; `null` continua permitido para remover o valor. Conhecer o UUID de outra conta não autoriza a edição. A correção e o teste de IDOR fazem parte desta entrega porque, sem ela, qualquer usuário autenticado poderia modificar a configuração de Calendly e outros dados do perfil de terceiros. + +## Fonte de verdade do Calendly + +A aplicação terá um único campo derivado no backend, `calendly_scheduling_available`. Para este fluxo ele é `true` somente quando existe uma URL HTTPS cujo hostname pertence ao Calendly **e** uma `CalendlyConnection` com `is_active=true`. Token de acesso expirado não desativa a capacidade enquanto o refresh continua válido; uma falha definitiva como `invalid_grant` marca a conexão como inativa. + +O backend devolve essa capacidade na projeção usada pela página do produto, e o frontend escolhe o fluxo com base nela. O backend repete a validação ao criar o pedido para impedir bypass pelo cliente HTTP. + +O callback OAuth persiste também a `scheduling_url` devolvida pelo Calendly como `calendly_url`, para que uma conexão válida tenha o link necessário ao popup. Ao desconectar, a conexão é desativada e URL/URIs derivados são limpos na mesma transação. A edição de perfil envia `null` ao apagar a URL, em vez de omitir o campo e preservar o valor antigo. + +O backend aplica a exigência de data ao `EMAIL` relacionado a produto (`product_id` presente). A consultoria sem produto mantém o contrato atual de `PENDING/EMAIL` sem data, evitando ampliar esta correção para um segundo fluxo de produto. Ela continua exigindo definição do horário pelo especialista ao confirmar. + +## Privacidade e autorização dos contatos + +Enquanto o pedido `PENDING/EMAIL` estiver no estágio `SCHEDULING`, somente o especialista atribuído pode ver e-mail e telefone do cliente. Essa projeção é aplicada tanto na listagem `GET /processes/specialist/:specialistId` quanto no detalhe `GET /processes/:id`, sempre validando que o usuário autenticado é o especialista da rota/processo. Ela continua disponível ao especialista atribuído durante `SCHEDULED`, `COMPLETED` e no histórico do processo. As listagens de cliente, `OFFICE`, `CONSULTANT`, outros especialistas e respostas públicas não recebem esses contatos por causa desse estado; `ADMIN` só os recebe nos endpoints administrativos que já exigem esse papel, nunca por herança de uma projeção pública. + +O cliente não passa a ver o telefone privado do especialista antes da confirmação. O e-mail comercial necessário para compor a mensagem vem da projeção segura do produto/especialista. Esse e-mail comercial é intencionalmente público e, portanto, sujeito a coleta automatizada; a projeção pública fica limitada a ID, nome comercial, especialidade, e-mail comercial, URL de agendamento e o booleano de capacidade, nunca documentos, telefone pessoal, estado civil, tokens, URIs OAuth ou detalhes da conexão. + +## Componentes de frontend + +- `ProductPage`: escolhe Calendly ou solicitação por e-mail usando a capacidade devolvida pelo backend; remove a bifurcação atual entre `EMAIL` sem data e `PLATFORM` já confirmado. +- `AppointmentDateTimeModal`: coleta a proposta futura e aceita `initialValue`. Na ação **Alterar e confirmar**, converte o ISO existente para `datetime-local` no fuso do navegador. Se o campo não for editado, envia o ISO original e preserva exatamente o instante; se o usuário editar uma hora local ambígua em transição de horário de verão, vale o offset escolhido pelo navegador. +- componente dedicado de sucesso do pedido: concentra `mailto:`, Gmail, cópia do endereço e navegação ao processo, mantendo a página de produto focada na orquestração. +- `ProcessCard`: separa explicitamente **Confirmar horário** de **Alterar e confirmar** e exibe os contatos autorizados. +- serviço de appointments: representa o contrato `PENDING/EMAIL` com data obrigatória e não chama a criação `PLATFORM` nesse cenário. +- perfil: permite remover de fato a URL do Calendly. + +## Tratamento de erros + +- data ausente, inválida ou passada: `400` com mensagem específica; +- `CALENDLY` solicitado sem capacidade ativa: `409/CALENDLY_UNAVAILABLE` e orientação para usar o fluxo por e-mail; +- `EMAIL` com produto solicitado quando há capacidade Calendly ativa: `409/EMAIL_FLOW_UNAVAILABLE`; +- pedido ativo duplicado: `409/ACTIVE_PROCESS_EXISTS`, devolvendo `process_id` e o snapshot mínimo somente depois de comprovar que o cliente autenticado é o dono; +- conflito descoberto na confirmação: `409` sem PII e com orientação para escolher outro horário; +- falha ao criar pedido/processo: transação revertida e nenhuma tentativa de abrir e-mail; +- falha ao abrir aplicativo externo: pedido permanece criado e fallbacks continuam disponíveis; +- telefone ausente: o atalho de telefone/WhatsApp não é exibido; telefone preenchido mas não normalizável: o valor original é exibido como texto, sem gerar link `wa.me` incorreto. + +Ao receber `409` em **Confirmar horário**, o frontend abre e mantém o modal **Alterar e confirmar**, pré-preenchido com a proposta e com erro inline associado ao campo. Os botões ficam desabilitados e com estado busy durante a requisição para impedir dupla submissão. + +O backend recebe e armazena um instante UTC (`toISOString()`). A interface mostra o fuso IANA do navegador, e o corpo do e-mail formata o instante nesse fuso, por exemplo `20/10/2026 14:30 (America/Sao_Paulo)`. O fuso não é persistido separadamente. + +Para WhatsApp, o helper remove caracteres não numéricos; números brasileiros com 10 ou 11 dígitos recebem prefixo `55`, e números com 12 ou 13 dígitos iniciados por `55` são aceitos. Os demais não geram link. O link usa `https://wa.me/` em nova aba com `noopener noreferrer`, mantendo o número original visível para o especialista. + +O painel recebe foco no título após a criação, anuncia sucesso com `role=status`/`aria-live=polite` e erros com `role=alert`. O modal preserva foco, rótulos, `aria-describedby` para erros e devolve o foco ao acionador. Falha ou indisponibilidade do clipboard mantém o endereço selecionável e anuncia que a cópia não ocorreu. + +## Estratégia de testes + +### Backend + +- TDD para exigir horário futuro no `PENDING/EMAIL` com produto, preservar consultoria sem produto e aceitar registros legados na leitura; +- teste da transação de criação `Appointment + Process`; +- teste da matriz de capacidade Calendly, incluindo URL/domínio, OAuth ativo/inativo, disconnect, data proibida no `CALENDLY` e rejeição recíproca de método; +- teste de bypass comprovando que o cliente não cria `SCHEDULED/PLATFORM` por `POST /appointments`; +- teste de confirmação no mesmo horário e em horário alterado; +- testes concorrentes PostgreSQL: duas propostas diferentes para o mesmo especialista/horário são aceitas, confirmações simultâneas deixam exatamente uma `SCHEDULED`, duplo clique não duplica histórico e especialistas diferentes podem usar o mesmo horário; +- teste de que o predicado central ignora propostas `PENDING/EMAIL` em todos os chamadores; +- testes de autorização e projeção de contatos em lista e detalhe; +- teste de IDOR em `PATCH /users/:id`, permitindo somente o próprio usuário ou `ADMIN`; +- teste de que não especialista não altera `calendly_url`; +- testes de não exposição de PII na consulta de pedido, conflitos e perfil público/privado. + +### Frontend + +- TDD do único CTA e do envio de `appointment_datetime` no fluxo sem Calendly; +- teste de que o e-mail só é aberto após resposta de sucesso e no máximo uma vez por appointment; +- teste das alternativas de e-mail e recuperação após reload/duplicidade; +- teste do helper de composição com acentos, `&`, `?`, `#`, CR/LF e valores longos; +- teste do tratamento específico de duplicidade sem confundir outros `409`; +- teste das ações distintas de confirmar e alterar/confirmar, incluindo valor inicial, preservação do ISO quando inalterado, escolha do navegador em horário DST editado e conflito inline; +- teste de telefone ausente ou inválido e da remoção da URL do Calendly. + +### E2E local + +Com a stack local, dois produtos/processos e três identidades — cliente com telefone, especialista atribuído e outro usuário/especialista — em contextos de navegador independentes: + +1. publicar ou selecionar produto de especialista sem Calendly; +2. como cliente, escolher uma data futura e criar o pedido; +3. verificar a URL `mailto:`/Gmail gerada, sem afirmar que um e-mail externo foi enviado; +4. verificar processo pendente e persistência da proposta; +5. como especialista atribuído, verificar e-mail, telefone e WhatsApp do cliente; +6. alterar e confirmar o horário; +7. verificar o agendamento `SCHEDULED`, o processo ainda em `SCHEDULING`, os controles da reunião e a ausência de consumo de remarcação; +8. repetir o caminho confirmando a sugestão sem alteração; +9. validar que usuário não atribuído não recebe os contatos. + +O E2E inspeciona o `href` de `mailto:` sem navegar para um aplicativo externo. O caminho Gmail só é aberto em aba controlável quando houver sessão apropriada. O cenário crítico é repetido em viewport móvel e com navegação por teclado. + +## Critérios de aceite + +- sem Calendly, o cliente sempre informa data e hora antes de criar o pedido; +- a criação resulta em `PENDING/EMAIL`, não em `SCHEDULED/PLATFORM`; +- o cliente consegue iniciar um e-mail com destinatário, assunto e corpo pré-preenchidos e possui fallbacks persistentes; +- o especialista atribuído vê a proposta, o e-mail e o WhatsApp/telefone válido do cliente; +- o especialista pode confirmar ou alterar e confirmar; +- somente a confirmação reserva o horário; o processo permanece em `SCHEDULING` para permitir a reunião; +- o backend impede bypass do tipo de integração e confirma sob lock; +- erros não disparam composição de e-mail indevidamente; +- endpoints tocados pelo fluxo não expõem dados pessoais a usuários não autorizados; +- a edição de perfil rejeita tentativas de alterar outro usuário sem papel `ADMIN`; +- recarregar ou revisitar a página recupera os fallbacks do próprio pedido sem repetir a abertura automática do e-mail; +- a consultoria sem produto continua podendo criar pedido `PENDING/EMAIL` sem data; +- testes automatizados e o E2E local cobrem os dois lados do fluxo. From b1a7d88fd5dfded3e275e43140c1c811668ebe93 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 07:32:30 -0300 Subject: [PATCH 02/60] docs: plan no-Calendly email scheduling implementation --- ...0-14-agendamento-sem-calendly-por-email.md | 702 ++++++++++++++++++ 1 file changed, 702 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-14-agendamento-sem-calendly-por-email.md diff --git a/docs/superpowers/plans/2026-10-14-agendamento-sem-calendly-por-email.md b/docs/superpowers/plans/2026-10-14-agendamento-sem-calendly-por-email.md new file mode 100644 index 0000000..eafb16b --- /dev/null +++ b/docs/superpowers/plans/2026-10-14-agendamento-sem-calendly-por-email.md @@ -0,0 +1,702 @@ +# Agendamento sem Calendly por e-mail — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Entregar o pedido de reunião por e-mail com data proposta, composição externa de mensagem, confirmação do especialista, contatos autorizados e fechamento dos vazamentos/atalhos descobertos. + +**Architecture:** O backend será a fonte de verdade para capacidade Calendly, autorização, deduplicação e ocupação de agenda. O frontend consumirá contratos discriminados, usará helpers puros para links externos e manterá um painel recuperável após a criação. A confirmação canônica continuará em `ProcessesService.confirmAppointment`, mantendo o processo em `SCHEDULING`. + +**Tech Stack:** NestJS, Prisma/PostgreSQL, Jest, React, TypeScript, Vite, Vitest/Testing Library e navegador local controlado. + +## Global Constraints + +- Não criar migration nem alterar `backend/prisma/schema.prisma`. +- Todo shell do repositório usa prefixo `rtk`. +- Jest roda com `--runInBand` ou no máximo `--maxWorkers=2`; Vitest usa no máximo dois forks. +- `PENDING/EMAIL` com produto é proposta e não ocupa agenda; consultoria sem produto continua aceitando EMAIL sem data. +- Confirmação muda apenas `Appointment` para `SCHEDULED`; `Process` permanece `SCHEDULING`. +- `calendly_scheduling_available` só é verdadeiro com URL HTTPS do domínio Calendly e conexão OAuth ativa. +- E-mail comercial do especialista é público por decisão de produto; documentos, telefone pessoal e dados OAuth nunca são públicos. +- Ações externas só ocorrem depois de persistência confirmada; o navegador não comprova envio de e-mail. +- `pending_expires_at` continua apenas como metadado; esta entrega não implementa expiração automática. + +--- + +### Task 1: Capacidade Calendly e projeção pública segura + +**Files:** +- Create: `backend/src/shared/utils/calendly-scheduling-capability.ts` +- Create: `backend/src/shared/utils/calendly-scheduling-capability.spec.ts` +- Create: `backend/src/features/specialists/specialists.controller.spec.ts` +- Modify: `backend/src/features/appointments/calendly-integration.service.ts` +- Modify: `backend/src/features/appointments/calendly-integration.service.spec.ts` +- Modify: `backend/src/features/specialists/specialists.controller.ts` +- Modify: `backend/src/features/specialists/specialists.service.ts` +- Modify: `backend/src/features/specialists/specialists.service.spec.ts` + +**Interfaces:** +- Produces: `isCalendlySchedulingAvailable(input: { calendlyUrl: string | null; connectionActive: boolean }): boolean`. +- Produces: `GET /specialists/:id/public-profile` e o tipo de resposta `PublicSpecialistProfile` com allowlist exata. +- Consumes: `CalendlyConnection.is_active` e `me.resource.scheduling_url` do callback OAuth. + +- [ ] **Step 1: Write failing capability and projection tests** + +```ts +expect(isCalendlySchedulingAvailable({ + calendlyUrl: 'https://calendly.com/especialista/reuniao', + connectionActive: true, +})).toBe(true); + +for (const calendlyUrl of [ + 'http://calendly.com/a', + 'https://evilcalendly.com/a', + 'https://calendly.com.evil.test/a', + 'https://calendly.com@evil.test/a', + 'not-a-url', +]) { + expect(isCalendlySchedulingAvailable({ calendlyUrl, connectionActive: true })).toBe(false); +} + +expect(await service.findPublicProfile('specialist-1')).toEqual({ + id: 'specialist-1', + name: 'Ana', + surname: 'Silva', + email: 'ana@example.com', + speciality: 'CAR', + calendly_url: 'https://calendly.com/ana/reuniao', + calendly_scheduling_available: true, +}); +``` + +In the same RED phase, extend `calendly-integration.service.spec.ts` to assert that OAuth callback stores a validated `scheduling_url`, disconnect clears URL/URIs and deactivates the connection in one transaction, access-token expiry with successful refresh remains active, and `invalid_grant` persists `is_active=false` plus `last_error`. + +- [ ] **Step 2: Run focused tests and verify RED** + +Run: + +```bash +rtk npm --prefix backend test -- --runInBand src/shared/utils/calendly-scheduling-capability.spec.ts src/features/appointments/calendly-integration.service.spec.ts src/features/specialists/specialists.service.spec.ts src/features/specialists/specialists.controller.spec.ts +``` + +Expected: FAIL because the capability helper, public projection and route do not exist. + +- [ ] **Step 3: Implement the domain helper and safe serializer** + +```ts +export function isCalendlySchedulingAvailable(input: { + calendlyUrl: string | null; + connectionActive: boolean; +}): boolean { + if (!input.connectionActive || !input.calendlyUrl) return false; + try { + const url = new URL(input.calendlyUrl); + const host = url.hostname.toLowerCase(); + return url.protocol === 'https:' && + (host === 'calendly.com' || host.endsWith('.calendly.com')); + } catch { + return false; + } +} +``` + +Implement `findPublicProfile` with a Prisma `select` allowlisting only `id`, `name`, `surname`, `email`, `speciality`, `calendly_url` and `calendly_connection.is_active`. Declare `@Public()` and `@Get(':id/public-profile')` before `@Get(':id')`. Reuse the serializer in public specialist lists so CPF/CNPJ and RG are never selected. + +- [ ] **Step 4: Persist and clear Calendly state consistently** + +Update the OAuth callback to validate and store `me.resource.scheduling_url`. Update disconnect so one transaction sets `CalendlyConnection.is_active=false` and clears `calendly_url`, `calendly_user_uri` and `calendly_organization_uri`. Add tests for expired access token with valid refresh and for definitive `invalid_grant` deactivation. + +- [ ] **Step 5: Run tests and commit** + +```bash +rtk npm --prefix backend test -- --runInBand src/shared/utils/calendly-scheduling-capability.spec.ts src/features/appointments/calendly-integration.service.spec.ts src/features/specialists/specialists.service.spec.ts src/features/specialists/specialists.controller.spec.ts +rtk git add backend/src/shared/utils/calendly-scheduling-capability.ts backend/src/shared/utils/calendly-scheduling-capability.spec.ts backend/src/features/appointments backend/src/features/specialists +rtk git commit -m "feat: centralize Calendly scheduling capability" +``` + +Expected: all focused tests PASS. + +--- + +### Task 2: Autorizar perfil e impedir IDOR + +**Files:** +- Create: `backend/src/features/users/users.controller.spec.ts` +- Modify: `backend/src/features/users/users.controller.ts` +- Modify: `backend/src/features/users/users.service.ts` +- Modify: `backend/src/features/users/users.service.spec.ts` +- Modify: `backend/src/features/users/dto/update-user.dto.ts` +- Modify: `frontend/src/services/specialists.service.ts` +- Modify: `frontend/src/services/specialists.service.test.ts` +- Modify: `frontend/src/pages/catalog/ProductPage.tsx` +- Modify: `frontend/src/pages/catalog/ProductPage.test.tsx` +- Modify: `frontend/src/components/processes/StartProcessForClientModal.tsx` +- Create: `frontend/src/components/processes/StartProcessForClientModal.test.tsx` + +**Interfaces:** +- Produces: `GET /users/:id` e `PATCH /users/:id` autorizados para self ou `ADMIN`. +- Produces: `calendly_url?: string | null`; somente `SPECIALIST` pode definir valor não nulo. + +- [ ] **Step 1: Write controller authorization tests** + +```ts +await expect(controller.getById(targetId, { user: outsider })).rejects.toThrow(ForbiddenException); +await expect(controller.update(targetId, { name: 'X' }, { user: outsider })).rejects.toThrow(ForbiddenException); +expect(usersService.getById).not.toHaveBeenCalled(); +expect(usersService.update).not.toHaveBeenCalled(); + +await expect(controller.getById(self.id, { user: self })).resolves.toMatchObject({ success: true }); +await expect(controller.getById(targetId, { user: admin })).resolves.toMatchObject({ success: true }); +``` + +Also validate that a customer cannot submit `calendly_url`, while a specialist can set a valid Calendly URL or remove it with `null`. + +- [ ] **Step 2: Run tests and verify RED** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/users/users.controller.spec.ts src/features/users/users.service.spec.ts +``` + +Expected: FAIL because controller methods do not receive/request the authenticated actor and `null` is rejected by the DTO. + +- [ ] **Step 3: Implement fail-closed authorization before database access** + +```ts +private assertSelfOrAdmin(targetId: string, actor: UserEntity): void { + if (actor.id !== targetId && actor.role !== UserRole.ADMIN) { + throw new ForbiddenException('Acesso não autorizado'); + } +} +``` + +Remove `@Public()` from `GET /users/:id`, read `req.user`, call the guard before the service, and apply the same rule to PATCH. In the service reject a non-null `calendly_url` unless the target role is `SPECIALIST`; normalize empty/null removal to `null`. + +- [ ] **Step 4: Migrate public specialist consumers before hardening is committed** + +Add `getPublicSpecialistById(id)` to the specialist service using `/specialists/:id/public-profile`. Replace `getUserById` only in ProductPage and StartProcessForClientModal; ProfilePage continues using the authenticated self endpoint. Update their existing mocks without changing scheduling behavior yet. + +Before production changes, add `StartProcessForClientModal.test.tsx` asserting that specialist display loads through `getPublicSpecialistById` and never invokes `getUserById`. + +- [ ] **Step 5: Run tests and commit** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/users/users.controller.spec.ts src/features/users/users.service.spec.ts +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/services/specialists.service.test.ts src/pages/catalog/ProductPage.test.tsx src/components/processes/StartProcessForClientModal.test.tsx +rtk git add backend/src/features/users frontend/src/services/specialists.service.ts frontend/src/services/specialists.service.test.ts frontend/src/pages/catalog/ProductPage.tsx frontend/src/pages/catalog/ProductPage.test.tsx frontend/src/components/processes/StartProcessForClientModal.tsx frontend/src/components/processes/StartProcessForClientModal.test.tsx +rtk git commit -m "fix: authorize private user profile access" +``` + +Expected: tests PASS and outsider cases do not call Prisma/service. + +--- + +### Task 3: Contrato seguro de pedido pendente e consulta própria + +**Files:** +- Create: `backend/src/features/appointments/dto/check-existing-appointment.dto.ts` +- Create: `backend/src/features/appointments/appointments.controller.spec.ts` +- Create: `backend/src/features/appointments/appointment-schedule-lock.spec.ts` +- Modify: `backend/src/features/appointments/dto/create-pending-appointment.dto.ts` +- Modify: `backend/src/features/appointments/dto/index.ts` +- Modify: `backend/src/features/appointments/entities/appointment.response.ts` +- Modify: `backend/src/features/appointments/appointments.controller.ts` +- Modify: `backend/src/features/appointments/appointments.service.ts` +- Modify: `backend/src/features/appointments/appointments.service.spec.ts` +- Modify: `backend/src/features/appointments/appointment-schedule-lock.ts` +- Modify: `backend/src/features/processes/process-dedup-lock.ts` +- Modify: `backend/src/features/processes/process-dedup-lock.spec.ts` + +**Interfaces:** +- Consumes: `isCalendlySchedulingAvailable` from Task 1. +- Produces: `ExistingAppointmentCheck = { exists: false } | { exists: true; appointment_id; process_id; appointment_status; scheduling_method; appointment_datetime }`. +- Produces: successful pending creation response containing `process_id`. +- Produces: `409/CALENDLY_UNAVAILABLE`, `409/EMAIL_FLOW_UNAVAILABLE` and own-only `409/ACTIVE_PROCESS_EXISTS` snapshot at `error.details.existing_request`. The duplicate snapshot always has `process_id`; appointment fields are nullable because an active process may exist without an appointment. +- Produces: the shared occupation predicate before EMAIL requests can carry a datetime. + +- [ ] **Step 1: Write the schedule occupation matrix tests** + +Preserve the existing ±1-hour conflict window: + +```ts +expect(buildOccupiedScheduleWhere('s1', when)).toMatchObject({ + specialist_id: 's1', + appointment_datetime: { + gte: new Date(when.getTime() - 60 * 60 * 1000), + lte: new Date(when.getTime() + 60 * 60 * 1000), + }, + OR: [ + { status: StatusAgendamento.SCHEDULED }, + { + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + calendly_sync_status: CalendlySyncStatus.SYNCED, + }, + { status: StatusAgendamento.PENDING, scheduling_method: null }, + ], +}); +``` + +Test exact boundaries at -60 minutes, +60 minutes and one millisecond outside. Assert `PENDING/EMAIL` and unsynced `PENDING/CALENDLY` never match, and conflict errors contain no competing appointment/client/process IDs. + +- [ ] **Step 2: Run the predicate test and implement the shared builder** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/appointments/appointment-schedule-lock.spec.ts +``` + +Expected RED: the builder does not exist and the old query includes all PENDING records. Implement `buildOccupiedScheduleWhere` and make `assertSpecialistScheduleAvailable` consume it; rerun until PASS before changing EMAIL creation. + +- [ ] **Step 3: Write RED service, dedup and controller tests** + +```ts +await expect(service.createPending(productEmailWithoutDate, customer.id, UserRole.CUSTOMER)).rejects.toThrow(BadRequestException); +await expect(service.createPending(productEmailWithPastDate, customer.id, UserRole.CUSTOMER)).rejects.toThrow(BadRequestException); +await expect(service.createPending(consultancyEmailWithoutDate, customer.id, UserRole.CUSTOMER)).resolves.toBeDefined(); +await expect(service.createPending(calendlyWithClientDate, customer.id, UserRole.CUSTOMER)).rejects.toThrow(BadRequestException); + +expect(await controller.checkExisting(query, customerRequest)).toEqual({ + success: true, + message: 'Consulta realizada com sucesso', + data: { + exists: true, + appointment_id: 'appointment-1', + process_id: 'process-1', + appointment_status: 'PENDING', + scheduling_method: 'EMAIL', + appointment_datetime: proposedDate, + }, +}); +``` + +Freeze the duplicate response shape: + +```ts +expect((error as ConflictException).getResponse()).toEqual({ + success: false, + error: { + code: 'ACTIVE_PROCESS_EXISTS', + message: expect.any(String), + details: { + existing_request: { + appointment_id: null, + process_id: 'process-1', + appointment_status: null, + scheduling_method: null, + appointment_datetime: null, + }, + }, + }, +}); +``` + +Add a second case with an attached `PENDING/EMAIL` appointment asserting the same shape with non-null appointment fields, so ProductPage can recover the e-mail panel only for that owned case. + +Cover the reciprocal method/capability matrix, mismatched `client_id`, non-customer check calls, atomic rollback and direct `POST /appointments` PLATFORM bypass. + +- [ ] **Step 4: Run tests and verify RED** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/appointments/appointments.controller.spec.ts src/features/appointments/appointments.service.spec.ts src/features/processes/process-dedup-lock.spec.ts +``` + +Expected: FAIL on the current EMAIL datetime rejection, arbitrary `client_id`, full Appointment return and direct PLATFORM creation. + +- [ ] **Step 5: Implement DTOs and discriminated responses** + +```ts +export class CheckExistingAppointmentDto { + @IsUUID() specialist_id: string; + @IsEnum(ProductType) product_type: ProductType; + @IsUUID() product_id: string; +} + +export type ExistingAppointmentCheck = + | { exists: false } + | { + exists: true; + appointment_id: string; + process_id: string; + appointment_status: StatusAgendamento; + scheduling_method: AppointmentSchedulingMethod | null; + appointment_datetime: Date | null; + }; + +export interface ActiveProcessSnapshot { + process_id: string; + appointment_id: string | null; + appointment_status: StatusAgendamento | null; + scheduling_method: AppointmentSchedulingMethod | null; + appointment_datetime: Date | null; +} +``` + +Derive customer ID only from JWT. Require a future datetime only for product EMAIL. Reject client datetime for CALENDLY. Validate method against backend capability. Return `process.id` from the creation transaction and only return an existing snapshot after proving ownership. Update `process-dedup-lock.ts` to select and return the exact snapshot above without PII. + +- [ ] **Step 6: Disable the direct PLATFORM path** + +No authorized internal caller exists today. In `AppointmentsService.create`, reject the current direct product scheduling path with a stable `403` before locking/inserting; the product UI must use pending EMAIL or CALENDLY. + +- [ ] **Step 7: Run tests and commit** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/appointments/appointment-schedule-lock.spec.ts src/features/appointments/appointments.controller.spec.ts src/features/appointments/appointments.service.spec.ts src/features/processes/process-dedup-lock.spec.ts +rtk git add backend/src/features/appointments backend/src/features/processes/process-dedup-lock.ts backend/src/features/processes/process-dedup-lock.spec.ts +rtk git commit -m "feat: create dated email appointment requests safely" +``` + +Expected: all contract tests PASS. + +--- + +### Task 4: Aplicar ocupação compartilhada e confirmação canônica + +**Files:** +- Modify: `backend/src/features/appointments/appointments.service.ts` +- Modify: `backend/src/features/processes/processes.service.ts` +- Modify: `backend/src/features/processes/processes.service.spec.ts` +- Modify: `backend/src/features/processes/processes.controller.spec.ts` +- Modify: `backend/src/features/processes/entity/process.response.entity.ts` +- Modify: `backend/src/features/appointments/appointments-concurrency.postgres.spec.ts` + +**Interfaces:** +- Consumes: `buildOccupiedScheduleWhere(specialistId, datetime, excludeAppointmentId?)` from Task 3 in every schedule writer. +- Produces: canonical `ProcessesService.confirmAppointment(processId, specialistId, datetime?)` behavior. +- Produces: assigned-specialist-only contact projection in list and detail. + +- [ ] **Step 1: Write canonical confirmation/contact RED tests** + +Test suggested-time confirmation, changed-time confirmation, future validation, specialist-only authorization, `Appointment=SCHEDULED`, `Process=SCHEDULING`, null reschedule audit fields, proposal/confirmed timestamps in notes, atomic rollback on conflict and idempotent double submission. For both list and detail assert the exact contact matrix: assigned specialist sees client email/phone for `PENDING/EMAIL`, `SCHEDULED` and `COMPLETED`; `PENDING/CALENDLY`, other specialist, OFFICE, CONSULTANT and public/client projections do not receive those contacts early. + +- [ ] **Step 2: Run focused tests and verify RED** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/appointments/appointment-schedule-lock.spec.ts src/features/processes/processes.service.spec.ts src/features/processes/processes.controller.spec.ts +``` + +Expected: FAIL because callers do not yet share the new predicate, contact projections differ and confirmation does not preserve all new invariants. + +- [ ] **Step 3: Apply the shared predicate and implement the canonical transaction** + +Use the same helper in direct creation, confirmation, Calendly callback and reschedule. Confirmation must acquire specialist lock, reread process/appointment in the transaction, validate the chosen future instant, update only the appointment status/date/audit confirmation fields and append notes without setting reschedule audit fields. + +- [ ] **Step 4: Add real PostgreSQL concurrency coverage** + +Exercise `ProcessesService.confirmAppointment`, not `AppointmentsService.confirmPending`: + +```ts +const [first, second] = await Promise.allSettled([ + firstService.confirmAppointment(firstProcessId, specialistId, proposedIso), + secondService.confirmAppointment(secondProcessId, specialistId, proposedIso), +]); +expect([first, second].filter((result) => result.status === 'fulfilled')).toHaveLength(1); +expect(await prisma.appointment.count({ + where: { specialist_id: specialistId, appointment_datetime: proposedDate, status: 'SCHEDULED' }, +})).toBe(1); +``` + +Also cover two concurrent `PENDING/EMAIL` creations for the same specialist/time both succeeding, two specialists at the same time, double-click on one process and absence of partial writes. + +- [ ] **Step 5: Run unit tests and commit** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/appointments/appointment-schedule-lock.spec.ts src/features/processes/processes.service.spec.ts src/features/processes/processes.controller.spec.ts +rtk git add backend/src/features/appointments backend/src/features/processes +rtk git commit -m "fix: confirm email proposals under schedule lock" +``` + +Expected: focused unit tests PASS. PostgreSQL test is executed later with a real URL. + +--- + +### Task 5: Contratos e helpers puros do frontend + +**Files:** +- Create: `frontend/src/lib/email-scheduling.ts` +- Create: `frontend/src/lib/email-scheduling.test.ts` +- Create: `frontend/src/lib/whatsapp.ts` +- Create: `frontend/src/lib/whatsapp.test.ts` +- Create: `frontend/src/services/appointments.service.test.ts` +- Create: `frontend/src/hooks/useCheckAppointment.test.tsx` +- Modify: `frontend/src/lib/appointment-datetime.ts` +- Modify: `frontend/src/lib/appointment-datetime.test.ts` +- Modify: `frontend/src/services/appointments.service.ts` +- Modify: `frontend/src/services/specialists.service.ts` +- Modify: `frontend/src/services/specialists.service.test.ts` +- Modify: `frontend/src/hooks/useCheckAppointment.ts` + +**Interfaces:** +- Produces: `buildEmailSchedulingLinks(input): { mailtoHref; gmailHref; subject; body }`. +- Produces: `buildWhatsAppHref(phone): string | null`. +- Produces: `isoToLocalDateTimeInput(iso): string`. +- Produces: `useCheckAppointment(specialistId, productType, productId)` returning the discriminated own-request check. +- Consumes: backend DTOs from Tasks 1 and 3. + +- [ ] **Step 1: Write helper and service RED tests** + +```ts +const links = buildEmailSchedulingLinks({ + recipient: 'especialista@example.com\r\nBcc:evil@example.com', + specialistName: 'Ana', + clientName: 'João', + productLabel: 'Carro A&B?#', + appointmentDatetime: '2026-10-20T17:30:00.000Z', + timeZone: 'America/Sao_Paulo', +}); +expect(links.mailtoHref).toContain('subject='); +expect(decodeURIComponent(links.mailtoHref)).not.toContain('\r\nBcc:'); +expect(links.gmailHref).toMatch(/^https:\/\/mail\.google\.com\/mail\/\?/); + +expect(buildWhatsAppHref('(11) 98765-4321')).toBe('https://wa.me/5511987654321'); +expect(buildWhatsAppHref('+55 11 98765-4321')).toBe('https://wa.me/5511987654321'); +expect(buildWhatsAppHref('123')).toBeNull(); +``` + +Assert that appointment check sends no `client_id`, EMAIL creation requires datetime at type/runtime boundary, CALENDLY rejects a client datetime type, and public specialist service calls `/specialists/:id/public-profile`. Hook tests use fake timers to cover the 500ms debounce, missing parameters, propagated service error, cleanup on unmount and a stale earlier response not overwriting the latest request. + +Frontend parsing of duplicates must read exactly `response.data.error.code === 'ACTIVE_PROCESS_EXISTS'` and `response.data.error.details.existing_request`, matching Task 3; other 409 responses remain ordinary errors. + +- [ ] **Step 2: Run tests and verify RED** + +```bash +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/lib/email-scheduling.test.ts src/lib/whatsapp.test.ts src/lib/appointment-datetime.test.ts src/services/appointments.service.test.ts src/services/specialists.service.test.ts src/hooks/useCheckAppointment.test.tsx +``` + +Expected: FAIL because helpers and discriminated service contracts do not exist. + +- [ ] **Step 3: Implement pure helpers and types** + +```ts +export type ProductPendingAppointmentInput = + | (BaseProductRequest & { scheduling_method: 'EMAIL'; appointment_datetime: string }) + | (BaseProductRequest & { scheduling_method: 'CALENDLY'; appointment_datetime?: never }); + +export function buildWhatsAppHref(phone: string): string | null { + const digits = phone.replace(/\D/g, ''); + const normalized = /^\d{10,11}$/.test(digits) + ? `55${digits}` + : /^55\d{10,11}$/.test(digits) ? digits : null; + return normalized ? `https://wa.me/${normalized}` : null; +} +``` + +For e-mail, strip CR/LF from recipient and subject, limit subject to 160 and body to 1800 characters, and encode fields separately. Existing check returns a discriminated object and propagates errors rather than converting them to `null`. + +Remove `clientId` from the hook signature and dependency list. Use a monotonically increasing request token so only the latest resolved promise can update `existingAppointment`, `isLoading` or `error`. + +- [ ] **Step 4: Preserve an unchanged ISO in datetime editing** + +Add `isoToLocalDateTimeInput`. Components compare the submitted local value to the initial local value; unchanged sends the original ISO, edited sends `new Date(localValue).toISOString()`. + +- [ ] **Step 5: Run tests and commit** + +```bash +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/lib/email-scheduling.test.ts src/lib/whatsapp.test.ts src/lib/appointment-datetime.test.ts src/services/appointments.service.test.ts src/services/specialists.service.test.ts src/hooks/useCheckAppointment.test.tsx +rtk git add frontend/src/lib frontend/src/services frontend/src/hooks/useCheckAppointment.ts frontend/src/hooks/useCheckAppointment.test.tsx +rtk git commit -m "feat: add safe email scheduling frontend contracts" +``` + +Expected: focused tests PASS. + +--- + +### Task 6: Unificar ProductPage e painel recuperável de e-mail + +**Files:** +- Create: `frontend/src/components/appointments/EmailSchedulingSuccess.tsx` +- Create: `frontend/src/components/appointments/EmailSchedulingSuccess.test.tsx` +- Modify: `frontend/src/components/appointments/NoCalendlySchedulingActions.tsx` +- Modify: `frontend/src/components/appointments/NoCalendlySchedulingActions.test.tsx` +- Modify: `frontend/src/pages/catalog/ProductPage.tsx` +- Modify: `frontend/src/pages/catalog/ProductPage.test.tsx` + +**Interfaces:** +- Consumes: helpers/services from Task 5 and backend capability/check contracts. +- Produces: one CTA `Solicitar reunião` when capability is false and persistent success fallbacks. + +- [ ] **Step 1: Write EmailSchedulingSuccess RED tests** + +```tsx +render(); +expect(screen.getByRole('status')).toBeInTheDocument(); +expect(screen.getByRole('link', { name: /gmail/i })).toHaveAttribute('rel', 'noopener noreferrer'); +await waitFor(() => expect(openMailClient).toHaveBeenCalledTimes(1)); +rerender(); +expect(openMailClient).toHaveBeenCalledTimes(1); +``` + +Cover clipboard success/failure, selectable fallback address, heading focus, `autoOpen=false` and session key `email-request-opened:`. + +- [ ] **Step 2: Write ProductPage RED tests** + +Cover stale URL + capability false, capability true, dated EMAIL payload, no `createPlatformAppointment`, no opener before 201, generic 409 staying an error, own `ACTIVE_PROCESS_EXISTS` reconstruction without auto-open, reload reconstruction, existing CALENDLY/SCHEDULED messaging and double-submit busy behavior. + +- [ ] **Step 3: Run tests and verify RED** + +```bash +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/components/appointments/EmailSchedulingSuccess.test.tsx src/components/appointments/NoCalendlySchedulingActions.test.tsx src/pages/catalog/ProductPage.test.tsx +``` + +Expected: FAIL on the current split EMAIL/PLATFORM UI and eager mail opening. + +- [ ] **Step 4: Implement the unified flow** + +Fetch the public specialist projection. Gate only on `calendly_scheduling_available`. For no Calendly, open `AppointmentDateTimeModal`, create `PENDING/EMAIL` with ISO, render success, then schedule the one-shot external attempt. Recover the same panel from own existing check/duplicate snapshots with `autoOpen=false`. + +- [ ] **Step 5: Run tests and commit** + +```bash +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/components/appointments/EmailSchedulingSuccess.test.tsx src/components/appointments/NoCalendlySchedulingActions.test.tsx src/pages/catalog/ProductPage.test.tsx +rtk git add frontend/src/components/appointments frontend/src/pages/catalog/ProductPage.tsx frontend/src/pages/catalog/ProductPage.test.tsx +rtk git commit -m "feat: unify no-Calendly email request flow" +``` + +Expected: focused tests PASS. + +--- + +### Task 7: Confirmar proposta, WhatsApp e remoção real do Calendly + +**Files:** +- Modify: `frontend/src/components/appointments/AppointmentDateTimeModal.tsx` +- Modify: `frontend/src/components/appointments/AppointmentDateTimeModal.test.tsx` +- Modify: `frontend/src/components/processes/ProcessCard.tsx` +- Modify: `frontend/src/components/processes/ProcessCard.test.tsx` +- Modify: `frontend/src/components/processes/StartProcessForClientModal.tsx` +- Create: `frontend/src/components/processes/StartProcessForClientModal.test.tsx` +- Modify: `frontend/src/pages/customer/ConsultoriaPage.tsx` +- Create: `frontend/src/pages/customer/ConsultoriaPage.test.tsx` +- Modify: `frontend/src/pages/profile/ProfilePage.tsx` +- Create: `frontend/src/pages/profile/ProfilePage.test.tsx` +- Modify: `frontend/src/services/users.service.ts` + +**Interfaces:** +- Consumes: `buildWhatsAppHref`, public Calendly capability and `confirmAppointment`. +- Produces: `AppointmentDateTimeModal.initialValue?: string` and distinct confirm/change actions. + +- [ ] **Step 1: Write modal and ProcessCard RED tests** + +```tsx +expect(screen.getByRole('button', { name: 'Confirmar horário' })).toBeEnabled(); +expect(screen.getByRole('button', { name: 'Alterar e confirmar' })).toBeEnabled(); +await user.click(screen.getByRole('button', { name: 'Confirmar horário' })); +expect(confirmAppointment).toHaveBeenCalledWith(process.id, process.appointment_datetime); +expect(rescheduleAppointment).not.toHaveBeenCalled(); +``` + +Assert changed confirmation uses the modal initial value, a 409 opens/keeps it with inline `role=alert`, busy disables both actions, invalid phone has no `wa.me`, and `SCHEDULED + SCHEDULING` keeps meeting actions. + +- [ ] **Step 2: Write capability/profile regression RED tests** + +Consultoria and StartProcess use the boolean, not stale URL. Consultoria without product can create EMAIL without date. Profile specialist clearing input sends `calendly_url: null`; customer never sends that field. + +- [ ] **Step 3: Run tests and verify RED** + +```bash +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/components/appointments/AppointmentDateTimeModal.test.tsx src/components/processes/ProcessCard.test.tsx src/components/processes/StartProcessForClientModal.test.tsx src/pages/customer/ConsultoriaPage.test.tsx src/pages/profile/ProfilePage.test.tsx +``` + +Expected: FAIL because confirmation is a single action, modal lacks initial value and profile omits empty Calendly URL. + +- [ ] **Step 4: Implement specialist actions and contact links** + +Direct confirmation sends the stored ISO. Alteration opens the modal with `initialValue` and calls the same confirmation endpoint. Do not call reschedule before initial confirmation. Render WhatsApp only from `buildWhatsAppHref`, with `target="_blank" rel="noopener noreferrer"`, while preserving the textual/copyable phone. + +- [ ] **Step 5: Align remaining capability consumers and profile payload** + +Replace raw `calendly_url` gates with the backend boolean in Consultoria and StartProcess. Extend `UpdateUserData.calendly_url` to `string | null` and send null for an emptied specialist field. + +- [ ] **Step 6: Run tests and commit** + +```bash +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/components/appointments/AppointmentDateTimeModal.test.tsx src/components/processes/ProcessCard.test.tsx src/components/processes/StartProcessForClientModal.test.tsx src/pages/customer/ConsultoriaPage.test.tsx src/pages/profile/ProfilePage.test.tsx +rtk git add frontend/src/components frontend/src/pages frontend/src/services/users.service.ts +rtk git commit -m "feat: confirm proposed times and expose WhatsApp safely" +``` + +Expected: focused tests PASS. + +--- + +### Task 8: Stack local, E2E real, revisão adversarial e PR + +**Files:** +- Create: `backend/prisma/seed-email-scheduling-e2e.ts` +- Create: `backend/test/email-scheduling.e2e-spec.ts` +- Modify: `backend/package.json` +- Modify: `docs/docs/agendamento-sem-calendly.md` + +**Interfaces:** +- Consumes: the complete backend/frontend behavior from Tasks 1–7. +- Produces: repeatable local fixtures, HTTP assertions, browser evidence and the PR to `develop`. + +- [ ] **Step 1: Add idempotent E2E fixtures and HTTP tests** + +The seed removes only its known deterministic records, never truncates. It creates one customer with phone, assigned specialist without Calendly, another specialist/user and two assigned products. Credentials come from test environment variables. HTTP tests prove own check shape, IDOR rejection, pending creation, assigned contact projection and confirmation state. + +Add the script `"seed:email-scheduling-e2e": "ts-node prisma/seed-email-scheduling-e2e.ts"`. Do not execute it until the database health check and migrations in Step 2 succeed. + +- [ ] **Step 2: Start stack and execute PostgreSQL concurrency test for real** + +```bash +rtk free -h +rtk docker compose up -d db +rtk docker compose exec -T db sh -lc 'until pg_isready -U user -d bmfluxdb; do sleep 1; done' +rtk env DATABASE_URL='postgresql://user:password@localhost:5432/bmfluxdb?schema=public' DIRECT_URL='postgresql://user:password@localhost:5432/bmfluxdb?schema=public' npm --prefix backend exec -- prisma migrate deploy +rtk env DATABASE_URL='postgresql://user:password@localhost:5432/bmfluxdb?schema=public' npm --prefix backend run seed:email-scheduling-e2e +rtk env POSTGRES_CONCURRENCY_TEST_URL='postgresql://user:password@localhost:5432/bmfluxdb?schema=public' node -e "if (!process.env.POSTGRES_CONCURRENCY_TEST_URL) process.exit(1)" +rtk env POSTGRES_CONCURRENCY_TEST_URL='postgresql://user:password@localhost:5432/bmfluxdb?schema=public' npm --prefix backend test -- --runInBand --runTestsByPath src/features/appointments/appointments-concurrency.postgres.spec.ts --json --outputFile=/tmp/high-class-shop-email-scheduling-jest.json +rtk node -e "const r=require('/tmp/high-class-shop-email-scheduling-jest.json');if(!r.success||r.numPendingTests!==0)process.exit(1)" +``` + +Expected: database is healthy, migrations/seed succeed, and the focused concurrency command executes with zero skipped tests and PASS. Keep the existing `describe.skip` behavior when the URL is absent so ordinary unit suites remain independent of PostgreSQL; the explicit precheck and URL in this dedicated gate prevent an accidental skip here. + +- [ ] **Step 3: Run HTTP E2E and browser scenarios** + +```bash +rtk env DATABASE_URL='postgresql://user:password@localhost:5432/bmfluxdb?schema=public' JWT_SECRET_ACCESS='local-e2e-access-secret' JWT_SECRET_REFRESH='local-e2e-refresh-secret' JWT_SECRET_REFERRAL='local-e2e-referral-secret' JWT_SECRET_ADVISOR='local-e2e-advisor-secret' JWT_SECRET_PASSWORD_RESET='local-e2e-reset-secret' npm --prefix backend run test:e2e -- --runInBand --runTestsByPath test/email-scheduling.e2e-spec.ts +``` + +Start backend and frontend from the checked-out source in separate terminal sessions, using the same local-only environment values and `VITE_API_BASE_URL=http://localhost:3000/api`. This avoids stale application images; Docker is used only for PostgreSQL. + +In independent browser contexts: + +1. Customer creates Product A request and inspect mailto/Gmail href without asserting external send. +2. Reload and verify fallbacks persist without another auto-open. +3. Assigned specialist sees proposal/email/phone/WhatsApp, changes and confirms; appointment becomes `SCHEDULED`, process remains `SCHEDULING`, meeting controls remain and reschedule audit stays null. +4. Product B repeats confirmation without change. +5. Unassigned user cannot read contacts, confirm, or access another private GET/PATCH user profile. +6. Repeat the critical request path on mobile viewport and by keyboard. + +Capture request/response status and payloads for creation, check and confirmation. After each confirmation, use a read-only Prisma/SQL query against the deterministic fixture IDs to assert appointment status/date, process status, null reschedule audit fields and exact appointment/process cardinality. Browser-visible assertions alone are insufficient for these database postconditions. + +- [ ] **Step 4: Run full verification sequentially** + +```bash +rtk free -h +rtk git diff --check +rtk npm --prefix backend test -- --maxWorkers=2 +rtk npm --prefix backend run test:e2e -- --runInBand +rtk npm --prefix backend run build +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 +rtk npm --prefix frontend run lint +rtk npm --prefix frontend run build +rtk rg -n 'client_id' frontend/src backend/src/features/appointments | rtk rg 'appointments/check' || true +``` + +Expected: all tests/builds PASS, no schema/migration diff, and no check request sends client identity. + +- [ ] **Step 5: Update documentation and commit E2E evidence code** + +Document the final manual flow, external e-mail limitation, confirmation semantics and contacts. Commit only source/tests/docs, never screenshots containing PII or local credentials. + +```bash +rtk git add backend/package.json backend/prisma/seed-email-scheduling-e2e.ts backend/test docs/docs/agendamento-sem-calendly.md +rtk git commit -m "test: cover no-Calendly email scheduling end to end" +``` + +- [ ] **Step 6: Run adversarial review and resolve every CRITICAL/HIGH** + +Use the `adversarial-review` skill across business rules, authorization/PII, concurrency, frontend UX/accessibility and E2E fidelity. Apply accepted fixes with their own RED/GREEN cycle and repeat affected verification. + +- [ ] **Step 7: Sync with develop, reverify and open PR** + +Fetch `origin/develop`, use `safe-main-sync` if it diverged materially, rerun affected suites/builds, push `codex/fix-no-calendly-email-flow` and create a PR targeting `develop`. Attach the created PR to the task. From 74f062211438f53204e3988c0495613686218af6 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 07:39:31 -0300 Subject: [PATCH 03/60] feat: centralize Calendly scheduling capability --- .../calendly-integration.service.spec.ts | 218 ++++++++++++++++++ .../calendly-integration.service.ts | 68 ++++-- .../specialists.controller.spec.ts | 54 +++++ .../specialists/specialists.controller.ts | 9 + .../specialists/specialists.service.spec.ts | 151 ++++++++++-- .../specialists/specialists.service.ts | 68 ++++-- .../calendly-scheduling-capability.spec.ts | 36 +++ .../utils/calendly-scheduling-capability.ts | 17 ++ 8 files changed, 569 insertions(+), 52 deletions(-) create mode 100644 backend/src/features/specialists/specialists.controller.spec.ts create mode 100644 backend/src/shared/utils/calendly-scheduling-capability.spec.ts create mode 100644 backend/src/shared/utils/calendly-scheduling-capability.ts diff --git a/backend/src/features/appointments/calendly-integration.service.spec.ts b/backend/src/features/appointments/calendly-integration.service.spec.ts index 19706dc..6911553 100644 --- a/backend/src/features/appointments/calendly-integration.service.spec.ts +++ b/backend/src/features/appointments/calendly-integration.service.spec.ts @@ -1,5 +1,223 @@ import { AppointmentSchedulingMethod } from '@prisma/client'; import { CalendlyIntegrationService } from './calendly-integration.service'; +import axios from 'axios'; + +jest.mock('axios'); + +describe('CalendlyIntegrationService connection lifecycle', () => { + const originalEnv = { ...process.env }; + beforeEach(() => { + jest.clearAllMocks(); + process.env.CALENDLY_OAUTH_CLIENT_ID = 'client-id'; + process.env.CALENDLY_OAUTH_CLIENT_SECRET = 'client-secret'; + process.env.CALENDLY_OAUTH_REDIRECT_URI = 'https://app.test/callback'; + process.env.CALENDLY_TOKEN_ENCRYPTION_KEY = + '12345678901234567890123456789012'; + delete process.env.CALENDLY_WEBHOOK_CALLBACK_URL; + }); + afterAll(() => { + process.env = originalEnv; + }); + + function makeCallbackService(scheduling_url: string | undefined) { + const prisma = { + calendlyOauthState: { + findUnique: jest + .fn() + .mockResolvedValue({ + id: 'state-1', + user_id: 'specialist-1', + used_at: null, + expires_at: new Date(Date.now() + 60000), + user: { id: 'specialist-1', role: 'SPECIALIST' }, + }), + update: jest.fn().mockResolvedValue({}), + }, + calendlyConnection: { + upsert: jest.fn().mockResolvedValue({ user_id: 'specialist-1' }), + }, + user: { update: jest.fn().mockResolvedValue({}) }, + }; + jest + .mocked(axios.post) + .mockResolvedValue({ + data: { + access_token: 'access', + refresh_token: 'refresh', + expires_in: 3600, + }, + }); + jest + .mocked(axios.get) + .mockResolvedValue({ + data: { + resource: { + uri: 'https://api.calendly.com/users/1', + current_organization: 'https://api.calendly.com/organizations/1', + scheduling_url, + }, + }, + }); + return { prisma, service: new CalendlyIntegrationService(prisma as any) }; + } + + it('persiste scheduling_url validada no callback OAuth', async () => { + const { prisma, service } = makeCallbackService( + 'https://calendly.com/ana/reuniao', + ); + expect(await service.handleOAuthCallback('code', 'state')).toBe( + 'specialist-1', + ); + expect(prisma.user.update).toHaveBeenCalledWith({ + where: { id: 'specialist-1' }, + data: { + calendly_url: 'https://calendly.com/ana/reuniao', + calendly_user_uri: 'https://api.calendly.com/users/1', + calendly_organization_uri: 'https://api.calendly.com/organizations/1', + }, + }); + expect(prisma.calendlyConnection.upsert).toHaveBeenCalledWith( + expect.objectContaining({ + create: expect.objectContaining({ is_active: true }), + update: expect.objectContaining({ is_active: true }), + }), + ); + }); + + it.each([ + undefined, + 'http://calendly.com/ana', + 'https://evilcalendly.com/ana', + 'https://calendly.com.evil.test/ana', + 'https://calendly.com@evil.test/ana', + 'not-a-url', + ])('rejeita scheduling_url inválida antes de persistir: %s', async (url) => { + const { prisma, service } = makeCallbackService(url); + await expect(service.handleOAuthCallback('code', 'state')).rejects.toThrow( + 'Calendly não retornou URL de agendamento válida', + ); + expect(prisma.calendlyConnection.upsert).not.toHaveBeenCalled(); + expect(prisma.user.update).not.toHaveBeenCalled(); + expect(prisma.calendlyOauthState.update).not.toHaveBeenCalled(); + }); + + it('desativa e limpa URL e URIs em uma transação', async () => { + const tx = { + calendlyConnection: { + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + user: { update: jest.fn().mockResolvedValue({}) }, + }; + const prisma = { + $transaction: jest.fn(async (callback: any) => + typeof callback === 'function' ? callback(tx) : Promise.all(callback), + ), + calendlyConnection: { + findUnique: jest.fn().mockResolvedValue({ id: 'connection-1' }), + update: jest.fn().mockResolvedValue({}), + }, + user: { update: jest.fn().mockResolvedValue({}) }, + }; + await new CalendlyIntegrationService(prisma as any).disconnect( + 'specialist-1', + ); + expect(prisma.$transaction).toHaveBeenCalledTimes(1); + expect(tx.calendlyConnection.updateMany).toHaveBeenCalledWith({ + where: { user_id: 'specialist-1' }, + data: { is_active: false, last_sync_at: expect.any(Date) }, + }); + expect(tx.user.update).toHaveBeenCalledWith({ + where: { id: 'specialist-1' }, + data: { + calendly_url: null, + calendly_user_uri: null, + calendly_organization_uri: null, + }, + }); + }); + + function makeRefreshService() { + const prisma = { + calendlyConnection: { findUnique: jest.fn(), update: jest.fn() }, + }; + const service = new CalendlyIntegrationService(prisma as any); + const connection = { + id: 'connection-1', + user_id: 'specialist-1', + is_active: true, + expires_at: new Date(0), + access_token_encrypted: (service as any).encryptToken('expired-access'), + refresh_token_encrypted: (service as any).encryptToken('valid-refresh'), + }; + prisma.calendlyConnection.findUnique.mockResolvedValue(connection); + prisma.calendlyConnection.update.mockImplementation(({ data }) => + Promise.resolve({ ...connection, ...data }), + ); + return { service, prisma }; + } + + it('mantém conexão ativa quando token expirado é renovado com sucesso', async () => { + const { service, prisma } = makeRefreshService(); + jest + .mocked(axios.get) + .mockRejectedValueOnce({ response: { status: 401 } }) + .mockResolvedValueOnce({ + data: { resource: { start_time: '2099-01-01T10:00:00.000Z' } }, + }); + jest + .mocked(axios.post) + .mockResolvedValue({ + data: { + access_token: 'renewed-access', + refresh_token: 'renewed-refresh', + expires_in: 3600, + }, + }); + expect( + await service.resolveScheduledStartTime( + 'specialist-1', + '/scheduled_events/1', + ), + ).toEqual(new Date('2099-01-01T10:00:00.000Z')); + expect( + prisma.calendlyConnection.update.mock.calls.every( + ([input]) => input.data.is_active !== false, + ), + ).toBe(true); + expect(axios.get).toHaveBeenLastCalledWith( + 'https://api.calendly.com/scheduled_events/1', + expect.objectContaining({ + headers: { Authorization: 'Bearer renewed-access' }, + }), + ); + }); + + it('persiste desativação e erro após invalid_grant definitivo', async () => { + const { service, prisma } = makeRefreshService(); + const error = { + response: { status: 400, data: { error: 'invalid_grant' } }, + }; + jest.mocked(axios.get).mockRejectedValue({ response: { status: 401 } }); + jest.mocked(axios.post).mockRejectedValue(error); + await expect( + service.resolveScheduledStartTime('specialist-1', '/scheduled_events/1'), + ).rejects.toBe(error); + expect(prisma.calendlyConnection.update).toHaveBeenCalledWith({ + where: { id: 'connection-1' }, + data: { is_active: false, last_error: 'invalid_grant' }, + }); + }); + + it('preserva conexão ativa após falha transitória de refresh', async () => { + const { service, prisma } = makeRefreshService(); + jest.mocked(axios.get).mockRejectedValue({ response: { status: 401 } }); + jest.mocked(axios.post).mockRejectedValue({ response: { status: 503 } }); + await expect( + service.resolveScheduledStartTime('specialist-1', '/scheduled_events/1'), + ).rejects.toBeDefined(); + expect(prisma.calendlyConnection.update).not.toHaveBeenCalled(); + }); +}); describe('CalendlyIntegrationService webhook schedule integrity', () => { it.each([ diff --git a/backend/src/features/appointments/calendly-integration.service.ts b/backend/src/features/appointments/calendly-integration.service.ts index b48e54d..b1aa3f2 100644 --- a/backend/src/features/appointments/calendly-integration.service.ts +++ b/backend/src/features/appointments/calendly-integration.service.ts @@ -22,6 +22,7 @@ import { } from 'crypto'; import { PrismaService } from 'src/prisma/prisma.service'; import { parseDate } from 'src/shared/utils/date.utils'; +import { isCalendlySchedulingAvailable } from 'src/shared/utils/calendly-scheduling-capability'; import { acquireSpecialistScheduleLock, assertSpecialistScheduleAvailable, @@ -39,6 +40,7 @@ interface CalendlyUserMeResponse { resource: { uri: string; current_organization?: string; + scheduling_url?: string; }; } @@ -183,6 +185,18 @@ export class CalendlyIntegrationService { ); } + const schedulingUrl = me.resource.scheduling_url ?? null; + if ( + !isCalendlySchedulingAvailable({ + calendlyUrl: schedulingUrl, + connectionActive: true, + }) + ) { + throw new BadRequestException( + 'Calendly não retornou URL de agendamento válida', + ); + } + const expiresAt = token.expires_in ? new Date(Date.now() + token.expires_in * 1000) : null; @@ -222,6 +236,7 @@ export class CalendlyIntegrationService { await this.prisma.user.update({ where: { id: stateRecord.user_id }, data: { + calendly_url: schedulingUrl, calendly_user_uri: me.resource.uri, calendly_organization_uri: me.resource.current_organization || null, }, @@ -244,30 +259,23 @@ export class CalendlyIntegrationService { } async disconnect(userId: string): Promise { - const connection = await this.prisma.calendlyConnection.findUnique({ - where: { user_id: userId }, - }); - - if (!connection) { - return; - } - - await this.prisma.$transaction([ - this.prisma.calendlyConnection.update({ - where: { id: connection.id }, + await this.prisma.$transaction(async (tx) => { + await tx.calendlyConnection.updateMany({ + where: { user_id: userId }, data: { is_active: false, last_sync_at: new Date(), }, - }), - this.prisma.user.update({ + }); + await tx.user.update({ where: { id: userId }, data: { + calendly_url: null, calendly_user_uri: null, calendly_organization_uri: null, }, - }), - ]); + }); + }); } async resolveScheduledStartTime( @@ -550,16 +558,28 @@ export class CalendlyIntegrationService { client_secret: clientSecret, }); - const { data } = await axios.post( - tokenUrl, - payload.toString(), - { - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', + let data: CalendlyTokenResponse; + try { + const response = await axios.post( + tokenUrl, + payload.toString(), + { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + timeout: 20000, }, - timeout: 20000, - }, - ); + ); + data = response.data; + } catch (error: any) { + if (error?.response?.data?.error === 'invalid_grant') { + await this.prisma.calendlyConnection.update({ + where: { id: connection.id }, + data: { is_active: false, last_error: 'invalid_grant' }, + }); + } + throw error; + } const expiresAt = data.expires_in ? new Date(Date.now() + data.expires_in * 1000) diff --git a/backend/src/features/specialists/specialists.controller.spec.ts b/backend/src/features/specialists/specialists.controller.spec.ts new file mode 100644 index 0000000..8fe4abe --- /dev/null +++ b/backend/src/features/specialists/specialists.controller.spec.ts @@ -0,0 +1,54 @@ +import { PATH_METADATA } from '@nestjs/common/constants'; +import { IS_PUBLIC_KEY } from 'src/shared/decorators/public.decorator'; +import { SpecialistsController } from './specialists.controller'; + +describe('SpecialistsController public profile', () => { + it('protege a listagem administrativa com ADMIN', () => { + expect( + Reflect.getMetadata('roles', SpecialistsController.prototype.findAll), + ).toEqual(['ADMIN']); + expect( + Reflect.getMetadata( + IS_PUBLIC_KEY, + SpecialistsController.prototype.findAll, + ), + ).not.toBe(true); + }); + + it('protege o cadastro completo com ADMIN', () => { + expect( + Reflect.getMetadata('roles', SpecialistsController.prototype.findOne), + ).toEqual(['ADMIN']); + expect( + Reflect.getMetadata( + IS_PUBLIC_KEY, + SpecialistsController.prototype.findOne, + ), + ).not.toBe(true); + }); + + it('publica a rota dedicada antes da rota genérica', () => { + const prototype = SpecialistsController.prototype; + expect( + Reflect.getMetadata(PATH_METADATA, prototype.findPublicProfile), + ).toBe(':id/public-profile'); + expect( + Reflect.getMetadata(IS_PUBLIC_KEY, prototype.findPublicProfile), + ).toBe(true); + const methods = Object.getOwnPropertyNames(prototype); + expect(methods.indexOf('findPublicProfile')).toBeLessThan( + methods.indexOf('findOne'), + ); + }); + + it('encaminha o ID para a projeção segura', async () => { + const profile = { + id: 'specialist-1', + calendly_scheduling_available: false, + }; + const service = { findPublicProfile: jest.fn().mockResolvedValue(profile) }; + const controller = new SpecialistsController(service as any); + expect(await controller.findPublicProfile('specialist-1')).toBe(profile); + expect(service.findPublicProfile).toHaveBeenCalledWith('specialist-1'); + }); +}); diff --git a/backend/src/features/specialists/specialists.controller.ts b/backend/src/features/specialists/specialists.controller.ts index 449a4e7..c8711e0 100644 --- a/backend/src/features/specialists/specialists.controller.ts +++ b/backend/src/features/specialists/specialists.controller.ts @@ -15,6 +15,7 @@ import { UpdateSpecialistDto } from './dto/update-specialist.dto'; import { InviteSpecialistDto } from './dto/invite-specialist.dto'; import { Roles } from 'src/shared/decorators/roles.decorator'; import { UserRole } from '@prisma/client'; +import { Public } from 'src/shared/decorators/public.decorator'; /** * Define a rota base para este controlador. @@ -30,6 +31,7 @@ export class SpecialistsController { // ROTAS CRUD PARA ESPECIALISTAS // Rota para buscar todos os especialistas. + @Roles(UserRole.ADMIN) @Get() findAll() { return this.specialistsService.findAll(); @@ -61,7 +63,14 @@ export class SpecialistsController { }; } + @Public() + @Get(':id/public-profile') + findPublicProfile(@Param('id') id: string) { + return this.specialistsService.findPublicProfile(id); + } + // Rota para buscar um único especialista pelo seu ID. + @Roles(UserRole.ADMIN) @Get(':id') findOne(@Param('id') id: string) { return this.specialistsService.findOne(id); diff --git a/backend/src/features/specialists/specialists.service.spec.ts b/backend/src/features/specialists/specialists.service.spec.ts index f620ed0..a7122f1 100644 --- a/backend/src/features/specialists/specialists.service.spec.ts +++ b/backend/src/features/specialists/specialists.service.spec.ts @@ -3,6 +3,9 @@ import { SpecialistsService } from './specialists.service'; jest.mock('bcrypt', () => ({ hash: jest.fn().mockResolvedValue('hashed-password'), })); +jest.mock('src/auth/constants', () => ({ + jwtConstants: { referral: 'test-referral-secret' }, +})); describe('SpecialistsService.inviteSpecialist', () => { it('assina a comissão definida pelo administrador', async () => { @@ -39,12 +42,17 @@ describe('SpecialistsService.inviteSpecialist', () => { }); describe('SpecialistsService.findAll', () => { - it('preserva null e zero como estados distintos', async () => { + it('preserva null, zero e Decimal de comissão na listagem administrativa', async () => { const prisma = { user: { findMany: jest.fn().mockResolvedValue([ - { id: 'legacy', commission_rate: null }, - { id: 'zero', commission_rate: 0 }, + { id: 'legacy', commission_rate: null, company: null }, + { id: 'zero', commission_rate: 0, company: null }, + { + id: 'decimal', + commission_rate: { toString: () => '12.5' }, + company: { id: 'company-1' }, + }, ]), }, } as any; @@ -57,7 +65,12 @@ describe('SpecialistsService.findAll', () => { const result = await service.findAll(); - expect(result.map((item) => item.commission_rate)).toEqual([null, 0]); + expect(result.map((item) => item.commission_rate)).toEqual([null, 0, 12.5]); + expect(result[2].company).toEqual({ id: 'company-1' }); + expect(prisma.user.findMany).toHaveBeenCalledWith({ + where: { role: 'SPECIALIST' }, + include: { company: true }, + }); }); }); @@ -78,6 +91,111 @@ describe('SpecialistsService.findAllGroupedByCategory', () => { const select = prisma.user.findMany.mock.calls[0][0].select; expect(select).not.toHaveProperty('commission_rate'); }); + + it('usa a mesma allowlist e serializa capacidade nas categorias', async () => { + const prisma = { + user: { findMany: jest.fn().mockResolvedValue([publicSpecialist]) }, + } as any; + const service = new SpecialistsService( + prisma, + {} as any, + {} as any, + {} as any, + ); + expect(await service.findAllGroupedByCategory()).toEqual({ + CAR: [publicProfile], + BOAT: [], + AIRCRAFT: [], + }); + expect(prisma.user.findMany).toHaveBeenCalledWith({ + where: { role: 'SPECIALIST' }, + select: publicSelect, + }); + }); +}); + +const publicSelect = { + id: true, + name: true, + surname: true, + email: true, + speciality: true, + calendly_url: true, + calendly_connection: { select: { is_active: true } }, +}; +const publicProfile = { + id: 'specialist-1', + name: 'Ana', + surname: 'Silva', + email: 'ana@example.com', + speciality: 'CAR', + calendly_url: 'https://calendly.com/ana/reuniao', + calendly_scheduling_available: true, +}; +const publicSpecialist = { + ...publicProfile, + calendly_connection: { is_active: true }, + cpf: 'private-cpf', + rg: 'private-rg', + password_hash: 'private-password', + commission_rate: 25, + bank: 'private-bank', + calendly_user_uri: 'private-uri', +}; + +describe('SpecialistsService.findPublicProfile', () => { + function makeService(record: unknown) { + const prisma = { + user: { findUnique: jest.fn().mockResolvedValue(record) }, + } as any; + return { + prisma, + service: new SpecialistsService(prisma, {} as any, {} as any, {} as any), + }; + } + + it('seleciona e retorna somente a allowlist pública', async () => { + const { service, prisma } = makeService(publicSpecialist); + expect(await service.findPublicProfile('specialist-1')).toEqual( + publicProfile, + ); + expect(prisma.user.findUnique).toHaveBeenCalledWith({ + where: { id: 'specialist-1', role: 'SPECIALIST' }, + select: publicSelect, + }); + }); + + it.each([null, { is_active: false }])( + 'desabilita capacidade sem conexão ativa %s', + async (calendly_connection) => { + const { service } = makeService({ + ...publicSpecialist, + calendly_connection, + }); + expect(await service.findPublicProfile('specialist-1')).toEqual({ + ...publicProfile, + calendly_scheduling_available: false, + }); + }, + ); + + it('desabilita capacidade com URL inválida', async () => { + const { service } = makeService({ + ...publicSpecialist, + calendly_url: 'https://evilcalendly.com/a', + }); + expect( + (await service.findPublicProfile('specialist-1')) + .calendly_scheduling_available, + ).toBe(false); + }); + + it('retorna 404 quando nenhum especialista corresponde ao ID', async () => { + const { service } = makeService(null); + await expect(service.findPublicProfile('missing')).rejects.toThrow( + 'Especialista não encontrado', + ); + }); }); describe('SpecialistsService.create', () => { @@ -95,9 +213,11 @@ describe('SpecialistsService.create', () => { const prisma = { user: { findUnique: jest.fn().mockResolvedValue(null), - create: jest.fn().mockImplementation(({ data }) => - Promise.resolve({ id: 'specialist-1', ...data }), - ), + create: jest + .fn() + .mockImplementation(({ data }) => + Promise.resolve({ id: 'specialist-1', ...data }), + ), }, } as any; const notifications = { @@ -115,15 +235,18 @@ describe('SpecialistsService.create', () => { }; } - it.each([0, 100])('persiste comissão obrigatória %s', async (commission_rate) => { - const { prisma, service } = makeService(); + it.each([0, 100])( + 'persiste comissão obrigatória %s', + async (commission_rate) => { + const { prisma, service } = makeService(); - await service.create({ ...base, commission_rate } as any); + await service.create({ ...base, commission_rate } as any); - expect(prisma.user.create).toHaveBeenCalledWith({ - data: expect.objectContaining({ commission_rate }), - }); - }); + expect(prisma.user.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ commission_rate }), + }); + }, + ); it.each([undefined, null, 12.345, 1e-7])( 'rejeita comissão inválida %s antes de persistir', diff --git a/backend/src/features/specialists/specialists.service.ts b/backend/src/features/specialists/specialists.service.ts index 7f64d5c..1b69eff 100644 --- a/backend/src/features/specialists/specialists.service.ts +++ b/backend/src/features/specialists/specialists.service.ts @@ -16,6 +16,43 @@ import { jwtConstants } from 'src/auth/constants'; import { NotificationService } from '../notifications/notification.service'; import { SpecialistInvitePayload } from '../../auth/types/specialist-invite-payload'; import { isValidCommissionRate } from '../../shared/validators/commission-rate.validator'; +import { isCalendlySchedulingAvailable } from '../../shared/utils/calendly-scheduling-capability'; + +const publicSpecialistSelect = { + id: true, + name: true, + surname: true, + email: true, + speciality: true, + calendly_url: true, + calendly_connection: { select: { is_active: true } }, +} satisfies Prisma.UserSelect; + +type PublicSpecialistRecord = Prisma.UserGetPayload<{ + select: typeof publicSpecialistSelect; +}>; + +export type PublicSpecialistProfile = Pick< + PublicSpecialistRecord, + 'id' | 'name' | 'surname' | 'email' | 'speciality' | 'calendly_url' +> & { calendly_scheduling_available: boolean }; + +function toPublicProfile( + specialist: PublicSpecialistRecord, +): PublicSpecialistProfile { + return { + id: specialist.id, + name: specialist.name, + surname: specialist.surname, + email: specialist.email, + speciality: specialist.speciality, + calendly_url: specialist.calendly_url, + calendly_scheduling_available: isCalendlySchedulingAvailable({ + calendlyUrl: specialist.calendly_url, + connectionActive: specialist.calendly_connection?.is_active ?? false, + }), + }; +} @Injectable() export class SpecialistsService { @@ -80,6 +117,17 @@ export class SpecialistsService { return specialists.map((specialist) => this.toResponse(specialist)); } + async findPublicProfile(id: string): Promise { + const specialist = await this.prisma.user.findUnique({ + where: { id, role: 'SPECIALIST' }, + select: publicSpecialistSelect, + }); + if (!specialist) { + throw new NotFoundException('Especialista não encontrado'); + } + return toPublicProfile(specialist); + } + // Cria um novo especialista na base de dados. async create(data: CreateSpecialistDto) { if (!isValidCommissionRate(data.commission_rate)) { @@ -278,24 +326,16 @@ export class SpecialistsService { async findAllGroupedByCategory() { const specialists = await this.prisma.user.findMany({ where: { role: 'SPECIALIST' }, - select: { - id: true, - name: true, - surname: true, - email: true, - cpf: true, - rg: true, - speciality: true, - company_id: true, - calendly_url: true, - }, + select: publicSpecialistSelect, }); + const profiles = specialists.map(toPublicProfile); + // Agrupa os especialistas por categoria const grouped = { - CAR: specialists.filter((s) => s.speciality === 'CAR'), - BOAT: specialists.filter((s) => s.speciality === 'BOAT'), - AIRCRAFT: specialists.filter((s) => s.speciality === 'AIRCRAFT'), + CAR: profiles.filter((s) => s.speciality === 'CAR'), + BOAT: profiles.filter((s) => s.speciality === 'BOAT'), + AIRCRAFT: profiles.filter((s) => s.speciality === 'AIRCRAFT'), }; return grouped; diff --git a/backend/src/shared/utils/calendly-scheduling-capability.spec.ts b/backend/src/shared/utils/calendly-scheduling-capability.spec.ts new file mode 100644 index 0000000..9291f26 --- /dev/null +++ b/backend/src/shared/utils/calendly-scheduling-capability.spec.ts @@ -0,0 +1,36 @@ +import { isCalendlySchedulingAvailable } from './calendly-scheduling-capability'; + +describe('isCalendlySchedulingAvailable', () => { + it.each([ + 'https://calendly.com/especialista/reuniao', + 'https://www.calendly.com/a', + 'https://CALENDLY.COM/a', + ])('aceita uma conexão ativa com URL Calendly HTTPS: %s', (calendlyUrl) => { + expect( + isCalendlySchedulingAvailable({ calendlyUrl, connectionActive: true }), + ).toBe(true); + }); + + it.each([ + null, + '', + 'http://calendly.com/a', + 'https://evilcalendly.com/a', + 'https://calendly.com.evil.test/a', + 'https://calendly.com@evil.test/a', + 'not-a-url', + ])('rejeita URL inválida ou ausente: %s', (calendlyUrl) => { + expect( + isCalendlySchedulingAvailable({ calendlyUrl, connectionActive: true }), + ).toBe(false); + }); + + it('não permite agendamento com conexão inativa', () => { + expect( + isCalendlySchedulingAvailable({ + calendlyUrl: 'https://calendly.com/a', + connectionActive: false, + }), + ).toBe(false); + }); +}); diff --git a/backend/src/shared/utils/calendly-scheduling-capability.ts b/backend/src/shared/utils/calendly-scheduling-capability.ts new file mode 100644 index 0000000..e9448e8 --- /dev/null +++ b/backend/src/shared/utils/calendly-scheduling-capability.ts @@ -0,0 +1,17 @@ +export function isCalendlySchedulingAvailable(input: { + calendlyUrl: string | null; + connectionActive: boolean; +}): boolean { + if (!input.connectionActive || !input.calendlyUrl) return false; + + try { + const url = new URL(input.calendlyUrl); + const host = url.hostname.toLowerCase(); + return ( + url.protocol === 'https:' && + (host === 'calendly.com' || host.endsWith('.calendly.com')) + ); + } catch { + return false; + } +} From 636fcf7f7846a7e0fca6674d855a8b965644f5c9 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 07:44:00 -0300 Subject: [PATCH 04/60] fix: preserve Calendly reconnection on stale refresh failure --- .../calendly-integration.service.spec.ts | 96 ++++++++++++++++++- .../calendly-integration.service.ts | 11 ++- 2 files changed, 99 insertions(+), 8 deletions(-) diff --git a/backend/src/features/appointments/calendly-integration.service.spec.ts b/backend/src/features/appointments/calendly-integration.service.spec.ts index 6911553..d8ffc1f 100644 --- a/backend/src/features/appointments/calendly-integration.service.spec.ts +++ b/backend/src/features/appointments/calendly-integration.service.spec.ts @@ -138,7 +138,11 @@ describe('CalendlyIntegrationService connection lifecycle', () => { function makeRefreshService() { const prisma = { - calendlyConnection: { findUnique: jest.fn(), update: jest.fn() }, + calendlyConnection: { + findUnique: jest.fn(), + update: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, }; const service = new CalendlyIntegrationService(prisma as any); const connection = { @@ -153,7 +157,7 @@ describe('CalendlyIntegrationService connection lifecycle', () => { prisma.calendlyConnection.update.mockImplementation(({ data }) => Promise.resolve({ ...connection, ...data }), ); - return { service, prisma }; + return { service, prisma, connection }; } it('mantém conexão ativa quando token expirado é renovado com sucesso', async () => { @@ -193,7 +197,7 @@ describe('CalendlyIntegrationService connection lifecycle', () => { }); it('persiste desativação e erro após invalid_grant definitivo', async () => { - const { service, prisma } = makeRefreshService(); + const { service, prisma, connection } = makeRefreshService(); const error = { response: { status: 400, data: { error: 'invalid_grant' } }, }; @@ -202,12 +206,93 @@ describe('CalendlyIntegrationService connection lifecycle', () => { await expect( service.resolveScheduledStartTime('specialist-1', '/scheduled_events/1'), ).rejects.toBe(error); - expect(prisma.calendlyConnection.update).toHaveBeenCalledWith({ - where: { id: 'connection-1' }, + expect(prisma.calendlyConnection.updateMany).toHaveBeenCalledWith({ + where: { + id: 'connection-1', + refresh_token_encrypted: connection.refresh_token_encrypted, + is_active: true, + }, data: { is_active: false, last_error: 'invalid_grant' }, }); }); + it('preserva reconexão enquanto refresh antigo está pendente com invalid_grant', async () => { + const { service, prisma } = makeCallbackService( + 'https://calendly.com/ana/reuniao', + ); + const storedConnection = { + id: 'connection-1', + user_id: 'specialist-1', + is_active: true, + last_error: null as string | null, + access_token_encrypted: (service as any).encryptToken('old-access'), + refresh_token_encrypted: (service as any).encryptToken('old-refresh'), + }; + const connectionClient = { + ...prisma.calendlyConnection, + findUnique: jest.fn(async () => ({ ...storedConnection })), + update: jest.fn(async ({ data }) => { + Object.assign(storedConnection, data); + return { ...storedConnection }; + }), + updateMany: jest.fn(async ({ where, data }) => { + const matches = Object.entries(where).every( + ([key, value]) => + storedConnection[key as keyof typeof storedConnection] === value, + ); + if (matches) Object.assign(storedConnection, data); + return { count: matches ? 1 : 0 }; + }), + }; + prisma.calendlyConnection = connectionClient; + connectionClient.upsert.mockImplementation(async ({ update }) => { + Object.assign(storedConnection, update); + return { ...storedConnection }; + }); + + let rejectRefresh!: (error: unknown) => void; + let markRefreshStarted!: () => void; + const refreshStarted = new Promise((resolve) => { + markRefreshStarted = resolve; + }); + jest.mocked(axios.get).mockRejectedValueOnce({ response: { status: 401 } }); + jest.mocked(axios.post).mockImplementationOnce( + () => + new Promise((_, reject) => { + rejectRefresh = reject; + markRefreshStarted(); + }), + ); + const error = { + response: { status: 400, data: { error: 'invalid_grant' } }, + }; + const refreshResult = expect( + service.resolveScheduledStartTime('specialist-1', '/scheduled_events/1'), + ).rejects.toBe(error); + await refreshStarted; + await service.handleOAuthCallback('new-code', 'new-state'); + const reconnectedTokens = { + access_token_encrypted: storedConnection.access_token_encrypted, + refresh_token_encrypted: storedConnection.refresh_token_encrypted, + }; + expect( + (service as any).decryptToken(reconnectedTokens.access_token_encrypted), + ).toBe('access'); + expect( + (service as any).decryptToken(reconnectedTokens.refresh_token_encrypted), + ).toBe('refresh'); + + rejectRefresh(error); + await refreshResult; + expect(storedConnection).toEqual( + expect.objectContaining({ + ...reconnectedTokens, + is_active: true, + last_error: null, + }), + ); + }); + it('preserva conexão ativa após falha transitória de refresh', async () => { const { service, prisma } = makeRefreshService(); jest.mocked(axios.get).mockRejectedValue({ response: { status: 401 } }); @@ -216,6 +301,7 @@ describe('CalendlyIntegrationService connection lifecycle', () => { service.resolveScheduledStartTime('specialist-1', '/scheduled_events/1'), ).rejects.toBeDefined(); expect(prisma.calendlyConnection.update).not.toHaveBeenCalled(); + expect(prisma.calendlyConnection.updateMany).not.toHaveBeenCalled(); }); }); diff --git a/backend/src/features/appointments/calendly-integration.service.ts b/backend/src/features/appointments/calendly-integration.service.ts index b1aa3f2..901d71e 100644 --- a/backend/src/features/appointments/calendly-integration.service.ts +++ b/backend/src/features/appointments/calendly-integration.service.ts @@ -543,7 +543,8 @@ export class CalendlyIntegrationService { access_token_encrypted: string; refresh_token_encrypted: string; }> { - const refreshToken = this.decryptToken(connection.refresh_token_encrypted); + const refreshTokenEncrypted = connection.refresh_token_encrypted; + const refreshToken = this.decryptToken(refreshTokenEncrypted); const tokenUrl = process.env.CALENDLY_OAUTH_TOKEN_URL || @@ -573,8 +574,12 @@ export class CalendlyIntegrationService { data = response.data; } catch (error: any) { if (error?.response?.data?.error === 'invalid_grant') { - await this.prisma.calendlyConnection.update({ - where: { id: connection.id }, + await this.prisma.calendlyConnection.updateMany({ + where: { + id: connection.id, + refresh_token_encrypted: refreshTokenEncrypted, + is_active: true, + }, data: { is_active: false, last_error: 'invalid_grant' }, }); } From 1791c50c320fffc0d9c884fd1d621bd44dabfc4d Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 07:53:26 -0300 Subject: [PATCH 05/60] fix: authorize private user profile access --- .../src/features/users/dto/update-user.dto.ts | 2 +- .../features/users/users.controller.spec.ts | 108 +++++++++++++ .../src/features/users/users.controller.ts | 25 ++- .../src/features/users/users.service.spec.ts | 69 ++++++++ backend/src/features/users/users.service.ts | 11 ++ .../StartProcessForClientModal.test.tsx | 153 ++++++++++++++++++ .../processes/StartProcessForClientModal.tsx | 4 +- .../src/pages/catalog/ProductPage.test.tsx | 18 ++- frontend/src/pages/catalog/ProductPage.tsx | 6 +- .../src/services/specialists.service.test.ts | 34 +++- frontend/src/services/specialists.service.ts | 20 +++ 11 files changed, 434 insertions(+), 16 deletions(-) create mode 100644 backend/src/features/users/users.controller.spec.ts create mode 100644 frontend/src/components/processes/StartProcessForClientModal.test.tsx diff --git a/backend/src/features/users/dto/update-user.dto.ts b/backend/src/features/users/dto/update-user.dto.ts index a6c6a3a..edabb9c 100644 --- a/backend/src/features/users/dto/update-user.dto.ts +++ b/backend/src/features/users/dto/update-user.dto.ts @@ -62,5 +62,5 @@ export class UpdateUserDto { @MaxLength(255, { message: 'URL do Calendly deve ter no máximo 255 caracteres', }) - calendly_url?: string; + calendly_url?: string | null; } diff --git a/backend/src/features/users/users.controller.spec.ts b/backend/src/features/users/users.controller.spec.ts new file mode 100644 index 0000000..0ded0ba --- /dev/null +++ b/backend/src/features/users/users.controller.spec.ts @@ -0,0 +1,108 @@ +import { ForbiddenException } from '@nestjs/common'; +import { GUARDS_METADATA } from '@nestjs/common/constants'; +import { UserRole } from '@prisma/client'; +import { AuthGuard } from 'src/auth/auth.guard'; +import { IS_PUBLIC_KEY } from 'src/shared/decorators/public.decorator'; +import { UsersController } from './users.controller'; + +const targetId = '11111111-1111-4111-8111-111111111111'; +const outsiderId = '22222222-2222-4222-8222-222222222222'; + +function setup() { + const service = { + getById: jest + .fn() + .mockResolvedValue({ id: targetId, phone: '11987654321' }), + update: jest.fn().mockResolvedValue({ id: targetId, name: 'Novo' }), + }; + return { service, controller: new UsersController(service as any) }; +} + +describe('UsersController private profile authorization', () => { + it('rejects editing another user before service access', async () => { + const { controller, service } = setup(); + await expect( + (controller.update as any)( + targetId, + { name: 'Novo' }, + { + user: { id: outsiderId, role: UserRole.CUSTOMER }, + }, + ), + ).rejects.toThrow(ForbiddenException); + expect(service.update).not.toHaveBeenCalled(); + }); + it('requires authentication on both profile routes', () => { + for (const method of [ + UsersController.prototype.getById, + UsersController.prototype.update, + ]) { + expect(Reflect.getMetadata(IS_PUBLIC_KEY, method)).not.toBe(true); + expect(Reflect.getMetadata(GUARDS_METADATA, method)).toContain(AuthGuard); + } + }); + + it.each([ + UserRole.CUSTOMER, + UserRole.SPECIALIST, + UserRole.CONSULTANT, + UserRole.OFFICE, + ])( + 'rejects reading and editing another user as %s before service access', + async (role) => { + const { controller, service } = setup(); + const request = { user: { id: outsiderId, role } }; + await expect( + (controller.getById as any)(targetId, request), + ).rejects.toThrow(ForbiddenException); + await expect( + (controller.update as any)(targetId, { name: 'Novo' }, request), + ).rejects.toThrow(ForbiddenException); + expect(service.getById).not.toHaveBeenCalled(); + expect(service.update).not.toHaveBeenCalled(); + }, + ); + + it.each([undefined, {}, { user: null }, { user: {} }])( + 'fails closed when the authenticated actor is missing: %p', + async (request) => { + const { controller, service } = setup(); + await expect( + (controller.getById as any)(targetId, request), + ).rejects.toThrow(ForbiddenException); + await expect( + (controller.update as any)(targetId, { name: 'Novo' }, request), + ).rejects.toThrow(ForbiddenException); + expect(service.getById).not.toHaveBeenCalled(); + expect(service.update).not.toHaveBeenCalled(); + }, + ); + + it.each([ + { id: targetId, role: UserRole.CUSTOMER }, + { id: targetId, role: UserRole.SPECIALIST }, + { id: outsiderId, role: UserRole.ADMIN }, + ])( + 'preserves private read/update response envelopes for %p', + async (user) => { + const { controller, service } = setup(); + const dto = { name: 'Novo' }; + await expect( + (controller.getById as any)(targetId, { user }), + ).resolves.toEqual({ + success: true, + message: 'Usuário obtido com sucesso', + data: { id: targetId, phone: '11987654321' }, + }); + await expect( + (controller.update as any)(targetId, dto, { user }), + ).resolves.toEqual({ + success: true, + message: 'Usuário atualizado com sucesso', + data: { id: targetId, name: 'Novo' }, + }); + expect(service.getById).toHaveBeenCalledWith(targetId); + expect(service.update).toHaveBeenCalledWith(targetId, dto); + }, + ); +}); diff --git a/backend/src/features/users/users.controller.ts b/backend/src/features/users/users.controller.ts index 1771ff5..d35c559 100644 --- a/backend/src/features/users/users.controller.ts +++ b/backend/src/features/users/users.controller.ts @@ -7,17 +7,26 @@ import { Body, ParseUUIDPipe, UseGuards, + Req, + ForbiddenException, } from '@nestjs/common'; import { UsersService } from './users.service'; import { GetUsersDto } from './dto/get-users.dto'; import { UpdateUserDto } from './dto/update-user.dto'; import { AuthGuard } from 'src/auth/auth.guard'; -import { Public } from 'src/shared/decorators/public.decorator'; +import { UserRole } from '@prisma/client'; +import { UserEntity } from 'src/auth/entities/user.entity'; @Controller('users') export class UsersController { constructor(private readonly usersService: UsersService) {} + private assertSelfOrAdmin(targetId: string, actor?: UserEntity): void { + if (!actor?.id || (actor.id !== targetId && actor.role !== UserRole.ADMIN)) { + throw new ForbiddenException('Acesso não autorizado'); + } + } + /** * DESATIVADA — GET /api/users (listagem) * @@ -32,7 +41,7 @@ export class UsersController { * * Comentada em vez de apagada: se a listagem voltar, ela precisa nascer * escopada por papel — o ADMIN tem visão global legítima, os demais não. - * Note que GET /api/users/:id (abaixo) continua ativa e é @Public(). + * GET /api/users/:id (abaixo) exige autenticação e acesso self ou ADMIN. */ // /** // * GET /api/users @@ -57,13 +66,17 @@ export class UsersController { /** * GET /api/users/:id - * Get a single user by ID (public - used for specialist info on product pages) + * Get a private user profile (self or ADMIN) * @param userId - The ID of the user (UUID) * @returns User data with full details */ @Get(':id') - @Public() - async getById(@Param('id', new ParseUUIDPipe()) userId: string) { + @UseGuards(AuthGuard) + async getById( + @Param('id', new ParseUUIDPipe()) userId: string, + @Req() req: { user?: UserEntity }, + ) { + this.assertSelfOrAdmin(userId, req?.user); const user = await this.usersService.getById(userId); return { @@ -93,7 +106,9 @@ export class UsersController { async update( @Param('id', new ParseUUIDPipe()) userId: string, @Body() updateUserDto: UpdateUserDto, + @Req() req: { user?: UserEntity }, ) { + this.assertSelfOrAdmin(userId, req?.user); const updatedUser = await this.usersService.update(userId, updateUserDto); return { diff --git a/backend/src/features/users/users.service.spec.ts b/backend/src/features/users/users.service.spec.ts index 095a58b..dc04956 100644 --- a/backend/src/features/users/users.service.spec.ts +++ b/backend/src/features/users/users.service.spec.ts @@ -1,5 +1,9 @@ import { UsersService } from './users.service'; import { UpdateUserDto } from './dto/update-user.dto'; +import { ForbiddenException } from '@nestjs/common'; +import { UserRole } from '@prisma/client'; +import { plainToInstance } from 'class-transformer'; +import { validate } from 'class-validator'; const userId = '11111111-1111-4111-8111-111111111111'; @@ -82,3 +86,68 @@ describe('UsersService — telefone no perfil', () => { expect(semCampo.update.mock.calls[0][0].data).not.toHaveProperty('phone'); }); }); + +describe('UsersService — Calendly no perfil', () => { + it.each([ + UserRole.CUSTOMER, + UserRole.CONSULTANT, + UserRole.OFFICE, + UserRole.ADMIN, + ])( + 'rejects non-null Calendly URLs for target role %s before writing', + async (role) => { + const { service, findUnique, update } = mkService(); + findUnique.mockResolvedValue({ id: userId, role }); + await expect( + service.update(userId, { calendly_url: 'https://calendly.com/ana' }), + ).rejects.toThrow(ForbiddenException); + expect(update).not.toHaveBeenCalled(); + expect(findUnique).toHaveBeenCalledTimes(1); + }, + ); + + it('saves a specialist URL and preserves the private response projection', async () => { + const { service, findUnique, update } = mkService(); + findUnique.mockResolvedValue({ id: userId, role: UserRole.SPECIALIST }); + await service.update(userId, { + calendly_url: ' https://calendly.com/ana ', + }); + expect(update).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + calendly_url: 'https://calendly.com/ana', + }), + select: expect.objectContaining({ phone: true, calendly_url: true }), + }), + ); + }); + + it.each([null, '', ' '])( + 'clears a specialist URL with %p', + async (calendly_url) => { + const { service, findUnique, update } = mkService(); + findUnique.mockResolvedValue({ id: userId, role: UserRole.SPECIALIST }); + await service.update(userId, { calendly_url }); + expect(update.mock.calls[0][0].data.calendly_url).toBeNull(); + }, + ); + + it('allows explicit null removal for a non-specialist but leaves absent URLs untouched', async () => { + const removal = mkService(); + await removal.service.update(userId, { calendly_url: null }); + expect(removal.update.mock.calls[0][0].data.calendly_url).toBeNull(); + const unchanged = mkService(); + await unchanged.service.update(userId, { name: 'Novo' }); + expect(unchanged.update.mock.calls[0][0].data).not.toHaveProperty( + 'calendly_url', + ); + }); + + it.each([null, 'https://calendly.com/ana'])( + 'DTO accepts Calendly value %p', + async (calendly_url) => { + const dto = plainToInstance(UpdateUserDto, { calendly_url }); + expect(await validate(dto)).toEqual([]); + }, + ); +}); diff --git a/backend/src/features/users/users.service.ts b/backend/src/features/users/users.service.ts index 57f427d..88669c4 100644 --- a/backend/src/features/users/users.service.ts +++ b/backend/src/features/users/users.service.ts @@ -2,11 +2,13 @@ import { Injectable, NotFoundException, ConflictException, + ForbiddenException, } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { GetUsersDto } from './dto/get-users.dto'; import { UpdateUserDto } from './dto/update-user.dto'; import { UserResponse } from './entity/user.response'; +import { UserRole } from '@prisma/client'; @Injectable() export class UsersService { @@ -173,6 +175,15 @@ export class UsersService { throw new NotFoundException(`Usuário com id ${userId} não encontrado`); } + if ( + updateUserDto.calendly_url != null && + existingUser.role !== UserRole.SPECIALIST + ) { + throw new ForbiddenException( + 'Somente especialistas podem definir uma URL do Calendly', + ); + } + // Verificar CPF duplicado (se estiver sendo atualizado) if (updateUserDto.cpf && updateUserDto.cpf !== existingUser.cpf) { const cpfExists = await this.prisma.user.findUnique({ diff --git a/frontend/src/components/processes/StartProcessForClientModal.test.tsx b/frontend/src/components/processes/StartProcessForClientModal.test.tsx new file mode 100644 index 0000000..e9c84f7 --- /dev/null +++ b/frontend/src/components/processes/StartProcessForClientModal.test.tsx @@ -0,0 +1,153 @@ +// @vitest-environment jsdom + +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import StartProcessForClientModal from "./StartProcessForClientModal"; +import { + getPublicSpecialistById, + type PublicSpecialistProfile, +} from "../../services/specialists.service"; +import { getUserById } from "../../services/users.service"; +import { + createConsultantProcess, + getClients, +} from "../../services/consultant.service"; +import { officeService } from "../../services/office"; + +vi.mock("../../services/specialists.service", () => ({ + getPublicSpecialistById: vi.fn(), +})); +vi.mock("../../services/users.service", () => ({ getUserById: vi.fn() })); +vi.mock("../../services/consultant.service", () => ({ + getClients: vi.fn(), + createConsultantProcess: vi.fn(), +})); +vi.mock("../../services/office", () => ({ + officeService: { listClients: vi.fn(), createProcess: vi.fn() }, +})); +vi.mock("../../services/appointments.service", () => ({ + registerCalendlyScheduledEvent: vi.fn(), + getCalendlySyncStatus: vi.fn(), +})); +vi.mock("react-calendly", () => ({ + useCalendlyEventListener: vi.fn(), + PopupModal: ({ url }: { url: string }) => Calendly popup, +})); + +const client = { + id: "client-1", + name: "Cliente", + surname: "Teste", + email: "cliente@example.com", +}; +const publicProfile: PublicSpecialistProfile = { + id: "specialist-1", + name: "Ana", + surname: "Silva", + email: "ana@example.com", + speciality: "CAR", + calendly_url: "https://calendly.com/ana", + calendly_scheduling_available: true, +}; + +function renderModal(mode: "CONSULTANT" | "OFFICE") { + render( + + + + } + /> + Processos do consultor} + /> + Processos do escritório} + /> + + , + ); +} + +describe("StartProcessForClientModal public specialist display", () => { + beforeEach(() => { + vi.mocked(getClients).mockResolvedValue([client] as never); + vi.mocked(officeService.listClients).mockResolvedValue([client] as never); + vi.mocked(getPublicSpecialistById).mockResolvedValue(publicProfile); + vi.mocked(getUserById).mockResolvedValue(publicProfile as never); + const process = { + id: "process-1", + status: "SCHEDULING", + appointment_id: "appointment-1", + }; + vi.mocked(createConsultantProcess).mockResolvedValue(process); + vi.mocked(officeService.createProcess).mockResolvedValue(process); + }); + afterEach(() => { + cleanup(); + vi.clearAllMocks(); + }); + + it.each(["CONSULTANT", "OFFICE"] as const)( + "loads the public specialist profile in %s mode without private user access", + async (mode) => { + renderModal(mode); + await screen.findByRole("button", { name: /Cliente Teste/ }); + await waitFor(() => + expect(getPublicSpecialistById).toHaveBeenCalledWith("specialist-1"), + ); + expect(getUserById).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: /Cliente Teste/ })); + fireEvent.click(screen.getByRole("button", { name: "Criar processo" })); + const createProcess = + mode === "OFFICE" + ? officeService.createProcess + : createConsultantProcess; + await waitFor(() => + expect(createProcess).toHaveBeenCalledWith({ + client_id: "client-1", + specialist_id: "specialist-1", + product_type: "CAR", + product_id: "car-1", + }), + ); + expect( + ( + await screen.findByRole("link", { name: "Calendly popup" }) + ).getAttribute("href"), + ).toBe(publicProfile.calendly_url); + }, + ); + + it("preserves process creation when the public profile has no Calendly URL", async () => { + vi.mocked(getPublicSpecialistById).mockResolvedValue({ + ...publicProfile, + calendly_url: null, + calendly_scheduling_available: false, + }); + renderModal("CONSULTANT"); + fireEvent.click( + await screen.findByRole("button", { name: /Cliente Teste/ }), + ); + fireEvent.click(screen.getByRole("button", { name: "Criar processo" })); + expect(await screen.findByText("Processos do consultor")).toBeTruthy(); + expect(getUserById).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/components/processes/StartProcessForClientModal.tsx b/frontend/src/components/processes/StartProcessForClientModal.tsx index e724db7..84c91fe 100644 --- a/frontend/src/components/processes/StartProcessForClientModal.tsx +++ b/frontend/src/components/processes/StartProcessForClientModal.tsx @@ -3,7 +3,7 @@ import { useNavigate } from "react-router-dom"; import { PopupModal, useCalendlyEventListener } from "react-calendly"; import { getClients, createConsultantProcess, type Client } from "../../services/consultant.service"; import { officeService } from "../../services/office"; -import { getUserById } from "../../services/users.service"; +import { getPublicSpecialistById } from "../../services/specialists.service"; import { registerCalendlyScheduledEvent, getCalendlySyncStatus, @@ -84,7 +84,7 @@ export default function StartProcessForClientModal({ // Carrega o link do Calendly do especialista para permitir agendar a reunião useEffect(() => { - getUserById(specialistId) + getPublicSpecialistById(specialistId) .then((u) => setSpecialistCalendlyUrl(u.calendly_url)) .catch(() => setSpecialistCalendlyUrl(null)); }, [specialistId]); diff --git a/frontend/src/pages/catalog/ProductPage.test.tsx b/frontend/src/pages/catalog/ProductPage.test.tsx index 595dbe9..e675826 100644 --- a/frontend/src/pages/catalog/ProductPage.test.tsx +++ b/frontend/src/pages/catalog/ProductPage.test.tsx @@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import ProductPage from "./ProductPage"; import { getCarById } from "../../services/cars.service"; import { getUserById } from "../../services/users.service"; +import { getPublicSpecialistById, type PublicSpecialistProfile } from "../../services/specialists.service"; import { checkExistingAppointment, createPendingAppointment, @@ -16,6 +17,7 @@ vi.mock("../../services/cars.service", () => ({ getCarById: vi.fn() })); vi.mock("../../services/boats.service", () => ({ getBoatById: vi.fn() })); vi.mock("../../services/aircrafts.service", () => ({ getAircraftById: vi.fn() })); vi.mock("../../services/users.service", () => ({ getUserById: vi.fn() })); +vi.mock("../../services/specialists.service", () => ({ getPublicSpecialistById: vi.fn() })); vi.mock("../../services/processes.service", () => ({ getProcessesByClient: vi.fn().mockResolvedValue([]), })); @@ -74,13 +76,14 @@ const product = { updated_at: "2026-01-01T00:00:00.000Z", }; -const specialist = { +const specialist: PublicSpecialistProfile = { id: "specialist-1", name: "Especialista", surname: "Teste", email: "especialista@example.com", calendly_url: null, speciality: "CAR", + calendly_scheduling_available: false, }; const appointment = { @@ -112,6 +115,7 @@ function renderPage() { describe("ProductPage scheduling", () => { beforeEach(() => { vi.mocked(getCarById).mockResolvedValue(product); + vi.mocked(getPublicSpecialistById).mockResolvedValue(specialist); vi.mocked(getUserById).mockResolvedValue(specialist as never); vi.mocked(checkExistingAppointment).mockResolvedValue(null); vi.mocked(createPendingAppointment).mockResolvedValue({ @@ -122,16 +126,24 @@ describe("ProductPage scheduling", () => { vi.mocked(createPlatformAppointment).mockResolvedValue(appointment); }); + it("loads specialist contact through the public profile without private user access", async () => { + renderPage(); + expect(await screen.findByRole("link", { name: "especialista@example.com" })).toBeTruthy(); + expect(getPublicSpecialistById).toHaveBeenCalledWith("specialist-1"); + expect(getUserById).not.toHaveBeenCalled(); + }); + afterEach(() => { cleanup(); vi.clearAllMocks(); }); it("keeps Calendly as the only path when it is configured", async () => { - vi.mocked(getUserById).mockResolvedValue({ + vi.mocked(getPublicSpecialistById).mockResolvedValue({ ...specialist, calendly_url: "https://calendly.com/especialista", - } as never); + calendly_scheduling_available: true, + }); renderPage(); diff --git a/frontend/src/pages/catalog/ProductPage.tsx b/frontend/src/pages/catalog/ProductPage.tsx index 6835c56..4de1829 100644 --- a/frontend/src/pages/catalog/ProductPage.tsx +++ b/frontend/src/pages/catalog/ProductPage.tsx @@ -8,7 +8,7 @@ import { getAircraftById, type RawAircraft, } from "../../services/aircrafts.service"; -import { getUserById } from "../../services/users.service"; +import { getPublicSpecialistById } from "../../services/specialists.service"; import { checkExistingAppointment, createPendingAppointment, @@ -223,7 +223,9 @@ export default function ProductPage() { // Buscar dados do especialista se houver if (rawProduct.specialist_id) { try { - const specialistData = await getUserById(rawProduct.specialist_id); + const specialistData = await getPublicSpecialistById( + rawProduct.specialist_id, + ); setSpecialist({ id: specialistData.id, name: specialistData.name, diff --git a/frontend/src/services/specialists.service.test.ts b/frontend/src/services/specialists.service.test.ts index 38a458f..760bdf5 100644 --- a/frontend/src/services/specialists.service.test.ts +++ b/frontend/src/services/specialists.service.test.ts @@ -1,9 +1,35 @@ -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import api from "./api"; +import * as specialistService from "./specialists.service"; import type { CreateSpecialistData, UpdateSpecialistData, } from "./specialists.service"; +vi.mock("./api", () => ({ default: { get: vi.fn() } })); + +afterEach(() => vi.clearAllMocks()); + +describe("public specialist profile", () => { + it("loads the raw public projection through its dedicated endpoint", async () => { + const profile = { + id: "specialist-1", + name: "Ana", + surname: "Silva", + email: "ana@example.com", + speciality: "CAR", + calendly_url: null, + calendly_scheduling_available: false, + }; + vi.mocked(api.get).mockResolvedValue({ data: profile }); + const getProfile = specialistService.getPublicSpecialistById; + await expect(getProfile(profile.id)).resolves.toEqual(profile); + expect(api.get).toHaveBeenCalledWith( + "/specialists/specialist-1/public-profile", + ); + }); +}); + const createBase = { name: "Ana", surname: "Silva", @@ -24,8 +50,10 @@ const createWithoutCommission: CreateSpecialistData = createBase; const partialUpdate: UpdateSpecialistData = { commission_rate: 0 }; -// @ts-expect-error Edições não podem introduzir comissão nula. -const updateWithNullCommission: UpdateSpecialistData = { commission_rate: null }; +const updateWithNullCommission: UpdateSpecialistData = { + // @ts-expect-error Edições não podem introduzir comissão nula. + commission_rate: null, +}; describe("specialists service type contracts", () => { it("mantém comissão obrigatória na criação e opcional no update", () => { diff --git a/frontend/src/services/specialists.service.ts b/frontend/src/services/specialists.service.ts index 4756754..8e4d929 100644 --- a/frontend/src/services/specialists.service.ts +++ b/frontend/src/services/specialists.service.ts @@ -27,6 +27,26 @@ export type GroupedSpecialists = { AIRCRAFT: Specialist[]; }; +// Projeção pública de contato comercial; não contém documentos ou dados OAuth. +export type PublicSpecialistProfile = { + id: string; + name: string; + surname: string; + email: string; + speciality: "CAR" | "BOAT" | "AIRCRAFT" | null; + calendly_url: string | null; + calendly_scheduling_available: boolean; +}; + +export async function getPublicSpecialistById( + id: string, +): Promise { + const { data } = await api.get( + `/specialists/${id}/public-profile`, + ); + return data; +} + // Tipo auxiliar para criação (DTO) export type CreateSpecialistData = { name: string; From 91f8696cd68dda37e7ee9af6956623ac194c5da6 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 08:10:15 -0300 Subject: [PATCH 06/60] feat: create dated email appointment requests safely --- .../appointment-schedule-lock.spec.ts | 220 ++++++ .../appointments/appointment-schedule-lock.ts | 57 +- .../appointments.controller.spec.ts | 104 +++ .../appointments/appointments.controller.ts | 145 +--- .../appointments/appointments.service.spec.ts | 439 +++++++++++- .../appointments/appointments.service.ts | 676 +++++------------- .../dto/check-existing-appointment.dto.ts | 13 + .../dto/create-pending-appointment.dto.ts | 20 +- .../src/features/appointments/dto/index.ts | 1 + .../entities/appointment.response.ts | 22 + .../processes/process-dedup-lock.spec.ts | 167 ++++- .../features/processes/process-dedup-lock.ts | 51 +- .../processes/processes.service.spec.ts | 29 +- 13 files changed, 1252 insertions(+), 692 deletions(-) create mode 100644 backend/src/features/appointments/appointment-schedule-lock.spec.ts create mode 100644 backend/src/features/appointments/appointments.controller.spec.ts create mode 100644 backend/src/features/appointments/dto/check-existing-appointment.dto.ts diff --git a/backend/src/features/appointments/appointment-schedule-lock.spec.ts b/backend/src/features/appointments/appointment-schedule-lock.spec.ts new file mode 100644 index 0000000..445c1a7 --- /dev/null +++ b/backend/src/features/appointments/appointment-schedule-lock.spec.ts @@ -0,0 +1,220 @@ +import { ConflictException } from '@nestjs/common'; +import { + AppointmentSchedulingMethod, + CalendlySyncStatus, + StatusAgendamento, +} from '@prisma/client'; +import * as scheduleLock from './appointment-schedule-lock'; + +describe('specialist schedule occupation', () => { + const when = new Date('2099-01-01T10:00:00.000Z'); + const hour = 60 * 60 * 1000; + + // Evaluate the Prisma filter at the storage boundary so availability tests + // exercise the actual query produced by the domain helper. + function matches(record: any, where: any): boolean { + return Object.entries(where).every(([key, value]: [string, any]) => { + if (key === 'OR') + return value.some((branch: any) => matches(record, branch)); + if (key === 'appointment_datetime') { + return ( + record[key] !== null && + record[key] >= value.gte && + record[key] <= value.lte + ); + } + if (value && typeof value === 'object') { + if ('not' in value) return record[key] !== value.not; + if ('in' in value) return value.in.includes(record[key]); + } + return record[key] === value; + }); + } + + function transaction(record: any) { + return { + appointment: { + findFirst: jest.fn(async ({ where }) => + matches(record, where) ? record : null, + ), + }, + }; + } + + const occupied = { + id: 'competing-appointment', + client_id: 'competing-client', + process_id: 'competing-process', + specialist_id: 's1', + status: StatusAgendamento.SCHEDULED, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + calendly_sync_status: CalendlySyncStatus.PENDING, + appointment_datetime: when, + }; + + it('builds one occupation predicate with the original inclusive one-hour window', () => { + expect( + (scheduleLock as any).buildOccupiedScheduleWhere('s1', when), + ).toEqual({ + specialist_id: 's1', + appointment_datetime: { + gte: new Date(when.getTime() - hour), + lte: new Date(when.getTime() + hour), + }, + OR: [ + { status: StatusAgendamento.SCHEDULED }, + { + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + calendly_sync_status: CalendlySyncStatus.SYNCED, + }, + { status: StatusAgendamento.PENDING, scheduling_method: null }, + ], + }); + }); + + it.each([-hour, hour])( + 'conflicts at the inclusive boundary %i ms', + async (offset) => { + const tx = transaction({ + ...occupied, + appointment_datetime: new Date(when.getTime() + offset), + }); + await expect( + scheduleLock.assertSpecialistScheduleAvailable(tx, 's1', when), + ).rejects.toThrow(ConflictException); + }, + ); + + it.each([-hour - 1, hour + 1])( + 'allows one millisecond outside the boundary %i ms', + async (offset) => { + const tx = transaction({ + ...occupied, + appointment_datetime: new Date(when.getTime() + offset), + }); + await expect( + scheduleLock.assertSpecialistScheduleAvailable(tx, 's1', when), + ).resolves.toBeUndefined(); + }, + ); + + it.each([ + [AppointmentSchedulingMethod.EMAIL, CalendlySyncStatus.PENDING], + [AppointmentSchedulingMethod.EMAIL, CalendlySyncStatus.SYNCED], + [AppointmentSchedulingMethod.CALENDLY, CalendlySyncStatus.PENDING], + [AppointmentSchedulingMethod.CALENDLY, CalendlySyncStatus.FAILED], + ])( + 'does not reserve a pending %s request with sync %s', + async (method, sync) => { + const tx = transaction({ + ...occupied, + status: StatusAgendamento.PENDING, + scheduling_method: method, + calendly_sync_status: sync, + }); + await expect( + scheduleLock.assertSpecialistScheduleAvailable(tx, 's1', when), + ).resolves.toBeUndefined(); + }, + ); + + it.each([ + [AppointmentSchedulingMethod.CALENDLY, CalendlySyncStatus.SYNCED], + [null, CalendlySyncStatus.PENDING], + ])( + 'reserves synced Calendly and legacy dated pending requests: %s', + async (method, sync) => { + const tx = transaction({ + ...occupied, + status: StatusAgendamento.PENDING, + scheduling_method: method, + calendly_sync_status: sync, + }); + await expect( + scheduleLock.assertSpecialistScheduleAvailable(tx, 's1', when), + ).rejects.toThrow(ConflictException); + }, + ); + + it.each([StatusAgendamento.COMPLETED, StatusAgendamento.CANCELLED])( + 'does not reserve a %s appointment', + async (status) => { + await expect( + scheduleLock.assertSpecialistScheduleAvailable( + transaction({ ...occupied, status }), + 's1', + when, + ), + ).resolves.toBeUndefined(); + }, + ); + + it('does not reserve undated legacy pending requests or another specialist', async () => { + await expect( + scheduleLock.assertSpecialistScheduleAvailable( + transaction({ + ...occupied, + status: StatusAgendamento.PENDING, + scheduling_method: null, + appointment_datetime: null, + }), + 's1', + when, + ), + ).resolves.toBeUndefined(); + await expect( + scheduleLock.assertSpecialistScheduleAvailable( + transaction({ ...occupied, specialist_id: 's2' }), + 's1', + when, + ), + ).resolves.toBeUndefined(); + }); + + it('excludes the appointment being updated', async () => { + await expect( + scheduleLock.assertSpecialistScheduleAvailable( + transaction(occupied), + 's1', + when, + occupied.id, + ), + ).resolves.toBeUndefined(); + }); + + it('does not query availability for an absent datetime', async () => { + const tx = transaction(occupied); + await expect( + scheduleLock.assertSpecialistScheduleAvailable(tx, 's1', null), + ).resolves.toBeUndefined(); + expect(tx.appointment.findFirst).not.toHaveBeenCalled(); + }); + + it('returns a conflict without competing appointment, client or process identities', async () => { + const tx = transaction(occupied); + const error = await scheduleLock + .assertSpecialistScheduleAvailable(tx, 's1', when) + .catch((caught) => caught); + expect(error).toBeInstanceOf(ConflictException); + expect(error.getResponse()).toEqual({ + success: false, + error: { + code: 409, + message: expect.any(String), + details: { suggested_times: expect.any(Array) }, + }, + }); + const response = JSON.stringify(error.getResponse()); + for (const identity of [ + occupied.id, + occupied.client_id, + occupied.process_id, + ]) { + expect(response).not.toContain(identity); + } + expect(tx.appointment.findFirst).toHaveBeenCalledWith( + expect.objectContaining({ select: { id: true } }), + ); + }); +}); diff --git a/backend/src/features/appointments/appointment-schedule-lock.ts b/backend/src/features/appointments/appointment-schedule-lock.ts index 5a2d6cc..b2ebf86 100644 --- a/backend/src/features/appointments/appointment-schedule-lock.ts +++ b/backend/src/features/appointments/appointment-schedule-lock.ts @@ -1,6 +1,36 @@ import { ConflictException } from '@nestjs/common'; -import { StatusAgendamento } from '@prisma/client'; -import { formatToISO, suggestNextAvailableSlots } from 'src/shared/utils/date.utils'; +import { + AppointmentSchedulingMethod, + CalendlySyncStatus, + Prisma, + StatusAgendamento, +} from '@prisma/client'; +import { suggestNextAvailableSlots } from 'src/shared/utils/date.utils'; + +export function buildOccupiedScheduleWhere( + specialistId: string, + appointmentDateTime: Date, + excludeAppointmentId?: string, +): Prisma.AppointmentWhereInput { + const hour = 60 * 60 * 1000; + return { + specialist_id: specialistId, + ...(excludeAppointmentId ? { id: { not: excludeAppointmentId } } : {}), + appointment_datetime: { + gte: new Date(appointmentDateTime.getTime() - hour), + lte: new Date(appointmentDateTime.getTime() + hour), + }, + OR: [ + { status: StatusAgendamento.SCHEDULED }, + { + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + calendly_sync_status: CalendlySyncStatus.SYNCED, + }, + { status: StatusAgendamento.PENDING, scheduling_method: null }, + ], + }; +} export async function acquireSpecialistScheduleLock( tx: any, @@ -19,17 +49,13 @@ export async function assertSpecialistScheduleAvailable( excludeAppointmentId?: string, ): Promise { if (!appointmentDateTime) return; - const conflictStart = new Date(appointmentDateTime.getTime() - 60 * 60 * 1000); - const conflictEnd = new Date(appointmentDateTime.getTime() + 60 * 60 * 1000); const existing = await tx.appointment.findFirst({ - where: { - specialist_id: specialistId, - ...(excludeAppointmentId ? { id: { not: excludeAppointmentId } } : {}), - appointment_datetime: { gte: conflictStart, lte: conflictEnd }, - status: { - in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], - }, - }, + where: buildOccupiedScheduleWhere( + specialistId, + appointmentDateTime, + excludeAppointmentId, + ), + select: { id: true }, }); if (!existing) return; @@ -39,13 +65,6 @@ export async function assertSpecialistScheduleAvailable( code: 409, message: 'Especialista já possui agendamento neste horário', details: { - conflicting_appointment: { - id: existing.id, - appointment_datetime: existing.appointment_datetime - ? formatToISO(existing.appointment_datetime) - : null, - client_id: existing.client_id, - }, suggested_times: suggestNextAvailableSlots(appointmentDateTime, 3), }, }, diff --git a/backend/src/features/appointments/appointments.controller.spec.ts b/backend/src/features/appointments/appointments.controller.spec.ts new file mode 100644 index 0000000..40b36fb --- /dev/null +++ b/backend/src/features/appointments/appointments.controller.spec.ts @@ -0,0 +1,104 @@ +import { + BadRequestException, + ForbiddenException, + ValidationPipe, +} from '@nestjs/common'; +import { + AppointmentSchedulingMethod, + ProductType, + StatusAgendamento, + UserRole, +} from '@prisma/client'; +import { AppointmentsController } from './appointments.controller'; + +describe('AppointmentsController own request check', () => { + const query = { + specialist_id: '33333333-3333-4333-8333-333333333333', + product_type: ProductType.CAR, + product_id: '11111111-1111-4111-8111-111111111111', + }; + const request = { user: { id: 'customer-1', role: UserRole.CUSTOMER } }; + const snapshot = { + exists: true, + appointment_id: 'appointment-1', + process_id: 'process-1', + appointment_status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + }; + function harness(data: any = snapshot) { + const service = { + findExistingAppointment: jest.fn().mockResolvedValue(data), + }; + return { service, controller: new AppointmentsController(service as any) }; + } + + it('derives the customer exclusively from JWT and returns the minimal contract', async () => { + const { controller, service } = harness(); + expect( + await controller.checkExisting( + { ...query, client_id: 'another-customer' } as any, + request, + ), + ).toEqual({ + success: true, + message: 'Consulta realizada com sucesso', + data: snapshot, + }); + expect(service.findExistingAppointment).toHaveBeenCalledWith( + request.user.id, + query.specialist_id, + query.product_type, + query.product_id, + ); + }); + + it('returns the absent discriminant', async () => { + const { controller } = harness({ exists: false }); + expect(await controller.checkExisting(query, request)).toEqual({ + success: true, + message: 'Consulta realizada com sucesso', + data: { exists: false }, + }); + }); + + it.each([ + UserRole.SPECIALIST, + UserRole.ADMIN, + UserRole.OFFICE, + UserRole.CONSULTANT, + ])('denies %s before invoking the service', async (role) => { + const { controller, service } = harness(); + await expect( + controller.checkExisting(query, { user: { id: 'outsider', role } }), + ).rejects.toThrow(ForbiddenException); + expect(service.findExistingAppointment).not.toHaveBeenCalled(); + }); + + it('validates the query DTO and forbids client identity at the HTTP boundary', async () => { + const [queryType] = Reflect.getMetadata( + 'design:paramtypes', + AppointmentsController.prototype, + 'checkExisting', + ); + expect(queryType.name).toBe('CheckExistingAppointmentDto'); + const pipe = new ValidationPipe({ + whitelist: true, + forbidNonWhitelisted: true, + transform: true, + }); + const metadata = { type: 'query' as const, metatype: queryType }; + await expect(pipe.transform(query, metadata)).resolves.toMatchObject(query); + for (const invalid of [ + { ...query, client_id: request.user.id }, + { ...query, specialist_id: 'bad-uuid' }, + { ...query, product_type: 'OTHER' }, + { ...query, product_id: 'bad-uuid' }, + { specialist_id: query.specialist_id }, + ]) { + await expect(pipe.transform(invalid, metadata)).rejects.toThrow( + BadRequestException, + ); + } + }); +}); diff --git a/backend/src/features/appointments/appointments.controller.ts b/backend/src/features/appointments/appointments.controller.ts index c5de542..798896c 100644 --- a/backend/src/features/appointments/appointments.controller.ts +++ b/backend/src/features/appointments/appointments.controller.ts @@ -11,10 +11,12 @@ import { UseGuards, Request, HttpStatus, + ForbiddenException, } from '@nestjs/common'; import { AppointmentsService } from './appointments.service'; import { CreatePendingAppointmentDto, + CheckExistingAppointmentDto, CreatePlatformAppointmentDto, CalendlyScheduledDto, GetAppointmentsQueryDto, @@ -25,6 +27,7 @@ import { AuthGuard } from 'src/auth/auth.guard'; import { AppointmentResponseEntity } from './entities/appointment.response'; import { UserEntity } from 'src/auth/entities/user.entity'; import { ConfirmProcessAppointmentDto } from 'src/features/processes/dto/confirm-process-appointment.dto'; +import { UserRole } from '@prisma/client'; /** * AppointmentsController @@ -115,50 +118,24 @@ export class AppointmentsController { /** * GET /api/appointments/check * - * Verifica se existe agendamento SCHEDULED entre cliente e especialista para um produto específico - * Usado para impedir agendamentos duplicados e condicionalmente exibir botão de confirmação - * - * Query Parameters (todos obrigatórios): - * - client_id: UUID do cliente - * - specialist_id: UUID do especialista - * - product_type: CAR | BOAT | AIRCRAFT - * - product_id: ID numérico do produto - * - * Respostas esperadas: - * - 200 OK: Retorna null se não encontrado, ou Appointment se existe - * - 400 Bad Request: Parâmetros inválidos ou ausentes - * - 401 Unauthorized: Token JWT inválido - * - * Exemplo de resposta 200 (sem agendamento): - * { - * "success": true, - * "message": "Agendamento não encontrado", - * "data": null - * } - * - * Exemplo de resposta 200 (com agendamento): - * { - * "success": true, - * "message": "Agendamento encontrado", - * "data": { - * "id": "uuid", - * "appointment_datetime": "2024-10-10T14:00:00Z", - * "status": "SCHEDULED", - * "created_at": "2024-10-08T14:30:00Z" - * } - * } - * - * Frontend: - * - Usar este endpoint ao carregar ProductPage - * - Se retorna dados: Mostrar "Você já possui um agendamento marcado" - * - Se retorna null: Mostrar botão de confirmação normalmente + * Consulta o próprio pedido do cliente autenticado para especialista/produto. + * Aceita specialist_id, product_type e product_id; o cliente vem do JWT. + * Retorna somente o discriminante e o snapshot mínimo, sem contatos pessoais. */ @Get('check') - async checkExisting(@Query() query: any, @Request() req: any) { - const { client_id, specialist_id, product_type, product_id } = query; + async checkExisting( + @Query() query: CheckExistingAppointmentDto, + @Request() req: any, + ) { + if (req.user.role !== UserRole.CUSTOMER) { + throw new ForbiddenException( + 'Apenas clientes podem consultar seus pedidos', + ); + } + const { specialist_id, product_type, product_id } = query; const appointment = await this.appointmentsService.findExistingAppointment( - client_id, + req.user.id, specialist_id, product_type, product_id, @@ -166,9 +143,7 @@ export class AppointmentsController { return { success: true, - message: appointment - ? 'Agendamento encontrado' - : 'Agendamento não encontrado', + message: 'Consulta realizada com sucesso', data: appointment, }; } @@ -185,68 +160,8 @@ export class AppointmentsController { /** * POST /api/appointments * - * Cria novo agendamento e auto-cria Process vinculado - * - * Request Body: - * { - * "client_id": "uuid-cliente", - * "specialist_id": "uuid-especialista", - * "product_type": "CAR", - * "product_id": 1, - * "appointment_datetime": "2024-10-10T14:00:00Z", - * "notes": "Test drive" - * } - * - * Respostas esperadas: - * - 201 Created: Agendamento criado com sucesso - * - 400 Bad Request: Dados inválidos, appointment_datetime no passado, etc - * - 409 Conflict: Conflito de horário (especialista já agendado) - * - 404 Not Found: Cliente, especialista ou produto não encontrado - * - 401 Unauthorized: Token JWT inválido - * - * Exemplo de resposta 201: - * { - * "success": true, - * "message": "Agendamento criado com sucesso", - * "data": { - * "id": "uuid", - * "appointment_datetime": "2024-10-10T14:00:00Z", - * "status": "SCHEDULED", - * "notes": "Test drive", - * "client": { "id", "name" }, - * "specialist": { "id", "name" }, - * "product": { "id": 1, "marca": "Ferrari", "modelo": "F8" }, - * "created_at": "2024-10-08T14:30:00Z" - * } - * } - * - * Exemplo de resposta 409 (conflito): - * { - * "success": false, - * "error": { - * "code": 409, - * "message": "Especialista já possui agendamento neste horário", - * "details": { - * "conflicting_appointment": { - * "id": "uuid", - * "appointment_datetime": "2024-10-10T14:00:00Z", - * "client_id": "uuid" - * }, - * "suggested_times": [ - * "2024-10-10T15:00:00Z", - * "2024-10-10T16:00:00Z", - * "2024-10-10T17:00:00Z" - * ] - * } - * } - * } - * - * Frontend: - * - Capturar 409 e exibir suggested_times ao usuário - * - Converter suggested_times de UTC para horário local para exibição - * - appointment_datetime enviado deve estar em UTC (converter do input local) - * - Após sucesso (201), redirecionare para página de confirmação - * - Auto-criação de Process é transparente (não precisa de ação adicional) + * A criação direta PLATFORM está desativada. Solicitações de reunião devem + * usar POST /appointments/pending e aguardar a confirmação do especialista. */ @Post() async create( @@ -422,23 +337,9 @@ export class AppointmentsController { /** * POST /api/appointments/pending * - * Cria um agendamento em status PENDING - * Usado quando cliente clica no link do Calendly e retorna à plataforma - * NÃO cria Process ainda - apenas registra intenção do cliente - * - * Request Body: - * { - * "client_id": "uuid-cliente", - * "specialist_id": "uuid-especialista", - * "product_type": "CAR", - * "product_id": 1, - * "notes": "Acessei o calendário do especialista" - * } - * - * Respostas: - * - 201 Created: Agendamento PENDING criado - * - 409 Conflict: Já existe agendamento PENDING ou SCHEDULED - * - 403 Forbidden: Apenas o próprio cliente pode criar + * Cria Appointment PENDING e Process SCHEDULING na mesma transação. + * EMAIL com produto exige uma proposta futura; CALENDLY não aceita horário + * do cliente. Retorna o appointment e seu process_id. */ @Post('pending') async createPending( diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts index 184f125..96a6576 100644 --- a/backend/src/features/appointments/appointments.service.spec.ts +++ b/backend/src/features/appointments/appointments.service.spec.ts @@ -60,9 +60,21 @@ describe('CreateAppointmentDto — seleção de produto', () => { true, ); }); + + it('validates an optional pending datetime as ISO 8601', async () => { + const dto = Object.assign(new CreatePendingAppointmentDto(), base, { + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: 'not-a-date', + }); + expect( + (await validate(dto)).some( + (error) => error.property === 'appointment_datetime', + ), + ).toBe(true); + }); }); -describe('AppointmentsService.create — associação e atomicidade', () => { +describe('AppointmentsService.createPending — associação e atomicidade', () => { const client = { id: 'client-1', name: 'Cliente', @@ -91,13 +103,19 @@ describe('AppointmentsService.create — associação e atomicidade', () => { product_type: ProductType.CAR, product_id: activeProduct.id, appointment_datetime: '2099-01-01T10:00:00.000Z', - } as CreateAppointmentDto; + scheduling_method: AppointmentSchedulingMethod.EMAIL, + } as CreatePendingAppointmentDto; function harness(options: { transactionalProduct?: typeof activeProduct; processFailure?: Error; + historyFailure?: Error; + calendlyUrl?: string | null; + connectionActive?: boolean; + existingProcess?: any; }) { const storedAppointments: any[] = []; + const storedProcesses: any[] = []; const appointmentCreate = jest.fn(async ({ data }) => { const appointment = { id: 'appointment-1', @@ -110,11 +128,24 @@ describe('AppointmentsService.create — associação e atomicidade', () => { }); const processCreate = jest.fn(async () => { if (options.processFailure) throw options.processFailure; - return { id: 'process-1' }; + const process = { id: 'process-1' }; + storedProcesses.push(process); + return process; }); - const historyCreate = jest.fn().mockResolvedValue({}); + const historyCreate = jest.fn(async () => { + if (options.historyFailure) throw options.historyFailure; + return {}; + }); + const selectedSpecialist = { + ...specialist, + calendly_url: options.calendlyUrl ?? null, + calendly_connection: + options.connectionActive === undefined + ? null + : { is_active: options.connectionActive }, + }; const userFindUnique = jest.fn(async ({ where }) => - where.id === client.id ? client : specialist, + where.id === client.id ? client : selectedSpecialist, ); const rootProductFindUnique = jest.fn().mockResolvedValue(activeProduct); const rootAppointmentCreate = jest.fn(); @@ -134,7 +165,7 @@ describe('AppointmentsService.create — associação e atomicidade', () => { create: appointmentCreate, }, process: { - findFirst: jest.fn().mockResolvedValue(null), + findFirst: jest.fn().mockResolvedValue(options.existingProcess ?? null), create: processCreate, }, processStatusHistory: { create: historyCreate }, @@ -151,10 +182,12 @@ describe('AppointmentsService.create — associação e atomicidade', () => { process: { create: rootProcessCreate }, $transaction: jest.fn(async (callback) => { const before = storedAppointments.length; + const beforeProcesses = storedProcesses.length; try { return await callback(tx); } catch (error) { storedAppointments.splice(before); + storedProcesses.splice(beforeProcesses); throw error; } }), @@ -175,6 +208,7 @@ describe('AppointmentsService.create — associação e atomicidade', () => { rootAppointmentCreate, rootProcessCreate, storedAppointments, + storedProcesses, }; } @@ -196,7 +230,7 @@ describe('AppointmentsService.create — associação e atomicidade', () => { ); await expect( - service.create(dto as any, client.id, UserRole.CUSTOMER), + service.createPending(dto, client.id, UserRole.CUSTOMER), ).rejects.toThrow(expectedError); expect(prisma.$transaction).toHaveBeenCalledTimes(1); expect(tx.car.findUnique).toHaveBeenCalled(); @@ -218,7 +252,7 @@ describe('AppointmentsService.create — associação e atomicidade', () => { }); await expect( - service.create(dto as any, client.id, UserRole.CUSTOMER), + service.createPending(dto, client.id, UserRole.CUSTOMER), ).rejects.toBe(processFailure); expect(prisma.$transaction).toHaveBeenCalledTimes(1); expect(storedAppointments).toHaveLength(0); @@ -227,13 +261,13 @@ describe('AppointmentsService.create — associação e atomicidade', () => { }); it.each([UserRole.SPECIALIST, UserRole.CONSULTANT, UserRole.ADMIN])( - 'rejects direct scheduling by %s', + 'rejects pending requests by %s', async (role) => { const { service, appointmentCreate } = harness({}); - await expect( - (service.create as any)(dto, client.id, role), - ).rejects.toThrow(ForbiddenException); + await expect(service.createPending(dto, client.id, role)).rejects.toThrow( + ForbiddenException, + ); expect(appointmentCreate).not.toHaveBeenCalled(); }, ); @@ -242,24 +276,33 @@ describe('AppointmentsService.create — associação e atomicidade', () => { const { service, appointmentCreate } = harness({}); await expect( - (service.create as any)(dto, 'another-client', UserRole.CUSTOMER), + service.createPending(dto, 'another-client', UserRole.CUSTOMER), ).rejects.toThrow(ForbiddenException); expect(appointmentCreate).not.toHaveBeenCalled(); }); - it('stores direct scheduling as SCHEDULED and PLATFORM', async () => { + it('stores the proposed date as PENDING/EMAIL and returns the process ID', async () => { const { service, appointmentCreate, historyCreate } = harness({}); - await (service.create as any)(dto, client.id, UserRole.CUSTOMER); + const result = await service.createPending( + dto, + client.id, + UserRole.CUSTOMER, + ); expect(appointmentCreate).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ - status: StatusAgendamento.SCHEDULED, - scheduling_method: AppointmentSchedulingMethod.PLATFORM, + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date(dto.appointment_datetime!), }), }), ); + expect(result).toMatchObject({ + id: 'appointment-1', + process_id: 'process-1', + }); expect(historyCreate).toHaveBeenCalledWith({ data: expect.objectContaining({ processId: 'process-1', @@ -269,30 +312,23 @@ describe('AppointmentsService.create — associação e atomicidade', () => { }); }); - it('serializa a verificação e a inserção do horário por especialista', async () => { + it('does not lock or check schedule availability for an EMAIL proposal', async () => { const { service, tx } = harness({}); - await service.create(dto as any, client.id, UserRole.CUSTOMER); + await service.createPending(dto, client.id, UserRole.CUSTOMER); - expect(tx.$queryRaw).toHaveBeenCalledWith( - expect.anything(), + expect(tx.$queryRaw.mock.calls.map((call) => call[1])).not.toContain( 'appointment-schedule:specialist-1', ); - expect(tx.$queryRaw.mock.invocationCallOrder[0]).toBeLessThan( - tx.appointment.findFirst.mock.invocationCallOrder[0], - ); + expect(tx.appointment.findFirst).not.toHaveBeenCalled(); }); - it('rejects platform scheduling when no datetime is supplied', async () => { + it('requires a date for an EMAIL product request', async () => { const { service, tx, appointmentCreate } = harness({}); const withoutDate = { ...dto, appointment_datetime: undefined }; await expect( - (service.create as any)( - withoutDate as CreateAppointmentDto, - client.id, - UserRole.CUSTOMER, - ), + service.createPending(withoutDate, client.id, UserRole.CUSTOMER), ).rejects.toThrow(BadRequestException); expect(tx.appointment.findFirst).not.toHaveBeenCalled(); @@ -302,19 +338,348 @@ describe('AppointmentsService.create — associação e atomicidade', () => { it('serializa e repete a deduplicação do processo antes de criá-lo', async () => { const { service, tx } = harness({}); - await service.create(dto as any, client.id, UserRole.CUSTOMER); + await service.createPending(dto, client.id, UserRole.CUSTOMER); expect(tx.$queryRaw).toHaveBeenCalledWith( expect.anything(), 'process-dedup:client-1:specialist-1:CAR:product-1', ); - expect(tx.process.findFirst).toHaveBeenCalledWith({ - where: expect.objectContaining({ car_id: 'product-1' }), - }); + expect(tx.process.findFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ car_id: 'product-1' }), + }), + ); expect(tx.process.findFirst.mock.invocationCallOrder[0]).toBeLessThan( tx.process.create.mock.invocationCallOrder[0], ); }); + + it.each(['not-a-date', '2000-01-01T00:00:00.000Z'])( + 'rejects an invalid or past product EMAIL date %s', + async (datetime) => { + const { service, appointmentCreate } = harness({}); + await expect( + service.createPending( + { ...dto, appointment_datetime: datetime }, + client.id, + UserRole.CUSTOMER, + ), + ).rejects.toThrow(BadRequestException); + expect(appointmentCreate).not.toHaveBeenCalled(); + }, + ); + + it('rolls back appointment and process when history insertion fails', async () => { + const historyFailure = new Error('history insert failed'); + const { service, storedAppointments, storedProcesses } = harness({ + historyFailure, + }); + await expect( + service.createPending(dto, client.id, UserRole.CUSTOMER), + ).rejects.toBe(historyFailure); + expect(storedAppointments).toHaveLength(0); + expect(storedProcesses).toHaveLength(0); + }); + + it.each([ + [null, false, false], + ['https://calendly.com/specialist/meeting', false, false], + [null, true, false], + ['http://calendly.com/specialist/meeting', true, false], + ['https://calendly.com.evil.test/meeting', true, false], + ['https://calendly.com/specialist/meeting', true, true], + ])( + 'enforces reciprocal method capability for URL %s and connection %s', + async (calendlyUrl, connectionActive, available) => { + for (const method of [ + AppointmentSchedulingMethod.EMAIL, + AppointmentSchedulingMethod.CALENDLY, + ]) { + const { service, appointmentCreate } = harness({ + calendlyUrl, + connectionActive, + }); + const input = { + ...dto, + scheduling_method: method, + appointment_datetime: + method === AppointmentSchedulingMethod.EMAIL + ? dto.appointment_datetime + : undefined, + }; + const creation = service.createPending( + input, + client.id, + UserRole.CUSTOMER, + ); + if ((method === AppointmentSchedulingMethod.CALENDLY) === available) { + await expect(creation).resolves.toMatchObject({ + status: StatusAgendamento.PENDING, + scheduling_method: method, + process_id: 'process-1', + }); + } else { + const error = await creation.catch((caught) => caught); + expect(error).toBeInstanceOf(ConflictException); + expect(error.getResponse()).toEqual({ + success: false, + error: { + code: + method === AppointmentSchedulingMethod.CALENDLY + ? 'CALENDLY_UNAVAILABLE' + : 'EMAIL_FLOW_UNAVAILABLE', + message: expect.any(String), + }, + }); + expect(appointmentCreate).not.toHaveBeenCalled(); + } + } + }, + ); + + it('preserves optional date EMAIL consultancy even with Calendly available', async () => { + const { service, appointmentCreate } = harness({ + calendlyUrl: 'https://calendly.com/specialist/meeting', + connectionActive: true, + }); + await expect( + service.createPending( + { + client_id: client.id, + specialist_id: specialist.id, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + }, + client.id, + UserRole.CUSTOMER, + ), + ).resolves.toMatchObject({ + process_id: 'process-1', + appointment_datetime: null, + }); + expect(appointmentCreate).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: null, + }), + }), + ); + }); + + it('persists an optional future consultancy EMAIL date exactly under the schedule lock', async () => { + const { service, tx } = harness({}); + const datetime = '2099-01-01T07:00:00-03:00'; + await expect( + service.createPending( + { + client_id: client.id, + specialist_id: specialist.id, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: datetime, + }, + client.id, + UserRole.CUSTOMER, + ), + ).resolves.toMatchObject({ + appointment_datetime: new Date(datetime), + status: StatusAgendamento.PENDING, + process_id: 'process-1', + }); + expect(tx.$queryRaw).toHaveBeenCalledWith( + expect.anything(), + 'appointment-schedule:specialist-1', + ); + expect(tx.appointment.findFirst).toHaveBeenCalledTimes(1); + }); + + it.each([ + 'not-a-date', + '01/01/2099', + '2000-01-01T00:00:00.000Z', + '2026-10-14T12:00:00.000Z', + ])( + 'rejects invalid, non-ISO, past or current optional consultancy date %s before writes', + async (datetime) => { + jest.useFakeTimers().setSystemTime(new Date('2026-10-14T12:00:00.000Z')); + try { + const { service, appointmentCreate, processCreate } = harness({}); + await expect( + service.createPending( + { + client_id: client.id, + specialist_id: specialist.id, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: datetime, + }, + client.id, + UserRole.CUSTOMER, + ), + ).rejects.toThrow(BadRequestException); + expect(appointmentCreate).not.toHaveBeenCalled(); + expect(processCreate).not.toHaveBeenCalled(); + } finally { + jest.useRealTimers(); + } + }, + ); + + it('returns ACTIVE_PROCESS_EXISTS with the owned proposal after acquiring the dedup lock', async () => { + const proposedDate = new Date(dto.appointment_datetime!); + const { service, prisma, tx, appointmentCreate } = harness({ + existingProcess: { + id: 'process-existing', + client_id: client.id, + appointment: { + id: 'appointment-existing', + client_id: client.id, + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: proposedDate, + }, + }, + }); + const error = await service + .createPending(dto, client.id, UserRole.CUSTOMER) + .catch((caught) => caught); + expect(error).toBeInstanceOf(ConflictException); + expect(error.getResponse().error.details.existing_request).toEqual({ + process_id: 'process-existing', + appointment_id: 'appointment-existing', + appointment_status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: proposedDate, + }); + expect(prisma.appointment.findFirst).not.toHaveBeenCalled(); + expect(tx.$queryRaw.mock.invocationCallOrder[1]).toBeLessThan( + tx.process.findFirst.mock.invocationCallOrder[0], + ); + expect(appointmentCreate).not.toHaveBeenCalled(); + }); + + it.each([ + UserRole.CUSTOMER, + UserRole.SPECIALIST, + UserRole.ADMIN, + UserRole.CONSULTANT, + ])( + 'rejects the direct PLATFORM bypass for %s before any database access', + async (role) => { + const { service, prisma, tx, appointmentCreate } = harness({}); + const error = await service + .create(dto as any, client.id, role) + .catch((caught) => caught); + expect(error).toBeInstanceOf(ForbiddenException); + expect(error.getResponse()).toEqual({ + success: false, + error: { code: 403, message: expect.any(String) }, + }); + expect(prisma.user.findUnique).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + expect(tx.$queryRaw).not.toHaveBeenCalled(); + expect(appointmentCreate).not.toHaveBeenCalled(); + }, + ); +}); + +describe('AppointmentsService.findExistingAppointment — own minimal projection', () => { + const ownedAppointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + product_type: ProductType.CAR, + product_id: 'car-1', + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + process: { id: 'process-1', client_id: 'client-1' }, + client: { + id: 'client-1', + name: 'Private Client', + email: 'private@example.com', + }, + specialist: { id: 'specialist-1', name: 'Specialist' }, + notes: 'private-notes', + created_at: new Date(), + updated_at: new Date(), + }; + function harness(appointment: any) { + const prisma = { + appointment: { findFirst: jest.fn().mockResolvedValue(appointment) }, + car: { findUnique: jest.fn().mockResolvedValue({ id: 'car-1' }) }, + } as any; + return { + prisma, + service: new AppointmentsService(prisma, {} as any, {} as any), + }; + } + it.each([ + ownedAppointment, + { + ...ownedAppointment, + scheduling_method: null, + appointment_datetime: null, + }, + ])( + 'returns only the owned discriminator and supports legacy date/method nulls', + async (appointment) => { + const { prisma, service } = harness(appointment); + expect( + await service.findExistingAppointment( + 'client-1', + 'specialist-1', + ProductType.CAR, + 'car-1', + ), + ).toEqual({ + exists: true, + appointment_id: appointment.id, + process_id: 'process-1', + appointment_status: appointment.status, + scheduling_method: appointment.scheduling_method, + appointment_datetime: appointment.appointment_datetime, + }); + expect(prisma.appointment.findFirst).toHaveBeenCalledWith({ + where: expect.objectContaining({ + client_id: 'client-1', + specialist_id: 'specialist-1', + product_type: ProductType.CAR, + product_id: 'car-1', + }), + select: { + id: true, + client_id: true, + status: true, + scheduling_method: true, + appointment_datetime: true, + process: { select: { id: true, client_id: true } }, + }, + }); + expect(prisma.car.findUnique).not.toHaveBeenCalled(); + }, + ); + it.each([ + null, + { ...ownedAppointment, client_id: 'another-client' }, + { ...ownedAppointment, process: null }, + { + ...ownedAppointment, + process: { id: 'private-process', client_id: 'another-client' }, + }, + ])( + 'fails closed for missing or unowned appointment/process %o', + async (appointment) => { + const { service } = harness(appointment); + expect( + await service.findExistingAppointment( + 'client-1', + 'specialist-1', + ProductType.CAR, + 'car-1', + ), + ).toEqual({ exists: false }); + }, + ); }); describe('AppointmentsService.createPending — integridade das partes', () => { @@ -338,7 +703,7 @@ describe('AppointmentsService.createPending — integridade das partes', () => { expect(prisma.user.findUnique).not.toHaveBeenCalled(); }); - it('rejeita horário pré-preenchido em uma solicitação por e-mail', async () => { + it('rejeita horário enviado pelo cliente para Calendly', async () => { const prisma = { user: { findUnique: jest.fn() }, } as any; @@ -349,7 +714,7 @@ describe('AppointmentsService.createPending — integridade das partes', () => { { client_id: 'client-1', specialist_id: 'specialist-1', - scheduling_method: AppointmentSchedulingMethod.EMAIL, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, appointment_datetime: '2099-01-01T10:00:00.000Z', } as CreatePendingAppointmentDto, 'client-1', @@ -408,6 +773,8 @@ describe('AppointmentsService.createPending — integridade das partes', () => { name: 'Specialist', role: UserRole.SPECIALIST, speciality: ProductType.CAR, + calendly_url: 'https://calendly.com/specialist/meeting', + calendly_connection: { is_active: true }, }; const tx = { $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 407a388..51fb4f8 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -20,6 +20,7 @@ import { ClientResponseDto, SpecialistResponseDto, ProductResponseDto, + ExistingAppointmentCheck, } from './entities/appointment.response'; import { AppointmentSchedulingMethod, @@ -34,6 +35,8 @@ import { ProcessStatus, } from '@prisma/client'; import { plainToInstance } from 'class-transformer'; +import { isISO8601 } from 'class-validator'; +import { isCalendlySchedulingAvailable } from 'src/shared/utils/calendly-scheduling-capability'; import { parseDate, isFutureDate } from 'src/shared/utils/date.utils'; import { NotificationService } from 'src/features/notifications/notification.service'; import { CalendlyIntegrationService } from './calendly-integration.service'; @@ -78,243 +81,20 @@ export class AppointmentsService { private calendlyIntegrationService: CalendlyIntegrationService, ) {} - /** - * Cria novo agendamento - * - * Fluxo: - * 1. Validar que cliente e especialista existem - * 2. Validar que appointment_datetime é futuro - * 3. Verificar conflitos de horário - * 4. Validar que produto existe e pertence ao especialista - * 5. Criar Appointment - * 6. Auto-criar Process em status SCHEDULING - * 7. Retornar AppointmentResponseEntity - * - * @param dto Dados do agendamento - * @param userId ID do usuário autenticado (JWT) - * @returns Appointment criado com dados completos - * @throws BadRequestException Se dados inválidos - * @throws ConflictException Se conflito de horário - * @throws NotFoundException Se usuário ou produto não encontrado - */ + /** Bloqueia a criação direta sem confirmação do especialista. */ async create( - dto: CreatePlatformAppointmentDto, - userId: string, - userRole: UserRole, + _dto: CreatePlatformAppointmentDto, + _userId: string, + _userRole: UserRole, ): Promise { - if (userRole !== UserRole.CUSTOMER || dto.client_id !== userId) { - throw new ForbiddenException({ - success: false, - error: { - code: 403, - message: 'Apenas o próprio cliente pode criar este agendamento', - }, - }); - } - - this.logger.log( - `[create] Criando agendamento para cliente ${dto.client_id} com especialista ${dto.specialist_id}`, - ); - - const appointmentDateTime = parseDate(dto.appointment_datetime); - if (!appointmentDateTime || !isFutureDate(appointmentDateTime)) { - this.logger.warn('[create] Data/hora do agendamento é inválida'); - throw new BadRequestException({ - success: false, - error: { - code: 400, - message: 'Data/hora do agendamento deve ser futura', - details: { - appointment_datetime: [ - 'appointment_datetime deve ser uma data ISO 8601 futura', - ], - }, - }, - }); - } - - // Validação 2: Verificar que cliente existe - this.logger.debug( - `[create] Validando existência do cliente ${dto.client_id}`, - ); - const client = await this.prisma.user.findUnique({ - where: { id: dto.client_id }, - }); - if (!client) { - this.logger.error(`[create] Cliente ${dto.client_id} não encontrado`); - throw new NotFoundException({ - success: false, - error: { - code: 404, - message: 'Cliente não encontrado', - details: { - client_id: dto.client_id, - }, - }, - }); - } - - // Validação 3: Verificar que especialista existe e tem role SPECIALIST - const specialist = await this.prisma.user.findUnique({ - where: { id: dto.specialist_id }, - }); - if (!specialist) { - throw new NotFoundException({ - success: false, - error: { - code: 404, - message: 'Especialista não encontrado', - details: { - specialist_id: dto.specialist_id, - }, - }, - }); - } - - if ( - specialist.role !== UserRole.SPECIALIST && - specialist.role !== UserRole.CONSULTANT - ) { - throw new BadRequestException({ - success: false, - error: { - code: 400, - message: 'Usuário não é especialista', - details: { - specialist_id: dto.specialist_id, - role: specialist.role, - }, - }, - }); - } - - // Validação 4: Validar que especialidade do especialista corresponde ao product_type - if (specialist.speciality && specialist.speciality !== dto.product_type) { - throw new BadRequestException({ - success: false, - error: { - code: 400, - message: 'Especialista não trabalha com este tipo de produto', - details: { - specialist_speciality: specialist.speciality, - requested_product_type: dto.product_type, - }, - }, - }); - } - - // Validação 5: Verificar que cliente e especialista são diferentes - if (dto.client_id === dto.specialist_id) { - throw new BadRequestException({ - success: false, - error: { - code: 400, - message: 'Cliente e especialista não podem ser a mesma pessoa', - details: { - client_id: dto.client_id, - specialist_id: dto.specialist_id, - }, - }, - }); - } - - const { appointment, process, product } = await this.prisma.$transaction( - async (tx) => { - // Validação 6: produto ativo, do tipo correto e pertencente ao especialista. - const product = (await validateSpecialistProductAssociation(tx, { - specialistId: dto.specialist_id, - productType: dto.product_type, - productId: dto.product_id, - })) as Car | Boat | Aircraft; - - await lockAndAssertNoActiveProcess(tx, { - clientId: dto.client_id, - specialistId: dto.specialist_id, - productType: dto.product_type, - productId: dto.product_id, - }); - await lockAndAssertSpecialistScheduleAvailable( - tx, - dto.specialist_id, - appointmentDateTime, - ); - - // Criar Appointment - const appointment = await tx.appointment.create({ - data: { - client_id: dto.client_id, - specialist_id: dto.specialist_id, - product_type: dto.product_type, - product_id: dto.product_id, - appointment_datetime: appointmentDateTime, - status: StatusAgendamento.SCHEDULED, - scheduling_method: AppointmentSchedulingMethod.PLATFORM, - notes: dto.notes, - }, - include: { - client: true, - specialist: true, - }, - }); - - // Auto-criar Process vinculado a este Appointment - // Process começa em status SCHEDULING (agendamento confirmado) - const process = await tx.process.create({ - data: { - client_id: dto.client_id, - specialist_id: dto.specialist_id, - product_type: dto.product_type, - appointment_id: appointment.id, - [dto.product_type === ProductType.CAR - ? 'car_id' - : dto.product_type === ProductType.BOAT - ? 'boat_id' - : 'aircraft_id']: dto.product_id, - status: 'SCHEDULING', // ProcessStatus enum - notes: `Criado via agendamento interno. Cliente agendou em ${appointment.appointment_datetime?.toISOString()}`, - }, - }); - - await tx.processStatusHistory.create({ - data: { - processId: process.id, - status: ProcessStatus.SCHEDULING, - changed_by: userId, - changed_at: new Date(), - }, - }); - - return { appointment, process, product }; + throw new ForbiddenException({ + success: false, + error: { + code: 403, + message: + 'Use o pedido pendente por e-mail ou Calendly para solicitar a reunião', }, - ); - - // Fire-and-forget: Notificar especialista sobre novo agendamento - const productDetails = product - ? `${(product as any).marca || ''} ${(product as any).modelo || ''}`.trim() - : `Produto ${dto.product_type}`; - - setImmediate(() => { - this.notificationService - .sendAppointmentCreatedEmail({ - specialistEmail: specialist.email, - specialistName: - `${specialist.name} ${specialist.surname || ''}`.trim(), - clientName: `${client.name} ${client.surname || ''}`.trim(), - appointmentDate: appointment.appointment_datetime || new Date(), - productDetails, - processId: process.id, - }) - .catch((err) => { - this.logger.error('Notification failed (non-critical)', { - method: 'create', - appointmentId: appointment.id, - error: err.message, - }); - }); }); - - // Montar resposta com dados completos - return this.mapToResponseEntity(appointment, client, specialist, product); } async reschedule( @@ -1200,8 +980,7 @@ export class AppointmentsService { } /** - * Cria um agendamento PENDING - * Usado quando cliente clica no link do Calendly e retorna à plataforma + * Cria um agendamento PENDING por EMAIL ou CALENDLY e seu processo associado. * * Dois fluxos suportados: * 1. Com produto: product_type e product_id fornecidos - fluxo padrão @@ -1209,37 +988,14 @@ export class AppointmentsService { * * @param dto Dados do agendamento (product_type e product_id opcionais) * @param userId ID do cliente autenticado - * @returns Appointment em status PENDING + * @returns Appointment em status PENDING e o process_id criado atomicamente */ async createPending( dto: CreatePendingAppointmentDto, userId: string, userRole: UserRole, - ): Promise { - this.logger.log( - `[createPending] Criando agendamento PENDING para cliente ${dto.client_id}`, - ); - - const schedulingMethod = - dto.scheduling_method ?? AppointmentSchedulingMethod.CALENDLY; - - if ( - schedulingMethod === AppointmentSchedulingMethod.EMAIL && - dto.appointment_datetime - ) { - throw new BadRequestException( - 'Solicitações por e-mail devem ter o horário definido pelo especialista', - ); - } - - // Validar que quem está criando é o próprio cliente - this.logger.log( - `[createPending] Validando permissão: userId=${userId} vs client_id=${dto.client_id}`, - ); + ): Promise { if (userRole !== UserRole.CUSTOMER || dto.client_id !== userId) { - this.logger.error( - `[createPending] ERRO: Cliente tentando criar agendamento para outro usuário`, - ); throw new ForbiddenException({ success: false, error: { @@ -1248,154 +1004,125 @@ export class AppointmentsService { }, }); } - this.logger.log(`[createPending] ✓ Permissão validada`); - // Validar cliente existe - this.logger.log(`[createPending] Buscando cliente ${dto.client_id}...`); - const client = await this.prisma.user.findUnique({ - where: { id: dto.client_id }, - }); - if (!client) { - this.logger.error( - `[createPending] ERRO: Cliente ${dto.client_id} não encontrado`, + const schedulingMethod = + dto.scheduling_method ?? AppointmentSchedulingMethod.CALENDLY; + if ( + schedulingMethod !== AppointmentSchedulingMethod.EMAIL && + schedulingMethod !== AppointmentSchedulingMethod.CALENDLY + ) { + throw new BadRequestException( + 'scheduling_method deve ser EMAIL ou CALENDLY', + ); + } + if ((dto.product_type != null) !== (dto.product_id != null)) { + throw new BadRequestException( + 'product_type e product_id devem ser informados juntos.', + ); + } + const isConsultancy = dto.product_id == null; + const hasDate = + dto.appointment_datetime !== undefined && + dto.appointment_datetime !== null; + if ( + schedulingMethod === AppointmentSchedulingMethod.CALENDLY && + dto.appointment_datetime !== undefined + ) { + throw new BadRequestException( + 'A data do Calendly deve ser definida pela sincronização, não pelo cliente', + ); + } + const pendingDateTime = hasDate + ? parseDate(dto.appointment_datetime) + : null; + if ( + hasDate && + (typeof dto.appointment_datetime !== 'string' || + !isISO8601(dto.appointment_datetime, { strict: true }) || + !pendingDateTime || + !isFutureDate(pendingDateTime)) + ) { + throw new BadRequestException( + 'Data/hora do agendamento deve ser uma data ISO 8601 futura válida', + ); + } + if ( + !isConsultancy && + schedulingMethod === AppointmentSchedulingMethod.EMAIL && + !pendingDateTime + ) { + throw new BadRequestException( + 'Data/hora proposta é obrigatória para solicitações por e-mail com produto', ); - throw new NotFoundException({ - success: false, - error: { code: 404, message: 'Cliente não encontrado' }, - }); } - this.logger.log(`[createPending] ✓ Cliente encontrado: ${client.name}`); - // Validar especialista existe - this.logger.log( - `[createPending] Buscando especialista ${dto.specialist_id}...`, - ); + const client = await this.prisma.user.findUnique({ where: { id: userId } }); + if (!client) throw new NotFoundException('Cliente não encontrado'); const specialist = await this.prisma.user.findUnique({ where: { id: dto.specialist_id }, + include: { calendly_connection: { select: { is_active: true } } }, }); - if (!specialist) { - this.logger.error( - `[createPending] ERRO: Especialista ${dto.specialist_id} não encontrado`, - ); - throw new NotFoundException({ - success: false, - error: { code: 404, message: 'Especialista não encontrado' }, - }); - } - this.logger.log( - `[createPending] ✓ Especialista encontrado: ${specialist.name}`, - ); - - // Determinar se é consultoria (sem produto) ou fluxo padrão (com produto) - const isConsultancy = !dto.product_type || !dto.product_id; - this.logger.log( - `[createPending] Modo: ${isConsultancy ? 'CONSULTORIA' : 'COM PRODUTO'}`, - ); - - // Verificar se já existe agendamento PENDING ou SCHEDULED - this.logger.log(`[createPending] Verificando agendamento duplicado...`); - const existingWhere: any = { - client_id: dto.client_id, - specialist_id: dto.specialist_id, - status: { - in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], - }, - }; - - if (isConsultancy) { - // Para consultoria, verificar se já existe agendamento sem produto - existingWhere.product_type = null; - existingWhere.product_id = null; - } else { - // Para fluxo normal, verificar por produto específico - existingWhere.product_type = dto.product_type; - existingWhere.product_id = dto.product_id; + if (!specialist) throw new NotFoundException('Especialista não encontrado'); + if (specialist.role !== UserRole.SPECIALIST) { + throw new BadRequestException('Usuário informado não é especialista'); } - - const existing = await this.prisma.appointment.findFirst({ - where: existingWhere, + const calendlyAvailable = isCalendlySchedulingAvailable({ + calendlyUrl: specialist.calendly_url, + connectionActive: specialist.calendly_connection?.is_active ?? false, }); - - if (existing) { - this.logger.error( - `[createPending] ERRO: Agendamento duplicado encontrado: ${existing.id}`, - ); + if ( + schedulingMethod === AppointmentSchedulingMethod.CALENDLY && + !calendlyAvailable + ) { throw new ConflictException({ success: false, error: { - code: 409, - message: isConsultancy - ? 'Já existe um agendamento de consultoria pendente com este especialista' - : 'Já existe um agendamento pendente ou confirmado para este produto', - details: { - existing_id: existing.id, - existing_status: existing.status, - }, + code: 'CALENDLY_UNAVAILABLE', + message: 'Calendly indisponível. Solicite a reunião por e-mail.', }, }); } - this.logger.log( - `[createPending] ✓ Nenhum agendamento duplicado encontrado`, - ); - - // Validar produto apenas se fornecido (não é consultoria) - let product: any = null; - if (!isConsultancy) { - this.logger.log( - `[createPending] Buscando produto ${dto.product_type}/${dto.product_id}...`, - ); - product = await this.getProductByType(dto.product_type!, dto.product_id!); - if (!product) { - this.logger.error( - `[createPending] ERRO: Produto ${dto.product_type}/${dto.product_id} não encontrado`, - ); - throw new NotFoundException({ - success: false, - error: { code: 404, message: 'Produto não encontrado' }, - }); - } - this.logger.log(`[createPending] ✓ Produto encontrado`); - } else { - this.logger.log( - `[createPending] Consultoria - pulando validação de produto`, - ); + if ( + !isConsultancy && + schedulingMethod === AppointmentSchedulingMethod.EMAIL && + calendlyAvailable + ) { + throw new ConflictException({ + success: false, + error: { + code: 'EMAIL_FLOW_UNAVAILABLE', + message: + 'Este especialista utiliza Calendly. Solicite a reunião pelo calendário.', + }, + }); } - // Criar appointment em status PENDING e Process em transação + // Metadata only: automatic expiration is not implemented. const pendingExpiresAt = new Date(); - pendingExpiresAt.setDate(pendingExpiresAt.getDate() + 7); // Expira em 7 dias + pendingExpiresAt.setDate(pendingExpiresAt.getDate() + 7); - this.logger.log( - `[createPending] Iniciando transação para criar appointment e process`, - ); - - let appointment: any; - let process: any; - - try { - this.logger.log(`[createPending] Entrando na transação do Prisma...`); - [appointment, process] = await this.prisma.$transaction(async (tx) => { - this.logger.log(`[createPending] Dentro da transação - iniciando`); - - await validateSpecialistProductAssociation(tx, { + const { appointment, process, product } = await this.prisma.$transaction( + async (tx) => { + const product = await validateSpecialistProductAssociation(tx, { specialistId: dto.specialist_id, productType: dto.product_type, productId: dto.product_id, }); + await lockAndAssertNoActiveProcess( + tx, + { + clientId: userId, + specialistId: dto.specialist_id, + productType: dto.product_type, + productId: dto.product_id, + }, + undefined, + { authenticatedClientId: userId }, + ); - await lockAndAssertNoActiveProcess(tx, { - clientId: dto.client_id, - specialistId: dto.specialist_id, - productType: isConsultancy ? null : dto.product_type, - productId: isConsultancy ? null : dto.product_id, - }); - const pendingDateTime = dto.appointment_datetime - ? parseDate(String(dto.appointment_datetime)) - : null; - if (dto.appointment_datetime && !pendingDateTime) { - throw new BadRequestException('Data/hora do agendamento é inválida'); - } - if (pendingDateTime) { + // Product EMAIL requests are proposals. Preserve the optional dated + // consultancy validation without making any PENDING/EMAIL occupy agenda. + if (isConsultancy && pendingDateTime) { await lockAndAssertSpecialistScheduleAvailable( tx, dto.specialist_id, @@ -1403,109 +1130,58 @@ export class AppointmentsService { ); } - // Criar appointment - const appointmentData: any = { - client_id: dto.client_id, - specialist_id: dto.specialist_id, - appointment_datetime: pendingDateTime, - status: StatusAgendamento.PENDING, - scheduling_method: schedulingMethod, - notes: - dto.notes || - (isConsultancy - ? 'Consultoria: cliente acessou link do Calendly' - : 'Cliente acessou link do Calendly'), - user_clicked_at: new Date(), - pending_expires_at: pendingExpiresAt, - }; - - // Adicionar produto se não for consultoria - if (!isConsultancy) { - appointmentData.product_type = dto.product_type; - appointmentData.product_id = dto.product_id; - } - - this.logger.log( - `[createPending] Criando appointment ${isConsultancy ? '(consultoria)' : `para produto ${dto.product_type}/${dto.product_id}`}`, - ); - const createdAppointment = await tx.appointment.create({ - data: appointmentData, - include: { - client: true, - specialist: true, + const appointment = await tx.appointment.create({ + data: { + client_id: userId, + specialist_id: dto.specialist_id, + product_type: dto.product_type ?? null, + product_id: dto.product_id ?? null, + appointment_datetime: pendingDateTime, + status: StatusAgendamento.PENDING, + scheduling_method: schedulingMethod, + notes: + dto.notes || + (schedulingMethod === AppointmentSchedulingMethod.EMAIL + ? 'Cliente solicitou reunião por e-mail' + : 'Cliente acessou link do Calendly'), + user_clicked_at: new Date(), + pending_expires_at: pendingExpiresAt, }, }); - this.logger.log( - `[createPending] Appointment criado: ${createdAppointment.id}`, - ); - - // Criar Process em status SCHEDULING - const processData: any = { - client_id: dto.client_id, - specialist_id: dto.specialist_id, - appointment_id: createdAppointment.id, - status: 'SCHEDULING', - notes: isConsultancy - ? `Consultoria criada via agendamento PENDING (${new Date().toISOString()})` - : `Criado via agendamento PENDING (${new Date().toISOString()})`, - }; - - // Adicionar produto apenas se não for consultoria - if (!isConsultancy) { - const productField = - dto.product_type === ProductType.CAR - ? 'car_id' - : dto.product_type === ProductType.BOAT - ? 'boat_id' - : 'aircraft_id'; - - this.logger.log( - `[createPending] Criando process com campo ${productField}=${dto.product_id}`, - ); - processData.product_type = dto.product_type; - processData[productField] = dto.product_id; - } else { - this.logger.log( - `[createPending] Criando process de consultoria (sem produto)`, - ); - } - - const createdProcess = await tx.process.create({ - data: processData, + const productField = + dto.product_type === ProductType.CAR + ? 'car_id' + : dto.product_type === ProductType.BOAT + ? 'boat_id' + : 'aircraft_id'; + const process = await tx.process.create({ + data: { + client_id: userId, + specialist_id: dto.specialist_id, + appointment_id: appointment.id, + status: ProcessStatus.SCHEDULING, + product_type: dto.product_type ?? null, + ...(isConsultancy ? {} : { [productField]: dto.product_id }), + notes: `Criado via agendamento PENDING (${new Date().toISOString()})`, + }, }); - this.logger.log( - `[createPending] Process criado: ${createdProcess.id} com status ${createdProcess.status}`, - ); - - // Criar histórico await tx.processStatusHistory.create({ data: { - processId: createdProcess.id, - status: 'SCHEDULING', - changed_by: dto.client_id, + processId: process.id, + status: ProcessStatus.SCHEDULING, + changed_by: userId, changed_at: new Date(), }, }); - this.logger.log( - `[createPending] Histórico de status criado para process ${createdProcess.id}`, - ); - - return [createdAppointment, createdProcess]; - }); - - this.logger.log( - `[createPending] Transação concluída com sucesso! Appointment: ${appointment.id}, Process: ${process.id}`, - ); - - return this.mapToResponseEntity(appointment, client, specialist, product); - } catch (error) { - this.logger.error(`[createPending] ERRO CRÍTICO na transação:`); - this.logger.error( - `[createPending] Tipo do erro: ${error?.constructor?.name}`, - ); - this.logger.error(`[createPending] Mensagem: ${error?.message}`); - throw error; - } + return { appointment, process, product }; + }, + ); + return Object.assign( + this.mapToResponseEntity(appointment, client, specialist, product), + { + process_id: process.id, + }, + ); } /** @@ -2000,14 +1676,14 @@ export class AppointmentsService { * @param specialistId ID do especialista (UUID) * @param productType Tipo de produto (CAR, BOAT, AIRCRAFT) * @param productId UUID do produto - * @returns Appointment se encontrado, caso contrário null + * @returns Discriminante e snapshot mínimo do pedido pertencente ao cliente */ async findExistingAppointment( clientId: string, specialistId: string, productType: ProductType, productId: string, - ): Promise { + ): Promise { const appointment = await this.prisma.appointment.findFirst({ where: { client_id: clientId, @@ -2017,24 +1693,34 @@ export class AppointmentsService { status: { in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], }, + process: { is: { client_id: clientId } }, + }, + select: { + id: true, + client_id: true, + status: true, + scheduling_method: true, + appointment_datetime: true, + process: { select: { id: true, client_id: true } }, }, - include: { client: true, specialist: true }, }); - if (!appointment) { - return null; + if ( + !appointment || + appointment.client_id !== clientId || + !appointment.process || + appointment.process.client_id !== clientId + ) { + return { exists: false }; } - - const product = await this.getProductByType( - appointment.product_type, - appointment.product_id, - ); - return this.mapToResponseEntity( - appointment, - appointment.client, - appointment.specialist, - product, - ); + return { + exists: true, + appointment_id: appointment.id, + process_id: appointment.process.id, + appointment_status: appointment.status, + scheduling_method: appointment.scheduling_method, + appointment_datetime: appointment.appointment_datetime, + }; } async registerCalendlyScheduled( diff --git a/backend/src/features/appointments/dto/check-existing-appointment.dto.ts b/backend/src/features/appointments/dto/check-existing-appointment.dto.ts new file mode 100644 index 0000000..1050b42 --- /dev/null +++ b/backend/src/features/appointments/dto/check-existing-appointment.dto.ts @@ -0,0 +1,13 @@ +import { ProductType } from '@prisma/client'; +import { IsEnum, IsUUID } from 'class-validator'; + +export class CheckExistingAppointmentDto { + @IsUUID() + specialist_id: string; + + @IsEnum(ProductType) + product_type: ProductType; + + @IsUUID() + product_id: string; +} diff --git a/backend/src/features/appointments/dto/create-pending-appointment.dto.ts b/backend/src/features/appointments/dto/create-pending-appointment.dto.ts index 1c151dd..9f4351d 100644 --- a/backend/src/features/appointments/dto/create-pending-appointment.dto.ts +++ b/backend/src/features/appointments/dto/create-pending-appointment.dto.ts @@ -1,14 +1,22 @@ import { AppointmentSchedulingMethod } from '@prisma/client'; -import { IsIn, IsOptional } from 'class-validator'; +import { OmitType } from '@nestjs/mapped-types'; +import { IsDateString, IsIn, IsOptional } from 'class-validator'; import { CreateAppointmentDto } from './create-appointment.dto'; -export class CreatePendingAppointmentDto extends CreateAppointmentDto { +export class CreatePendingAppointmentDto extends OmitType( + CreateAppointmentDto, + ['appointment_datetime'] as const, +) { + @IsOptional() + @IsDateString( + { strict: true }, + { message: 'appointment_datetime deve ser uma data ISO 8601 válida' }, + ) + appointment_datetime?: string; + @IsOptional() @IsIn( - [ - AppointmentSchedulingMethod.EMAIL, - AppointmentSchedulingMethod.CALENDLY, - ], + [AppointmentSchedulingMethod.EMAIL, AppointmentSchedulingMethod.CALENDLY], { message: 'scheduling_method deve ser EMAIL ou CALENDLY', }, diff --git a/backend/src/features/appointments/dto/index.ts b/backend/src/features/appointments/dto/index.ts index 4ff7585..9c83a94 100644 --- a/backend/src/features/appointments/dto/index.ts +++ b/backend/src/features/appointments/dto/index.ts @@ -2,6 +2,7 @@ export * from './create-appointment.dto'; export * from './create-platform-appointment.dto'; export * from './create-pending-appointment.dto'; +export * from './check-existing-appointment.dto'; export * from './reschedule-appointment.dto'; export * from './get-appointments-query.dto'; export * from './update-appointment-status.dto'; diff --git a/backend/src/features/appointments/entities/appointment.response.ts b/backend/src/features/appointments/entities/appointment.response.ts index 183685f..fb56052 100644 --- a/backend/src/features/appointments/entities/appointment.response.ts +++ b/backend/src/features/appointments/entities/appointment.response.ts @@ -6,6 +6,25 @@ import { } from '@prisma/client'; import { Expose, Type } from 'class-transformer'; +export type ExistingAppointmentCheck = + | { exists: false } + | { + exists: true; + appointment_id: string; + process_id: string; + appointment_status: StatusAgendamento; + scheduling_method: AppointmentSchedulingMethod | null; + appointment_datetime: Date | null; + }; + +export interface ActiveProcessSnapshot { + process_id: string; + appointment_id: string | null; + appointment_status: StatusAgendamento | null; + scheduling_method: AppointmentSchedulingMethod | null; + appointment_datetime: Date | null; +} + /** * DTO aninhado: dados do cliente no agendamento * Contém informações mínimas necessárias para exibição @@ -139,6 +158,9 @@ export class ProductResponseDto { * - Exemplo: "2024-10-10T14:00:00Z" → 14:00 (São Paulo, -03:00) */ export class AppointmentResponseEntity { + @Expose() + process_id?: string; + /** * ID único do agendamento (UUID) */ diff --git a/backend/src/features/processes/process-dedup-lock.spec.ts b/backend/src/features/processes/process-dedup-lock.spec.ts index f2e15f8..cd4fc32 100644 --- a/backend/src/features/processes/process-dedup-lock.spec.ts +++ b/backend/src/features/processes/process-dedup-lock.spec.ts @@ -1,6 +1,14 @@ import { ConflictException } from '@nestjs/common'; -import { ProductType } from '@prisma/client'; -import { assertNoActiveProcess } from './process-dedup-lock'; +import { + AppointmentSchedulingMethod, + CalendlySyncStatus, + ProductType, + StatusAgendamento, +} from '@prisma/client'; +import { + assertNoActiveProcess, + lockAndAssertNoActiveProcess, +} from './process-dedup-lock'; describe('assertNoActiveProcess', () => { it('returns a stable error code when an active product process exists', async () => { @@ -31,3 +39,158 @@ describe('assertNoActiveProcess', () => { }); }); }); + +describe('own active process snapshot', () => { + const scope = { + clientId: 'client-1', + specialistId: 'specialist-1', + productType: ProductType.CAR, + productId: 'car-1', + }; + const options = { authenticatedClientId: scope.clientId }; + const appointment = { + id: 'appointment-1', + client_id: scope.clientId, + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + calendly_sync_status: CalendlySyncStatus.PENDING, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + client: { email: 'private@example.com', phone: 'private-phone' }, + }; + function harness(existing: any) { + const tx = { + $queryRaw: jest.fn().mockResolvedValue([]), + process: { findFirst: jest.fn().mockResolvedValue(existing) }, + }; + return tx; + } + async function response( + tx: any, + actorOptions: any = options, + exclude?: string, + ) { + const error = await (assertNoActiveProcess as any)( + tx, + scope, + exclude, + actorOptions, + ).catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(ConflictException); + return error.getResponse(); + } + + it.each([null, appointment])( + 'returns the exact owned snapshot with appointment %o', + async (attached) => { + const tx = harness({ + id: 'process-1', + client_id: scope.clientId, + appointment: attached, + notes: 'private-notes', + }); + expect(await response(tx)).toEqual({ + success: false, + error: { + code: 'ACTIVE_PROCESS_EXISTS', + message: expect.any(String), + details: { + existing_request: { + process_id: 'process-1', + appointment_id: attached?.id ?? null, + appointment_status: attached?.status ?? null, + scheduling_method: attached?.scheduling_method ?? null, + appointment_datetime: attached?.appointment_datetime ?? null, + }, + }, + }, + }); + expect(tx.process.findFirst).toHaveBeenCalledWith({ + where: expect.objectContaining({ client_id: scope.clientId }), + select: { + id: true, + client_id: true, + appointment: { + select: { + id: true, + client_id: true, + status: true, + scheduling_method: true, + appointment_datetime: true, + }, + }, + }, + }); + }, + ); + + it('does not reveal details without the authenticated client opt-in', async () => { + const tx = harness({ + id: 'process-1', + client_id: scope.clientId, + appointment, + }); + const error = await assertNoActiveProcess(tx, scope).catch( + (caught) => caught, + ); + expect(error.getResponse().error).not.toHaveProperty('details'); + }); + + it.each([ + ['another-client', scope.clientId], + [scope.clientId, 'another-client'], + ])( + 'does not reveal details when actor %s or stored owner %s differs', + async (actorId, storedId) => { + const result = await response( + harness({ id: 'process-1', client_id: storedId, appointment }), + { authenticatedClientId: actorId }, + ); + expect(result.error).not.toHaveProperty('details'); + }, + ); + + it('nulls all appointment fields when the linked appointment belongs to someone else', async () => { + const result = await response( + harness({ + id: 'process-1', + client_id: scope.clientId, + appointment: { ...appointment, client_id: 'another-client' }, + }), + ); + expect(result.error.details.existing_request).toEqual({ + process_id: 'process-1', + appointment_id: null, + appointment_status: null, + scheduling_method: null, + appointment_datetime: null, + }); + }); + + it('forwards options and exclusions through the lock wrapper before reading', async () => { + const tx = harness({ + id: 'process-1', + client_id: scope.clientId, + appointment, + }); + const error = await (lockAndAssertNoActiveProcess as any)( + tx, + scope, + 'excluded-process', + options, + ).catch((caught: unknown) => caught); + expect(error.getResponse().error.details.existing_request.process_id).toBe( + 'process-1', + ); + expect(tx.process.findFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ id: { not: 'excluded-process' } }), + }), + ); + expect(tx.$queryRaw.mock.invocationCallOrder[0]).toBeLessThan( + tx.process.findFirst.mock.invocationCallOrder[0], + ); + expect(JSON.stringify(error.getResponse())).not.toMatch( + /private@example.com|private-phone|private-notes|client_id/, + ); + }); +}); diff --git a/backend/src/features/processes/process-dedup-lock.ts b/backend/src/features/processes/process-dedup-lock.ts index e37732b..3bf2ead 100644 --- a/backend/src/features/processes/process-dedup-lock.ts +++ b/backend/src/features/processes/process-dedup-lock.ts @@ -1,5 +1,6 @@ import { ConflictException } from '@nestjs/common'; import { ProcessStatus, ProductType } from '@prisma/client'; +import type { ActiveProcessSnapshot } from '../appointments/entities/appointment.response'; export const ACTIVE_PROCESS_STATUSES: ProcessStatus[] = [ ProcessStatus.SCHEDULING, @@ -15,12 +16,17 @@ export type ActiveProcessScope = { productId?: string | null; }; -const PRODUCT_FIELD: Record = { - [ProductType.CAR]: 'car_id', - [ProductType.BOAT]: 'boat_id', - [ProductType.AIRCRAFT]: 'aircraft_id', +type ActiveProcessConflictOptions = { + authenticatedClientId?: string; }; +const PRODUCT_FIELD: Record = + { + [ProductType.CAR]: 'car_id', + [ProductType.BOAT]: 'boat_id', + [ProductType.AIRCRAFT]: 'aircraft_id', + }; + export function activeProcessDedupKey(scope: ActiveProcessScope): string { const isConsultancy = !scope.productType || !scope.productId; return `process-dedup:${scope.clientId}:${scope.specialistId}:${isConsultancy ? 'CONSULTANCY' : scope.productType}:${isConsultancy ? 'none' : scope.productId}`; @@ -40,6 +46,7 @@ export async function assertNoActiveProcess( tx: any, scope: ActiveProcessScope, excludeProcessId?: string, + options?: ActiveProcessConflictOptions, ): Promise { const isConsultancy = !scope.productType || !scope.productId; const where: Record = isConsultancy @@ -57,8 +64,38 @@ export async function assertNoActiveProcess( }; if (excludeProcessId) where.id = { not: excludeProcessId }; - const existing = await tx.process.findFirst({ where }); + const existing = await tx.process.findFirst({ + where, + select: { + id: true, + client_id: true, + appointment: { + select: { + id: true, + client_id: true, + status: true, + scheduling_method: true, + appointment_datetime: true, + }, + }, + }, + }); if (existing) { + const owned = + options?.authenticatedClientId !== undefined && + options.authenticatedClientId === scope.clientId && + existing.client_id === scope.clientId; + const appointment = + owned && existing.appointment?.client_id === scope.clientId + ? existing.appointment + : null; + const snapshot: ActiveProcessSnapshot = { + process_id: existing.id, + appointment_id: appointment?.id ?? null, + appointment_status: appointment?.status ?? null, + scheduling_method: appointment?.scheduling_method ?? null, + appointment_datetime: appointment?.appointment_datetime ?? null, + }; throw new ConflictException({ success: false, error: { @@ -66,6 +103,7 @@ export async function assertNoActiveProcess( message: isConsultancy ? 'Já existe consultoria ativa entre este cliente e este especialista.' : 'Já existe processo ativo para este cliente com este produto.', + ...(owned ? { details: { existing_request: snapshot } } : {}), }, }); } @@ -75,7 +113,8 @@ export async function lockAndAssertNoActiveProcess( tx: any, scope: ActiveProcessScope, excludeProcessId?: string, + options?: ActiveProcessConflictOptions, ): Promise { await acquireActiveProcessDedupLock(tx, scope); - await assertNoActiveProcess(tx, scope, excludeProcessId); + await assertNoActiveProcess(tx, scope, excludeProcessId, options); } diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts index 8c38283..c3b263f 100644 --- a/backend/src/features/processes/processes.service.spec.ts +++ b/backend/src/features/processes/processes.service.spec.ts @@ -100,9 +100,24 @@ describe('ProcessesService — produto UUID', () => { ); expect(rootFindFirst).not.toHaveBeenCalled(); - expect(transactionalFindFirst).toHaveBeenCalledWith({ - where: expect.objectContaining({ car_id: productId }), - }); + expect(transactionalFindFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ car_id: productId }), + select: { + id: true, + client_id: true, + appointment: { + select: { + id: true, + client_id: true, + status: true, + scheduling_method: true, + appointment_datetime: true, + }, + }, + }, + }), + ); expect(create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ car_id: productId }), @@ -1290,9 +1305,11 @@ describe('ProcessesService — telefone da contraparte após confirmação', () ])( 'detalhe não expõe telefones para %s mesmo após confirmação', async (role, requesterId) => { - const result = await detailService( - StatusAgendamento.SCHEDULED, - ).getById('process-1', requesterId, role); + const result = await detailService(StatusAgendamento.SCHEDULED).getById( + 'process-1', + requesterId, + role, + ); expect(result.client.phone).toBeNull(); expect(result.specialist.phone).toBeNull(); From 5f47215ab606614929617f47edb3e5c3ac252564 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 08:25:32 -0300 Subject: [PATCH 07/60] fix: scope active email requests and validate proposed instants --- .../appointments/appointments.service.spec.ts | 199 ++++++++++++++++-- .../appointments/appointments.service.ts | 25 ++- .../dto/create-pending-appointment.dto.ts | 9 +- ...t-association-concurrency.postgres.spec.ts | 103 +++++---- 4 files changed, 281 insertions(+), 55 deletions(-) diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts index 96a6576..e1f8d33 100644 --- a/backend/src/features/appointments/appointments.service.spec.ts +++ b/backend/src/features/appointments/appointments.service.spec.ts @@ -72,6 +72,40 @@ describe('CreateAppointmentDto — seleção de produto', () => { ), ).toBe(true); }); + + it.each([ + '2099-01-01', + '2099-01-01T10:00:00', + '2099-01-01T10:00:00.000', + '2099-02-30T10:00:00Z', + '2099-01-01T10:00:00+25:00', + ])( + 'rejects a pending datetime without a valid time and timezone: %s', + async (datetime) => { + const dto = Object.assign(new CreatePendingAppointmentDto(), base, { + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: datetime, + }); + expect( + (await validate(dto)).some( + (error) => error.property === 'appointment_datetime', + ), + ).toBe(true); + }, + ); + + it.each([ + '2099-01-01T10:00:00.000Z', + '2099-01-01T07:00:00-03:00', + '2099-01-01T15:30:00+05:30', + '2099-01-01T07:00:00-0300', + ])('accepts an explicit pending datetime timezone: %s', async (datetime) => { + const dto = Object.assign(new CreatePendingAppointmentDto(), base, { + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: datetime, + }); + expect(await validate(dto)).toEqual([]); + }); }); describe('AppointmentsService.createPending — associação e atomicidade', () => { @@ -118,7 +152,7 @@ describe('AppointmentsService.createPending — associação e atomicidade', () const storedProcesses: any[] = []; const appointmentCreate = jest.fn(async ({ data }) => { const appointment = { - id: 'appointment-1', + id: `appointment-${storedAppointments.length + 1}`, ...data, created_at: new Date(), updated_at: new Date(), @@ -126,9 +160,9 @@ describe('AppointmentsService.createPending — associação e atomicidade', () storedAppointments.push(appointment); return appointment; }); - const processCreate = jest.fn(async () => { + const processCreate = jest.fn(async ({ data }) => { if (options.processFailure) throw options.processFailure; - const process = { id: 'process-1' }; + const process = { id: `process-${storedProcesses.length + 1}`, ...data }; storedProcesses.push(process); return process; }); @@ -312,6 +346,99 @@ describe('AppointmentsService.createPending — associação e atomicidade', () }); }); + it.each([false, true])( + 'checks the new request after rejection regardless of record order (reverse=%s)', + async (reverse) => { + const { service, prisma, tx, storedAppointments, storedProcesses } = + harness({}); + const matches = (row: any, where: any) => + Object.entries(where).every(([key, value]) => + value !== null && typeof value === 'object' && 'in' in value + ? (value.in as unknown[]).includes(row[key]) + : row[key] === value, + ); + tx.process.findFirst.mockImplementation( + async ({ where }) => + storedProcesses.find((row) => matches(row, where)) ?? null, + ); + prisma.appointment.findFirst.mockImplementation(async ({ where }) => { + const { process: processFilter, ...appointmentFilter } = where; + const rows = reverse + ? [...storedAppointments].reverse() + : storedAppointments; + for (const appointment of rows) { + const process = storedProcesses.find( + (row) => row.appointment_id === appointment.id, + ); + if ( + matches(appointment, appointmentFilter) && + process && + matches(process, processFilter.is) + ) { + return { ...appointment, process }; + } + } + return null; + }); + + await service.createPending(dto, client.id, UserRole.CUSTOMER); + // Rejecting a process preserves the original PENDING appointment. + storedProcesses[0].status = ProcessStatus.REJECTED; + const replacement = await service.createPending( + dto, + client.id, + UserRole.CUSTOMER, + ); + + expect( + await service.findExistingAppointment( + client.id, + specialist.id, + ProductType.CAR, + activeProduct.id, + ), + ).toEqual({ + exists: true, + appointment_id: replacement.id, + process_id: replacement.process_id, + appointment_status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date(dto.appointment_datetime!), + }); + + storedProcesses[1].status = ProcessStatus.REJECTED; + expect( + await service.findExistingAppointment( + client.id, + specialist.id, + ProductType.CAR, + activeProduct.id, + ), + ).toEqual({ exists: false }); + }, + ); + + it.each([ + '2099-01-01T07:00:00-03:00', + '2099-01-01T15:30:00+05:30', + '2099-01-01T07:00:00-0300', + ])( + 'persists the exact instant of a product EMAIL proposal with offset %s', + async (datetime) => { + const { service } = harness({}); + await expect( + service.createPending( + { ...dto, appointment_datetime: datetime }, + client.id, + UserRole.CUSTOMER, + ), + ).resolves.toMatchObject({ + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + status: StatusAgendamento.PENDING, + }); + }, + ); + it('does not lock or check schedule availability for an EMAIL proposal', async () => { const { service, tx } = harness({}); @@ -354,18 +481,43 @@ describe('AppointmentsService.createPending — associação e atomicidade', () ); }); - it.each(['not-a-date', '2000-01-01T00:00:00.000Z'])( - 'rejects an invalid or past product EMAIL date %s', + it.each([ + 'not-a-date', + '2099-01-01', + '2099-01-01T10:00:00', + '2099-01-01T10:00:00.000', + '2099-02-30T10:00:00Z', + '2099-01-01T10:00:00+25:00', + '2000-01-01T00:00:00.000Z', + '2026-10-14T12:00:00.000Z', + '2026-10-14T09:00:00-03:00', + ])( + 'rejects an invalid, ambiguous, past or current product EMAIL date %s before writes', async (datetime) => { - const { service, appointmentCreate } = harness({}); - await expect( - service.createPending( - { ...dto, appointment_datetime: datetime }, - client.id, - UserRole.CUSTOMER, - ), - ).rejects.toThrow(BadRequestException); - expect(appointmentCreate).not.toHaveBeenCalled(); + jest.useFakeTimers().setSystemTime(new Date('2026-10-14T12:00:00.000Z')); + try { + const { + service, + prisma, + appointmentCreate, + processCreate, + historyCreate, + } = harness({}); + await expect( + service.createPending( + { ...dto, appointment_datetime: datetime }, + client.id, + UserRole.CUSTOMER, + ), + ).rejects.toThrow(BadRequestException); + expect(prisma.user.findUnique).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + expect(appointmentCreate).not.toHaveBeenCalled(); + expect(processCreate).not.toHaveBeenCalled(); + expect(historyCreate).not.toHaveBeenCalled(); + } finally { + jest.useRealTimers(); + } }, ); @@ -496,6 +648,9 @@ describe('AppointmentsService.createPending — associação e atomicidade', () it.each([ 'not-a-date', '01/01/2099', + '2099-01-01', + '2099-01-01T10:00:00', + '2099-01-01T10:00:00.000', '2000-01-01T00:00:00.000Z', '2026-10-14T12:00:00.000Z', ])( @@ -645,6 +800,22 @@ describe('AppointmentsService.findExistingAppointment — own minimal projection specialist_id: 'specialist-1', product_type: ProductType.CAR, product_id: 'car-1', + process: { + is: { + client_id: 'client-1', + specialist_id: 'specialist-1', + product_type: ProductType.CAR, + car_id: 'car-1', + status: { + in: [ + ProcessStatus.SCHEDULING, + ProcessStatus.NEGOTIATION, + ProcessStatus.PROCESSING_CONTRACT, + ProcessStatus.DOCUMENTATION, + ], + }, + }, + }, }), select: { id: true, diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 51fb4f8..8c70225 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -13,6 +13,7 @@ import { CreatePendingAppointmentDto, CreatePlatformAppointmentDto, GetAppointmentsQueryDto, + PENDING_APPOINTMENT_DATETIME_PATTERN, UpdateAppointmentStatusDto, } from './dto'; import { @@ -43,7 +44,10 @@ import { CalendlyIntegrationService } from './calendly-integration.service'; import { buildNegotiationSnapshotUpdate } from 'src/features/processes/negotiation-snapshot'; import { lockNegotiationProductMoney } from 'src/features/products/product-monetary-lock'; import { validateSpecialistProductAssociation } from 'src/features/products/product-association-validator'; -import { lockAndAssertNoActiveProcess } from 'src/features/processes/process-dedup-lock'; +import { + ACTIVE_PROCESS_STATUSES, + lockAndAssertNoActiveProcess, +} from 'src/features/processes/process-dedup-lock'; import { acquireSpecialistScheduleLock, assertSpecialistScheduleAvailable, @@ -1038,12 +1042,13 @@ export class AppointmentsService { if ( hasDate && (typeof dto.appointment_datetime !== 'string' || + !PENDING_APPOINTMENT_DATETIME_PATTERN.test(dto.appointment_datetime) || !isISO8601(dto.appointment_datetime, { strict: true }) || !pendingDateTime || !isFutureDate(pendingDateTime)) ) { throw new BadRequestException( - 'Data/hora do agendamento deve ser uma data ISO 8601 futura válida', + 'Data/hora do agendamento deve ser ISO 8601 futura válida com Z ou offset explícito', ); } if ( @@ -1684,6 +1689,12 @@ export class AppointmentsService { productType: ProductType, productId: string, ): Promise { + const productField = + productType === ProductType.CAR + ? 'car_id' + : productType === ProductType.BOAT + ? 'boat_id' + : 'aircraft_id'; const appointment = await this.prisma.appointment.findFirst({ where: { client_id: clientId, @@ -1693,7 +1704,15 @@ export class AppointmentsService { status: { in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], }, - process: { is: { client_id: clientId } }, + process: { + is: { + client_id: clientId, + specialist_id: specialistId, + product_type: productType, + [productField]: productId, + status: { in: ACTIVE_PROCESS_STATUSES }, + }, + }, }, select: { id: true, diff --git a/backend/src/features/appointments/dto/create-pending-appointment.dto.ts b/backend/src/features/appointments/dto/create-pending-appointment.dto.ts index 9f4351d..41b50ad 100644 --- a/backend/src/features/appointments/dto/create-pending-appointment.dto.ts +++ b/backend/src/features/appointments/dto/create-pending-appointment.dto.ts @@ -1,8 +1,11 @@ import { AppointmentSchedulingMethod } from '@prisma/client'; import { OmitType } from '@nestjs/mapped-types'; -import { IsDateString, IsIn, IsOptional } from 'class-validator'; +import { IsDateString, IsIn, IsOptional, Matches } from 'class-validator'; import { CreateAppointmentDto } from './create-appointment.dto'; +export const PENDING_APPOINTMENT_DATETIME_PATTERN = + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})$/; + export class CreatePendingAppointmentDto extends OmitType( CreateAppointmentDto, ['appointment_datetime'] as const, @@ -12,6 +15,10 @@ export class CreatePendingAppointmentDto extends OmitType( { strict: true }, { message: 'appointment_datetime deve ser uma data ISO 8601 válida' }, ) + @Matches(PENDING_APPOINTMENT_DATETIME_PATTERN, { + message: + 'appointment_datetime deve incluir data, hora e Z ou offset explícito', + }) appointment_datetime?: string; @IsOptional() diff --git a/backend/src/features/products/product-association-concurrency.postgres.spec.ts b/backend/src/features/products/product-association-concurrency.postgres.spec.ts index 817b92d..af35fd8 100644 --- a/backend/src/features/products/product-association-concurrency.postgres.spec.ts +++ b/backend/src/features/products/product-association-concurrency.postgres.spec.ts @@ -1,5 +1,11 @@ import { randomUUID } from 'node:crypto'; -import { PrismaClient, ProductCurrency, ProductType, UserRole } from '@prisma/client'; +import { + AppointmentSchedulingMethod, + PrismaClient, + ProductCurrency, + ProductType, + UserRole, +} from '@prisma/client'; import { BadRequestException } from '@nestjs/common'; import { ConflictException } from '@nestjs/common'; import { CarsService } from '../cars/cars.service'; @@ -93,27 +99,9 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = const clientId = randomUUID(); const specialistId = randomUUID(); const carId = randomUUID(); - const updater = new PrismaClient({ - datasources: { - db: { - url: withApplicationName(databaseUrl!, `product_mutation_${suffix}`), - }, - }, - }); - const creator = new PrismaClient({ - datasources: { - db: { - url: withApplicationName(databaseUrl!, `product_consumer_${suffix}`), - }, - }, - }); - const competitor = new PrismaClient({ - datasources: { - db: { - url: withApplicationName(databaseUrl!, `product_competitor_${suffix}`), - }, - }, - }); + let updater: PrismaClient; + let creator: PrismaClient; + let competitor: PrismaClient; beforeEach(async () => { const processes = await updater.process.findMany({ @@ -140,6 +128,27 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = }); beforeAll(async () => { + updater = new PrismaClient({ + datasources: { + db: { + url: withApplicationName(databaseUrl!, `product_mutation_${suffix}`), + }, + }, + }); + creator = new PrismaClient({ + datasources: { + db: { + url: withApplicationName(databaseUrl!, `product_consumer_${suffix}`), + }, + }, + }); + competitor = new PrismaClient({ + datasources: { + db: { + url: withApplicationName(databaseUrl!, `product_competitor_${suffix}`), + }, + }, + }); await updater.user.createMany({ data: [ { @@ -179,17 +188,26 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = }); afterAll(async () => { - await updater.process.deleteMany({ - where: { client_id: clientId, specialist_id: specialistId }, - }); - await updater.appointment.deleteMany({ - where: { client_id: clientId, specialist_id: specialistId }, - }); - await updater.car.deleteMany({ where: { id: carId } }); - await updater.user.deleteMany({ - where: { id: { in: [clientId, specialistId] } }, - }); - await Promise.all([updater.$disconnect(), creator.$disconnect(), competitor.$disconnect()]); + try { + if (updater) { + await updater.process.deleteMany({ + where: { client_id: clientId, specialist_id: specialistId }, + }); + await updater.appointment.deleteMany({ + where: { client_id: clientId, specialist_id: specialistId }, + }); + await updater.car.deleteMany({ where: { id: carId } }); + await updater.user.deleteMany({ + where: { id: { in: [clientId, specialistId] } }, + }); + } + } finally { + await Promise.all([ + updater?.$disconnect(), + creator?.$disconnect(), + competitor?.$disconnect(), + ]); + } }); it('serializes deactivation against creation and rejects the now-inactive product', async () => { @@ -208,14 +226,15 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = const deactivate = cars.remove(carId); await mutationReached.promise; - const create = appointments.create( + const create = appointments.createPending( { client_id: clientId, specialist_id: specialistId, product_type: ProductType.CAR, product_id: carId, appointment_datetime: '2099-01-01T10:00:00.000Z', - } as any, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + }, clientId, UserRole.CUSTOMER, ); @@ -225,6 +244,7 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = await expect(deactivate).resolves.toEqual({ ok: true }); await expect(create).rejects.toBeInstanceOf(BadRequestException); await expect(updater.appointment.count({ where: { product_id: carId } })).resolves.toBe(0); + await expect(updater.process.count({ where: { car_id: carId } })).resolves.toBe(0); }, 15_000); it('serializes late assignment against creation on the target product identity', async () => { @@ -273,14 +293,15 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = sendAppointmentCreatedEmail: jest.fn().mockResolvedValue(undefined), } as any, {} as any, - ).create( + ).createPending( { client_id: clientId, specialist_id: specialistId, product_type: ProductType.CAR, product_id: carId, appointment_datetime: '2099-01-01T10:00:00.000Z', - } as any, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + }, clientId, UserRole.CUSTOMER, ); @@ -293,6 +314,14 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ reason: expect.any(ConflictException), }); + if (outcomes[1].status === 'fulfilled') { + expect(outcomes[1].value).toMatchObject({ + status: 'PENDING', + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + process_id: expect.any(String), + }); + } await expect( updater.process.count({ where: { From 38b5b50233c90a79bef2b539249fbbc6f051f883 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 08:31:38 -0300 Subject: [PATCH 08/60] test: remove fixture histories before restricted processes --- ...t-association-concurrency.postgres.spec.ts | 91 ++++++++++++++++++- 1 file changed, 88 insertions(+), 3 deletions(-) diff --git a/backend/src/features/products/product-association-concurrency.postgres.spec.ts b/backend/src/features/products/product-association-concurrency.postgres.spec.ts index af35fd8..7b54b50 100644 --- a/backend/src/features/products/product-association-concurrency.postgres.spec.ts +++ b/backend/src/features/products/product-association-concurrency.postgres.spec.ts @@ -91,6 +91,93 @@ function signalProductLockAttempt(client: PrismaClient, attempted: Deferred) { }); } +async function deleteFixtureProcesses( + client: PrismaClient, + clientId: string, + specialistId: string, +): Promise { + const processes = await client.process.findMany({ + where: { client_id: clientId, specialist_id: specialistId }, + select: { id: true }, + }); + const processIds = processes.map(({ id }) => id); + await client.processStatusHistory.deleteMany({ + where: { processId: { in: processIds } }, + }); + await client.process.deleteMany({ + where: { id: { in: processIds } }, + }); +} + +describe('product association fixture cleanup', () => { + it('removes restricted history before its own processes and preserves other fixtures', async () => { + const clientId = 'fixture-client'; + const specialistId = 'fixture-specialist'; + let processes = [ + { id: 'own-process', client_id: clientId, specialist_id: specialistId }, + { + id: 'other-client-process', + client_id: 'other-client', + specialist_id: specialistId, + }, + { + id: 'other-specialist-process', + client_id: clientId, + specialist_id: 'other-specialist', + }, + ]; + let history = processes.map(({ id }) => ({ processId: id })); + const deletionOrder: string[] = []; + const client = { + process: { + findMany: async ({ where }: any) => + processes + .filter( + (row) => + row.client_id === where.client_id && + row.specialist_id === where.specialist_id, + ) + .map(({ id }) => ({ id })), + deleteMany: async ({ where }: any) => { + const targets = processes + .filter((row) => + where.id + ? where.id.in.includes(row.id) + : row.client_id === where.client_id && + row.specialist_id === where.specialist_id, + ) + .map(({ id }) => id); + if (history.some(({ processId }) => targets.includes(processId))) { + throw new Error('ProcessStatusHistory FK RESTRICT'); + } + processes = processes.filter(({ id }) => !targets.includes(id)); + deletionOrder.push('process'); + }, + }, + processStatusHistory: { + deleteMany: async ({ where }: any) => { + history = history.filter( + ({ processId }) => !where.processId.in.includes(processId), + ); + deletionOrder.push('history'); + }, + }, + } as unknown as PrismaClient; + + await deleteFixtureProcesses(client, clientId, specialistId); + + expect(deletionOrder).toEqual(['history', 'process']); + expect(processes.map(({ id }) => id)).toEqual([ + 'other-client-process', + 'other-specialist-process', + ]); + expect(history.map(({ processId }) => processId)).toEqual([ + 'other-client-process', + 'other-specialist-process', + ]); + }); +}); + const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL; const describeWithPostgres = databaseUrl ? describe : describe.skip; @@ -190,9 +277,7 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = afterAll(async () => { try { if (updater) { - await updater.process.deleteMany({ - where: { client_id: clientId, specialist_id: specialistId }, - }); + await deleteFixtureProcesses(updater, clientId, specialistId); await updater.appointment.deleteMany({ where: { client_id: clientId, specialist_id: specialistId }, }); From 3b122230c226e0776f8e5f488f39779b516f14ea Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 08:50:42 -0300 Subject: [PATCH 09/60] fix: confirm email proposals under schedule lock --- .../appointments-concurrency.postgres.spec.ts | 937 ++++++++++-------- .../appointments/appointments.service.spec.ts | 73 ++ .../appointments/appointments.service.ts | 15 +- .../entity/process.response.entity.ts | 6 +- .../processes/processes.controller.spec.ts | 33 +- .../processes/processes.controller.ts | 6 + .../processes/processes.service.spec.ts | 598 ++++++++++- .../features/processes/processes.service.ts | 265 +++-- 8 files changed, 1363 insertions(+), 570 deletions(-) diff --git a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts index c16b71b..05e5700 100644 --- a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts +++ b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts @@ -2,12 +2,15 @@ import { randomUUID } from 'node:crypto'; import { ConflictException } from '@nestjs/common'; import { AppointmentSchedulingMethod, + CalendlySyncStatus, PrismaClient, + ProcessStatus, ProductCurrency, ProductType, StatusAgendamento, UserRole, } from '@prisma/client'; +import { ProcessesService } from '../processes/processes.service'; import { AppointmentsService } from './appointments.service'; type Deferred = { promise: Promise; resolve: () => void }; @@ -31,25 +34,33 @@ function bindMember(target: any, property: PropertyKey): any { } function signalScheduleLockAttempt(client: PrismaClient, attempted: Deferred) { - const wrapTransaction = (tx: any) => - new Proxy(tx, { - get(target, property) { - if (property === '$queryRaw') { - return (strings: TemplateStringsArray, ...values: unknown[]) => { - if (String(values[0]).startsWith('appointment-schedule:')) { - attempted.resolve(); - } - return target.$queryRaw(strings, ...values); - }; - } - return bindMember(target, property); - }, - }); return new Proxy(client, { get(target, property) { if (property === '$transaction') { return (callback: (tx: any) => Promise, options?: any) => - target.$transaction((tx) => callback(wrapTransaction(tx)), options); + target.$transaction( + (tx) => + callback( + new Proxy(tx, { + get(transaction, member) { + if (member === '$queryRaw') { + return ( + strings: TemplateStringsArray, + ...values: unknown[] + ) => { + if ( + String(values[0]).startsWith('appointment-schedule:') + ) + attempted.resolve(); + return transaction.$queryRaw(strings, ...values); + }; + } + return bindMember(transaction, member); + }, + }), + ), + options, + ); } return bindMember(target, property); }, @@ -59,420 +70,532 @@ function signalScheduleLockAttempt(client: PrismaClient, attempted: Deferred) { const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL; const describeWithPostgres = databaseUrl ? describe : describe.skip; -describeWithPostgres('appointment schedule lock — PostgreSQL concurrency', () => { - const suffix = randomUUID().replaceAll('-', ''); - const firstClientId = randomUUID(); - const secondClientId = randomUUID(); - const specialistId = randomUUID(); - const firstCarId = randomUUID(); - const secondCarId = randomUUID(); - const first = new PrismaClient({ - datasources: { - db: { url: withApplicationName(databaseUrl!, `schedule_a_${suffix}`) }, - }, - }); - const second = new PrismaClient({ - datasources: { - db: { url: withApplicationName(databaseUrl!, `schedule_b_${suffix}`) }, - }, - }); - const holder = new PrismaClient({ - datasources: { - db: { - url: withApplicationName(databaseUrl!, `schedule_holder_${suffix}`), - }, - }, - }); +describeWithPostgres( + 'appointment schedule lock — PostgreSQL concurrency', + () => { + const suffix = randomUUID().replaceAll('-', ''); + const clientIds = [randomUUID(), randomUUID()]; + const specialistIds = [randomUUID(), randomUUID()]; + const carIds = [randomUUID(), randomUUID(), randomUUID()]; + const specialistId = specialistIds[0]; + const proposedIso = '2099-01-01T10:00:00.000Z'; + const proposedDate = new Date(proposedIso); + let first: PrismaClient; + let second: PrismaClient; + let holder: PrismaClient; + const notifications = { + sendAppointmentConfirmedEmail: jest.fn().mockResolvedValue(undefined), + sendAppointmentRescheduledEmail: jest.fn().mockResolvedValue(undefined), + }; - beforeAll(async () => { - await holder.user.createMany({ - data: [ - { - id: firstClientId, - name: 'First', - surname: 'Client', - email: `schedule-client-a-${suffix}@example.test`, - rg: suffix.slice(0, 10) + '1', - role: UserRole.CUSTOMER, - password_hash: 'not-used', - }, - { - id: secondClientId, - name: 'Second', - surname: 'Client', - email: `schedule-client-b-${suffix}@example.test`, - rg: suffix.slice(0, 10) + '2', - role: UserRole.CUSTOMER, - password_hash: 'not-used', - }, - { - id: specialistId, + beforeAll(async () => { + const client = (name: string) => + new PrismaClient({ + datasources: { + db: { url: withApplicationName(databaseUrl!, `${name}_${suffix}`) }, + }, + }); + first = client('schedule_a'); + second = client('schedule_b'); + holder = client('schedule_holder'); + await holder.user.createMany({ + data: [...clientIds, ...specialistIds].map((id, index) => ({ + id, name: 'Schedule', - surname: 'Specialist', - email: `schedule-specialist-${suffix}@example.test`, - rg: suffix.slice(11, 22), - role: UserRole.SPECIALIST, - speciality: ProductType.CAR, + surname: `Fixture ${index}`, + email: `schedule-${index}-${suffix}@example.test`, + rg: `${suffix.slice(0, 12)}${index}`, + role: index < 2 ? UserRole.CUSTOMER : UserRole.SPECIALIST, + speciality: index < 2 ? null : ProductType.CAR, password_hash: 'not-used', - }, - ], + })), + }); + await holder.car.createMany({ + data: carIds.map((id, index) => ({ + id, + specialist_id: index < 2 ? specialistId : specialistIds[1], + marca: 'Schedule', + modelo: `Car ${index}`, + identificador: `schedule-${index}-${suffix}`, + valor: 100000 + index, + currency: ProductCurrency.BRL, + estado: 'SP', + ano: 2026, + })), + }); }); - await holder.car.createMany({ - data: [firstCarId, secondCarId].map((id, index) => ({ - id, - specialist_id: specialistId, - marca: 'Schedule', - modelo: `Car ${index + 1}`, - identificador: `schedule-${index}-${suffix}`, - valor: 100000 + index, - currency: ProductCurrency.BRL, - estado: 'SP', - ano: 2026, - })), - }); - }); - beforeEach(async () => { - const appointments = await holder.appointment.findMany({ - where: { specialist_id: specialistId }, - select: { id: true }, - }); - const processes = await holder.process.findMany({ - where: { appointment_id: { in: appointments.map(({ id }) => id) } }, - select: { id: true }, - }); - await holder.processStatusHistory.deleteMany({ - where: { processId: { in: processes.map(({ id }) => id) } }, - }); - await holder.process.deleteMany({ - where: { id: { in: processes.map(({ id }) => id) } }, - }); - await holder.appointment.deleteMany({ - where: { id: { in: appointments.map(({ id }) => id) } }, - }); - }); + async function clearAppointments() { + const where = { + specialist_id: { in: specialistIds }, + client_id: { in: clientIds }, + }; + const processes = await holder.process.findMany({ + where, + select: { id: true }, + }); + await holder.processStatusHistory.deleteMany({ + where: { processId: { in: processes.map(({ id }) => id) } }, + }); + await holder.process.deleteMany({ + where: { id: { in: processes.map(({ id }) => id) } }, + }); + await holder.appointment.deleteMany({ where }); + } - afterAll(async () => { - const appointments = await holder.appointment.findMany({ - where: { specialist_id: specialistId }, - select: { id: true }, - }); - await holder.process.deleteMany({ - where: { appointment_id: { in: appointments.map(({ id }) => id) } }, - }); - await holder.appointment.deleteMany({ - where: { specialist_id: specialistId }, - }); - await holder.car.deleteMany({ - where: { id: { in: [firstCarId, secondCarId] } }, + beforeEach(async () => { + await clearAppointments(); + jest.clearAllMocks(); }); - await holder.user.deleteMany({ - where: { id: { in: [firstClientId, secondClientId, specialistId] } }, - }); - await Promise.all([first.$disconnect(), second.$disconnect(), holder.$disconnect()]); - }); - it('allows only one overlapping appointment across different products', async () => { - const lockKey = `appointment-schedule:${specialistId}`; - const holderReady = deferred(); - const releaseHolder = deferred(); - const firstAttempted = deferred(); - const secondAttempted = deferred(); - const held = holder.$transaction(async (tx) => { - await tx.$queryRaw` - SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))::text AS locked - `; - holderReady.resolve(); - await releaseHolder.promise; + afterAll(async () => { + try { + if (holder) { + await clearAppointments(); + await holder.car.deleteMany({ where: { id: { in: carIds } } }); + await holder.user.deleteMany({ + where: { id: { in: [...clientIds, ...specialistIds] } }, + }); + } + } finally { + await Promise.all([ + first?.$disconnect(), + second?.$disconnect(), + holder?.$disconnect(), + ]); + } }); - await holderReady.promise; - const notification = { - sendAppointmentCreatedEmail: jest.fn().mockResolvedValue(undefined), - } as any; - const serviceA = new AppointmentsService( - signalScheduleLockAttempt(first, firstAttempted) as any, - notification, - {} as any, - ); - const serviceB = new AppointmentsService( - signalScheduleLockAttempt(second, secondAttempted) as any, - notification, - {} as any, - ); - const appointment_datetime = '2099-01-01T10:00:00.000Z'; + function appointments(client: PrismaClient, attempted?: Deferred) { + return new AppointmentsService( + (attempted + ? signalScheduleLockAttempt(client, attempted) + : client) as any, + notifications as any, + {} as any, + ); + } - const outcomesPromise = Promise.allSettled([ - serviceA.create( - { - client_id: firstClientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - product_id: firstCarId, - appointment_datetime, - } as any, - firstClientId, - UserRole.CUSTOMER, - ), - serviceB.create( + function processes(client: PrismaClient, attempted: Deferred) { + return new ProcessesService( + signalScheduleLockAttempt(client, attempted) as any, + notifications as any, + ); + } + + function createRequest( + client: PrismaClient, + index: number, + otherSpecialist = false, + ) { + return appointments(client).createPending( { - client_id: secondClientId, - specialist_id: specialistId, + client_id: clientIds[index], + specialist_id: otherSpecialist ? specialistIds[1] : specialistId, product_type: ProductType.CAR, - product_id: secondCarId, - appointment_datetime, - } as any, - secondClientId, + product_id: otherSpecialist ? carIds[2] : carIds[index], + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: proposedIso, + }, + clientIds[index], UserRole.CUSTOMER, - ), - ]); - await Promise.all([firstAttempted.promise, secondAttempted.promise]); - releaseHolder.resolve(); - await held; - const outcomes = await outcomesPromise; - - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); - await expect(holder.appointment.count({ where: { specialist_id: specialistId } })).resolves.toBe(1); - }, 15_000); - - it('allows only one definitive reschedule under concurrent requests', async () => { - const appointment = await holder.appointment.create({ - data: { - client_id: firstClientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - product_id: firstCarId, - status: StatusAgendamento.SCHEDULED, - scheduling_method: AppointmentSchedulingMethod.PLATFORM, - appointment_datetime: new Date('2099-01-01T09:00:00.000Z'), - }, - }); - await holder.process.create({ - data: { - client_id: firstClientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - car_id: firstCarId, - appointment_id: appointment.id, - status: 'SCHEDULING', - }, - }); + ); + } - const releaseHolder = deferred(); - const holderReady = deferred(); - const firstAttempted = deferred(); - const secondAttempted = deferred(); - const held = holdScheduleLock(releaseHolder, holderReady); - await holderReady.promise; - const serviceA = service(first, firstAttempted); - const serviceB = service(second, secondAttempted); - - const outcomesPromise = Promise.allSettled([ - serviceA.reschedule( - appointment.id, - '2099-01-02T10:00:00.000Z', - specialistId, - ), - serviceB.reschedule( - appointment.id, - '2099-01-03T10:00:00.000Z', - specialistId, - ), - ]); - const bothAttemptedBeforeCompletion = await Promise.race([ - Promise.all([firstAttempted.promise, secondAttempted.promise]).then( - () => true, - ), - outcomesPromise.then(() => false), - ]); - releaseHolder.resolve(); - await held; - const outcomes = await outcomesPromise; - - expect(bothAttemptedBeforeCompletion).toBe(true); - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); - const stored = await holder.appointment.findUniqueOrThrow({ - where: { id: appointment.id }, - }); - expect(stored.specialist_rescheduled_at).not.toBeNull(); - expect(stored.specialist_rescheduled_from).toEqual( - new Date('2099-01-01T09:00:00.000Z'), - ); - }, 15_000); + // Force both service calls to attempt the real advisory lock while it is held. + // Release even on an early failure so a broken prerequisite cannot hang Jest. + async function race( + start: (a: Deferred, b: Deferred) => [Promise, Promise], + lockSpecialist = specialistId, + ) { + const ready = deferred(); + const release = deferred(); + const a = deferred(); + const b = deferred(); + const held = holder.$transaction(async (tx) => { + const key = `appointment-schedule:${lockSpecialist}`; + await tx.$queryRaw`SELECT pg_advisory_xact_lock(hashtextextended(${key}, 0))::text AS locked`; + ready.resolve(); + await release.promise; + }); + await ready.promise; + const calls = start(a, b); + const outcomes = Promise.allSettled(calls); + let bothAttempted: boolean; + try { + bothAttempted = await Promise.race([ + Promise.all([a.promise, b.promise]).then(() => true), + Promise.race( + calls.map((call) => + call.then( + () => false, + () => false, + ), + ), + ), + ]); + } finally { + release.resolve(); + await held; + } + const result = await outcomes; + expect(bothAttempted).toBe(true); + return result; + } - async function createPendingWithProcess(clientId: string, carId: string) { - const appointment = await holder.appointment.create({ - data: { - client_id: clientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - product_id: carId, - status: 'PENDING', - }, - }); - await holder.process.create({ - data: { - client_id: clientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - car_id: carId, - appointment_id: appointment.id, - status: 'SCHEDULING', - }, - }); - return appointment; - } + it('allows concurrent dated EMAIL proposals for the same specialist/time', async () => { + const outcomes = await Promise.allSettled([ + createRequest(first, 0), + createRequest(second, 1), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(2); + expect( + await holder.appointment.count({ + where: { + specialist_id: specialistId, + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: proposedDate, + }, + }), + ).toBe(2); + expect( + await holder.process.count({ + where: { + specialist_id: specialistId, + status: ProcessStatus.SCHEDULING, + }, + }), + ).toBe(2); + expect( + await holder.processStatusHistory.count({ + where: { process: { specialist_id: specialistId } }, + }), + ).toBe(2); + }, 15_000); - async function holdScheduleLock(release: Deferred, ready: Deferred) { - const lockKey = `appointment-schedule:${specialistId}`; - return holder.$transaction(async (tx) => { - await tx.$queryRaw` - SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))::text AS locked - `; - ready.resolve(); - await release.promise; - }); - } + it('serializes canonical confirmations and leaves the losing request completely pending', async () => { + const firstRequest = await createRequest(holder, 0); + const secondRequest = await createRequest(holder, 1); + const before = await holder.process.findMany({ + where: { + id: { in: [firstRequest.process_id, secondRequest.process_id] }, + }, + include: { appointment: true }, + }); + const outcomes = await race((a, b) => [ + processes(first, a).confirmAppointment( + firstRequest.process_id, + specialistId, + proposedIso, + ), + processes(second, b).confirmAppointment( + secondRequest.process_id, + specialistId, + proposedIso, + ), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + const failure = outcomes.find( + ({ status }) => status === 'rejected', + ) as PromiseRejectedResult; + expect(failure.reason).toBeInstanceOf(ConflictException); + const loserIndex = outcomes.findIndex( + ({ status }) => status === 'rejected', + ); + const loserId = [firstRequest.process_id, secondRequest.process_id][ + loserIndex + ]; + expect( + await holder.process.findUniqueOrThrow({ + where: { id: loserId }, + include: { appointment: true }, + }), + ).toEqual(before.find(({ id }) => id === loserId)); + expect( + await holder.appointment.count({ + where: { + specialist_id: specialistId, + appointment_datetime: proposedDate, + status: StatusAgendamento.SCHEDULED, + }, + }), + ).toBe(1); + expect( + await holder.process.count({ + where: { + specialist_id: specialistId, + status: ProcessStatus.SCHEDULING, + }, + }), + ).toBe(2); + expect( + await holder.processStatusHistory.count({ + where: { process: { specialist_id: specialistId } }, + }), + ).toBe(2); + }, 15_000); - function service(client: PrismaClient, attempted: Deferred) { - return new AppointmentsService( - signalScheduleLockAttempt(client, attempted) as any, - { - sendAppointmentCreatedEmail: jest.fn().mockResolvedValue(undefined), - sendAppointmentConfirmedEmail: jest.fn().mockResolvedValue(undefined), - sendAppointmentRescheduledEmail: jest.fn().mockResolvedValue(undefined), - } as any, - {} as any, - ); - } + it('allows different specialists to confirm the same instant', async () => { + const firstRequest = await createRequest(holder, 0); + const secondRequest = await createRequest(holder, 1, true); + const outcomes = await Promise.allSettled([ + new ProcessesService( + first as any, + notifications as any, + ).confirmAppointment( + firstRequest.process_id, + specialistId, + proposedIso, + ), + new ProcessesService( + second as any, + notifications as any, + ).confirmAppointment( + secondRequest.process_id, + specialistIds[1], + proposedIso, + ), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(2); + expect( + await holder.appointment.count({ + where: { + specialist_id: { in: specialistIds }, + status: StatusAgendamento.SCHEDULED, + appointment_datetime: proposedDate, + }, + }), + ).toBe(2); + }, 15_000); - it('serializes direct create against confirming an overlapping pending appointment', async () => { - const pending = await createPendingWithProcess(secondClientId, secondCarId); - const release = deferred(); - const ready = deferred(); - const createAttempted = deferred(); - const confirmAttempted = deferred(); - const held = holdScheduleLock(release, ready); - await ready.promise; - const serviceA = service(first, createAttempted); - const serviceB = service(second, confirmAttempted); - const scheduledAt = new Date('2099-01-01T10:00:00.000Z'); + it('makes a concurrent double-click idempotent without duplicate notes, histories or emails', async () => { + const request = await createRequest(holder, 0); + const outcomes = await race((a, b) => [ + processes(first, a).confirmAppointment( + request.process_id, + specialistId, + proposedIso, + ), + processes(second, b).confirmAppointment( + request.process_id, + specialistId, + proposedIso, + ), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(2); + expect(outcomes[0]).toEqual(outcomes[1]); + const stored = await holder.process.findUniqueOrThrow({ + where: { id: request.process_id }, + include: { appointment: true }, + }); + expect(stored.status).toBe(ProcessStatus.SCHEDULING); + expect( + stored.notes?.match(/Agendamento confirmado pelo especialista/g), + ).toHaveLength(1); + expect(stored.appointment).toMatchObject({ + status: StatusAgendamento.SCHEDULED, + appointment_datetime: proposedDate, + specialist_rescheduled_at: null, + specialist_rescheduled_from: null, + }); + expect( + await holder.processStatusHistory.count({ + where: { processId: stored.id }, + }), + ).toBe(1); + expect( + await holder.appointment.count({ + where: { specialist_id: specialistId }, + }), + ).toBe(1); + await new Promise((resolve) => setImmediate(resolve)); + expect(notifications.sendAppointmentConfirmedEmail).toHaveBeenCalledTimes( + 1, + ); + }, 15_000); - const creating = serviceA.create( - { - client_id: firstClientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - product_id: firstCarId, - appointment_datetime: scheduledAt.toISOString(), - } as any, - firstClientId, - UserRole.CUSTOMER, - ); - const confirming = serviceB.confirmPending(pending.id, specialistId, scheduledAt); - const bothAttemptedBeforeCompletion = await Promise.race([ - Promise.all([createAttempted.promise, confirmAttempted.promise]).then(() => true), - confirming.then( - () => false, - () => false, - ), - ]); - release.resolve(); - await held; - const outcomes = await Promise.allSettled([creating, confirming]); + it('rolls back the process claim if appointment persistence fails', async () => { + const request = await createRequest(holder, 0); + const before = await holder.process.findUniqueOrThrow({ + where: { id: request.process_id }, + include: { appointment: true }, + }); + const failingStorage = new Proxy(first, { + get(target, property) { + if (property === '$transaction') + return (callback: any) => + target.$transaction((tx) => + callback( + new Proxy(tx, { + get(transaction, member) { + if (member === 'appointment') + return new Proxy(transaction.appointment, { + get(repository, action) { + if (action === 'update') + return async () => { + throw new Error( + 'appointment persistence failed', + ); + }; + return bindMember(repository, action); + }, + }); + return bindMember(transaction, member); + }, + }), + ), + ); + return bindMember(target, property); + }, + }); + await expect( + new ProcessesService( + failingStorage as any, + notifications as any, + ).confirmAppointment(request.process_id, specialistId, proposedIso), + ).rejects.toThrow('appointment persistence failed'); + expect( + await holder.process.findUniqueOrThrow({ + where: { id: request.process_id }, + include: { appointment: true }, + }), + ).toEqual(before); + expect( + await holder.processStatusHistory.count({ + where: { processId: request.process_id }, + }), + ).toBe(1); + expect( + notifications.sendAppointmentConfirmedEmail, + ).not.toHaveBeenCalled(); + }, 15_000); - expect(bothAttemptedBeforeCompletion).toBe(true); - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); - }, 15_000); + it('allows only one definitive reschedule under concurrent requests', async () => { + const request = await createRequest(holder, 0); + await new ProcessesService( + holder as any, + notifications as any, + ).confirmAppointment(request.process_id, specialistId, proposedIso); + const outcomes = await race((a, b) => [ + appointments(first, a).reschedule( + request.id, + '2099-01-02T10:00:00Z', + specialistId, + ), + appointments(second, b).reschedule( + request.id, + '2099-01-03T10:00:00Z', + specialistId, + ), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + expect( + outcomes.find(({ status }) => status === 'rejected'), + ).toMatchObject({ reason: expect.any(ConflictException) }); + const stored = await holder.appointment.findUniqueOrThrow({ + where: { id: request.id }, + }); + expect(stored.specialist_rescheduled_at).not.toBeNull(); + expect(stored.specialist_rescheduled_from).toEqual(proposedDate); + }, 15_000); - it('serializes two confirmations that select the same specialist time', async () => { - const firstPending = await createPendingWithProcess(firstClientId, firstCarId); - const secondPending = await createPendingWithProcess(secondClientId, secondCarId); - const release = deferred(); - const ready = deferred(); - const firstAttempted = deferred(); - const secondAttempted = deferred(); - const held = holdScheduleLock(release, ready); - await ready.promise; - const serviceA = service(first, firstAttempted); - const serviceB = service(second, secondAttempted); - const scheduledAt = new Date('2099-01-01T11:00:00.000Z'); - const firstConfirm = serviceA.confirmPending(firstPending.id, specialistId, scheduledAt); - const secondConfirm = serviceB.confirmPending(secondPending.id, specialistId, scheduledAt); - const bothAttemptedBeforeCompletion = await Promise.race([ - Promise.all([firstAttempted.promise, secondAttempted.promise]).then(() => true), - Promise.allSettled([firstConfirm, secondConfirm]).then(() => false), - ]); - release.resolve(); - await held; - const outcomes = await Promise.allSettled([firstConfirm, secondConfirm]); + async function calendlyRequest(index: number) { + return holder.appointment.create({ + data: { + client_id: clientIds[index], + specialist_id: specialistId, + product_type: ProductType.CAR, + product_id: carIds[index], + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + }, + }); + } - expect(bothAttemptedBeforeCompletion).toBe(true); - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); - }, 15_000); + function callback( + client: PrismaClient, + attempted: Deferred, + appointment: { id: string }, + index: number, + ) { + return appointments(client, attempted).registerCalendlyScheduled( + appointment.id, + clientIds[index], + { + event_uri: `https://calendly.test/events/${appointment.id}`, + invitee_uri: `https://calendly.test/invitees/${appointment.id}`, + scheduled_start_time: proposedIso, + }, + ); + } - it('serializes two Calendly callbacks that resolve to an overlapping time', async () => { - const firstPending = await holder.appointment.create({ - data: { - client_id: firstClientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - product_id: firstCarId, - status: 'PENDING', - }, - }); - const secondPending = await holder.appointment.create({ - data: { - client_id: secondClientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - product_id: secondCarId, - status: 'PENDING', - }, - }); - const release = deferred(); - const ready = deferred(); - const firstAttempted = deferred(); - const secondAttempted = deferred(); - const held = holdScheduleLock(release, ready); - await ready.promise; - const serviceA = service(first, firstAttempted); - const serviceB = service(second, secondAttempted); - const scheduledStart = '2099-01-01T12:00:00.000Z'; - const firstRegister = serviceA.registerCalendlyScheduled(firstPending.id, firstClientId, { - event_uri: `https://calendly.test/events/${firstPending.id}`, - invitee_uri: `https://calendly.test/invitees/${firstPending.id}`, - scheduled_start_time: scheduledStart, - }); - const secondRegister = serviceB.registerCalendlyScheduled(secondPending.id, secondClientId, { - event_uri: `https://calendly.test/events/${secondPending.id}`, - invitee_uri: `https://calendly.test/invitees/${secondPending.id}`, - scheduled_start_time: scheduledStart, - }); - const bothAttemptedBeforeCompletion = await Promise.race([ - Promise.all([firstAttempted.promise, secondAttempted.promise]).then(() => true), - Promise.allSettled([firstRegister, secondRegister]).then(() => false), - ]); - release.resolve(); - await held; - const outcomes = await Promise.allSettled([firstRegister, secondRegister]); + it('serializes two Calendly callbacks that resolve to an overlapping time', async () => { + const a = await calendlyRequest(0); + const b = await calendlyRequest(1); + const outcomes = await race((firstAttempt, secondAttempt) => [ + callback(first, firstAttempt, a, 0), + callback(second, secondAttempt, b, 1), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + expect( + outcomes.find(({ status }) => status === 'rejected'), + ).toMatchObject({ reason: expect.any(ConflictException) }); + expect( + await holder.appointment.count({ + where: { + specialist_id: specialistId, + calendly_sync_status: CalendlySyncStatus.SYNCED, + }, + }), + ).toBe(1); + }, 15_000); - expect(bothAttemptedBeforeCompletion).toBe(true); - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); - }, 15_000); -}); + it('serializes the canonical confirmation against a Calendly callback', async () => { + const request = await createRequest(holder, 0); + const pendingCalendly = await calendlyRequest(1); + const outcomes = await race((a, b) => [ + processes(first, a).confirmAppointment( + request.process_id, + specialistId, + proposedIso, + ), + callback(second, b, pendingCalendly, 1), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + expect( + outcomes.find(({ status }) => status === 'rejected'), + ).toMatchObject({ reason: expect.any(ConflictException) }); + expect( + await holder.appointment.count({ + where: { + specialist_id: specialistId, + appointment_datetime: proposedDate, + OR: [ + { status: StatusAgendamento.SCHEDULED }, + { + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + calendly_sync_status: CalendlySyncStatus.SYNCED, + }, + ], + }, + }), + ).toBe(1); + }, 15_000); + }, +); diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts index e1f8d33..6086252 100644 --- a/backend/src/features/appointments/appointments.service.spec.ts +++ b/backend/src/features/appointments/appointments.service.spec.ts @@ -1866,3 +1866,76 @@ describe('AppointmentsService.reschedule — alteração definitiva', () => { }); }); }); + +describe('AppointmentsService — sugestões compartilham ocupação da agenda', () => { + const requested = new Date('2099-01-01T10:00:00Z'); + it.each([ + [ + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + 'PENDING', + 11, + ], + [ + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.CALENDLY, + 'PENDING', + 11, + ], + [ + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.CALENDLY, + 'SYNCED', + 13, + ], + [StatusAgendamento.PENDING, null, 'PENDING', 13], + [ + StatusAgendamento.SCHEDULED, + AppointmentSchedulingMethod.EMAIL, + 'PENDING', + 13, + ], + ])( + 'suggestions respect %s/%s/%s including the one-hour boundary', + async (status, method, sync, firstHour) => { + const record: Record = { + specialist_id: 'specialist-1', + status, + scheduling_method: method, + calendly_sync_status: sync, + appointment_datetime: new Date('2099-01-01T11:00:00Z'), + }; + const findFirst = jest.fn(async ({ where }) => { + const branches = where.OR ?? [{ status: where.status }]; + const occupied = branches.some((branch: any) => + Object.entries(branch).every(([key, value]) => record[key] === value), + ); + const inWindow = + record.appointment_datetime >= where.appointment_datetime.gte && + record.appointment_datetime <= where.appointment_datetime.lte; + return occupied && inWindow ? { id: 'occupied' } : null; + }); + const service = new AppointmentsService( + { appointment: { findFirst } } as any, + {} as any, + {} as any, + ); + expect( + await (service as any).suggestAlternativeTimes( + 'specialist-1', + requested, + ), + ).toEqual( + [0, 1, 2].map( + (offset) => `2099-01-01T${Number(firstHour) + offset}:00:00.000Z`, + ), + ); + expect(findFirst).toHaveBeenCalledWith( + expect.objectContaining({ + select: { id: true }, + where: expect.objectContaining({ OR: expect.any(Array) }), + }), + ); + }, + ); +}); diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 8c70225..0bc0ac6 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -51,6 +51,7 @@ import { import { acquireSpecialistScheduleLock, assertSpecialistScheduleAvailable, + buildOccupiedScheduleWhere, lockAndAssertSpecialistScheduleAvailable, } from './appointment-schedule-lock'; @@ -771,19 +772,9 @@ export class AppointmentsService { // Avançar 1 hora checkTime = new Date(checkTime.getTime() + 60 * 60 * 1000); - // Verificar se este horário está livre - const conflictStart = new Date(checkTime.getTime() - 60 * 60 * 1000); - const conflictEnd = new Date(checkTime.getTime() + 60 * 60 * 1000); - const conflict = await this.prisma.appointment.findFirst({ - where: { - specialist_id: specialistId, - appointment_datetime: { - gte: conflictStart, - lte: conflictEnd, - }, - status: StatusAgendamento.SCHEDULED, - }, + where: buildOccupiedScheduleWhere(specialistId, checkTime), + select: { id: true }, }); if (!conflict) { diff --git a/backend/src/features/processes/entity/process.response.entity.ts b/backend/src/features/processes/entity/process.response.entity.ts index b55f96f..b03421b 100644 --- a/backend/src/features/processes/entity/process.response.entity.ts +++ b/backend/src/features/processes/entity/process.response.entity.ts @@ -6,9 +6,7 @@ export class ProcessResponse { appointment_id?: string | null; appointment_status?: $Enums.StatusAgendamento | null; appointment_datetime?: Date | null; - appointment_scheduling_method?: - | $Enums.AppointmentSchedulingMethod - | null; + appointment_scheduling_method?: $Enums.AppointmentSchedulingMethod | null; specialist_rescheduled_at?: Date | null; specialist_rescheduled_from?: Date | null; product_type: $Enums.ProductType | null; // Null para processos de consultoria @@ -16,7 +14,7 @@ export class ProcessResponse { client: { id: string; name: string; - email: string; + email?: string; phone?: string | null; }; specialist: { diff --git a/backend/src/features/processes/processes.controller.spec.ts b/backend/src/features/processes/processes.controller.spec.ts index 069aa67..5c55a1a 100644 --- a/backend/src/features/processes/processes.controller.spec.ts +++ b/backend/src/features/processes/processes.controller.spec.ts @@ -65,7 +65,7 @@ describe('ProcessesController.confirmAppointment', () => { await (controller.confirmAppointment as any)( processId, { appointment_datetime: appointmentDatetime }, - { user: { id: specialistId } }, + { user: { id: specialistId, role: UserRole.SPECIALIST } }, ); expect(service.confirmAppointment).toHaveBeenCalledWith( @@ -74,4 +74,35 @@ describe('ProcessesController.confirmAppointment', () => { appointmentDatetime, ); }); + + it.each([ + UserRole.ADMIN, + UserRole.CUSTOMER, + UserRole.OFFICE, + UserRole.CONSULTANT, + undefined, + ])( + 'rejects role %s before calling the confirmation service', + async (role) => { + const service = { confirmAppointment: jest.fn() } as any; + const controller = new ProcessesController(service); + await expect( + controller.confirmAppointment( + 'process-1', + {}, + { user: { id: 'actor', role } }, + ), + ).rejects.toThrow(ForbiddenException); + expect(service.confirmAppointment).not.toHaveBeenCalled(); + }, + ); + + it('rejects a missing actor before calling the confirmation service', async () => { + const service = { confirmAppointment: jest.fn() } as any; + const controller = new ProcessesController(service); + await expect( + controller.confirmAppointment('process-1', {}, {}), + ).rejects.toThrow(ForbiddenException); + expect(service.confirmAppointment).not.toHaveBeenCalled(); + }); }); diff --git a/backend/src/features/processes/processes.controller.ts b/backend/src/features/processes/processes.controller.ts index c23d155..a3c72a9 100644 --- a/backend/src/features/processes/processes.controller.ts +++ b/backend/src/features/processes/processes.controller.ts @@ -447,6 +447,12 @@ export class ProcessesController { ): Promise> { const userId = req.user?.sub || req.user?.id; + if (!userId || req.user?.role !== UserRole.SPECIALIST) { + throw new ForbiddenException( + 'Apenas o especialista pode confirmar o agendamento', + ); + } + const result = await this.processesService.confirmAppointment( processId, userId, diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts index c3b263f..793cbf1 100644 --- a/backend/src/features/processes/processes.service.spec.ts +++ b/backend/src/features/processes/processes.service.spec.ts @@ -5,6 +5,7 @@ import { NotFoundException, } from '@nestjs/common'; import { + AppointmentSchedulingMethod, Prisma, ProcessStatus, ProductCurrency, @@ -1043,6 +1044,10 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { status: StatusAgendamento.PENDING, appointment_datetime: null, scheduling_method: 'EMAIL', + confirmed_at: null, + confirmed_by_id: null, + specialist_rescheduled_at: null, + specialist_rescheduled_from: null, ...appointmentOverrides, }; const process = { @@ -1050,6 +1055,7 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { specialist_id: specialistId, client_id: clientId, status: ProcessStatus.SCHEDULING, + appointment_id: appointment.id, notes: null, updated_at: new Date('2026-01-01T00:00:00.000Z'), appointment, @@ -1069,9 +1075,11 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { boat: null, aircraft: null, }; - const appointmentUpdate = jest.fn().mockResolvedValue({ - ...appointment, - status: StatusAgendamento.SCHEDULED, + let stored = structuredClone(process); + let working = stored; + const appointmentUpdate = jest.fn().mockImplementation(({ data }) => { + Object.assign(working.appointment, data); + return Promise.resolve(structuredClone(working.appointment)); }); const tx = { $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), @@ -1081,13 +1089,28 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { update: appointmentUpdate, }, process: { - findUnique: jest.fn().mockResolvedValue(process), - updateMany: jest.fn().mockResolvedValue({ count: processClaimCount }), + findUnique: jest + .fn() + .mockImplementation(() => Promise.resolve(structuredClone(working))), + updateMany: jest.fn().mockImplementation(({ data }) => { + if (processClaimCount === 1) Object.assign(working, data); + return Promise.resolve({ count: processClaimCount }); + }), }, + processStatusHistory: { create: jest.fn() }, }; const prisma = { - process: { findUnique: jest.fn().mockResolvedValue(process) }, - $transaction: jest.fn(async (callback: any) => callback(tx)), + process: { + findUnique: jest + .fn() + .mockImplementation(() => Promise.resolve(structuredClone(stored))), + }, + $transaction: jest.fn(async (callback: any) => { + working = structuredClone(stored); + const result = await callback(tx); + stored = working; + return result; + }), } as any; const notifications = { sendAppointmentConfirmedEmail: jest.fn().mockResolvedValue(undefined), @@ -1096,6 +1119,10 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { service: new ProcessesService(prisma, notifications), tx, appointmentUpdate, + prisma, + notifications, + stored: () => structuredClone(stored), + mutate: (change: (value: typeof process) => void) => change(stored), }; } @@ -1108,15 +1135,25 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { expect(appointmentUpdate).not.toHaveBeenCalled(); }); - it('requires an explicit datetime for EMAIL even when legacy data has one', async () => { - const { service, appointmentUpdate } = makeService({ + it('confirms the stored EMAIL proposal without requiring a second datetime', async () => { + const { service, stored } = makeService({ appointment_datetime: new Date(futureIso), }); await expect( - (service.confirmAppointment as any)('process-1', specialistId, undefined), - ).rejects.toThrow(BadRequestException); - expect(appointmentUpdate).not.toHaveBeenCalled(); + service.confirmAppointment('process-1', specialistId), + ).resolves.toMatchObject({ + status: ProcessStatus.SCHEDULING, + appointment_status: StatusAgendamento.SCHEDULED, + appointment_datetime: new Date(futureIso), + }); + expect(stored().status).toBe(ProcessStatus.SCHEDULING); + expect(stored().appointment).toMatchObject({ + confirmed_by_id: specialistId, + confirmed_at: expect.anything(), + specialist_rescheduled_at: null, + specialist_rescheduled_from: null, + }); }); it('stores the initial datetime without consuming the definitive change', async () => { @@ -1146,12 +1183,19 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { id: 'process-1', status: ProcessStatus.SCHEDULING, updated_at: new Date('2026-01-01T00:00:00.000Z'), + specialist_id: specialistId, + client_id: clientId, + appointment_id: 'appointment-1', + notes: null, }, }), ); const updateData = appointmentUpdate.mock.calls[0][0].data; expect(updateData).not.toHaveProperty('specialist_rescheduled_at'); expect(updateData).not.toHaveProperty('specialist_rescheduled_from'); + expect(tx.process.updateMany.mock.invocationCallOrder[0]).toBeLessThan( + appointmentUpdate.mock.invocationCallOrder[0], + ); }); it('rejects a past datetime before writing', async () => { @@ -1168,11 +1212,290 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { }); it('aborts when the process changes during confirmation', async () => { - const { service } = makeService({}, 0); + const { service, stored } = makeService({}, 0); + const before = stored(); await expect( (service.confirmAppointment as any)('process-1', specialistId, futureIso), ).rejects.toThrow(ConflictException); + expect(stored()).toEqual(before); + }); + + it('appends the original proposal and changed confirmed instant without reschedule audit', async () => { + const proposed = new Date('2099-01-01T10:00:00.000Z'); + const { service, stored, mutate, tx } = makeService({ + appointment_datetime: proposed, + }); + mutate((process) => { + process.notes = 'Nota anterior' as any; + }); + await service.confirmAppointment('process-1', specialistId, futureIso); + expect(stored().notes).toContain('Nota anterior'); + expect(stored().notes).toContain(proposed.toISOString()); + expect(stored().notes).toContain(futureIso); + expect(stored().appointment).toMatchObject({ + appointment_datetime: new Date(futureIso), + specialist_rescheduled_at: null, + specialist_rescheduled_from: null, + }); + expect(tx.processStatusHistory.create).not.toHaveBeenCalled(); + }); + + it('returns the same confirmation on double submission without new notes or emails', async () => { + const { service, stored, appointmentUpdate, notifications, tx } = + makeService(); + const first = await service.confirmAppointment( + 'process-1', + specialistId, + futureIso, + ); + await new Promise((resolve) => setImmediate(resolve)); + const afterFirst = stored(); + const second = await service.confirmAppointment( + 'process-1', + specialistId, + futureIso, + ); + await new Promise((resolve) => setImmediate(resolve)); + expect(second).toEqual(first); + expect(stored()).toEqual(afterFirst); + expect(appointmentUpdate).toHaveBeenCalledTimes(1); + expect(tx.process.updateMany).toHaveBeenCalledTimes(1); + expect(notifications.sendAppointmentConfirmedEmail).toHaveBeenCalledTimes( + 1, + ); + }); + + it('accepts the identical retry after the confirmed instant has passed', async () => { + const { service, stored, appointmentUpdate } = makeService(); + const first = await service.confirmAppointment( + 'process-1', + specialistId, + futureIso, + ); + await new Promise((resolve) => setImmediate(resolve)); + const before = stored(); + jest.useFakeTimers({ now: new Date('2100-01-01T00:00:00Z') }); + try { + await expect( + service.confirmAppointment('process-1', specialistId, futureIso), + ).resolves.toEqual(first); + expect(stored()).toEqual(before); + expect(appointmentUpdate).toHaveBeenCalledTimes(1); + } finally { + jest.useRealTimers(); + } + }); + + it('uses a single confirmation timestamp in the appointment and appended note', async () => { + const { service, stored } = makeService(); + await service.confirmAppointment('process-1', specialistId, futureIso); + expect(stored().notes).toContain( + (stored().appointment.confirmed_at as unknown as Date).toISOString(), + ); + }); + + it('notifies the participant snapshot reread under the schedule lock', async () => { + const { service, tx, stored, mutate, notifications } = makeService(); + tx.$queryRaw.mockImplementation(async () => { + mutate((process) => { + process.client.email = 'current-client@example.com'; + }); + tx.process.findUnique.mockImplementation(async () => stored()); + return [{ locked: null }]; + }); + await service.confirmAppointment('process-1', specialistId, futureIso); + await new Promise((resolve) => setImmediate(resolve)); + expect(notifications.sendAppointmentConfirmedEmail).toHaveBeenCalledWith( + expect.objectContaining({ clientEmail: 'current-client@example.com' }), + ); + }); + + it('rolls back a claimed process when updating the appointment fails', async () => { + const { service, tx, stored, notifications } = makeService(); + const before = stored(); + tx.appointment.update.mockRejectedValue(new Error('storage failure')); + await expect( + service.confirmAppointment('process-1', specialistId, futureIso), + ).rejects.toThrow('storage failure'); + expect(stored()).toEqual(before); + await new Promise((resolve) => setImmediate(resolve)); + expect(notifications.sendAppointmentConfirmedEmail).not.toHaveBeenCalled(); + }); + + it('never treats a different datetime as an idempotent confirmation', async () => { + const { service, stored } = makeService(); + await service.confirmAppointment('process-1', specialistId, futureIso); + const before = stored(); + await expect( + service.confirmAppointment( + 'process-1', + specialistId, + '2099-01-02T13:00:00Z', + ), + ).rejects.toThrow(BadRequestException); + expect(stored()).toEqual(before); + }); + + it.each([undefined, '2099-01-01T10:00:00-03:00'])( + 'accepts an identical retry with omitted/equivalent-offset datetime %s', + async (datetime) => { + const { service, stored, appointmentUpdate } = makeService(); + const first = await service.confirmAppointment( + 'process-1', + specialistId, + futureIso, + ); + const before = stored(); + await expect( + service.confirmAppointment('process-1', specialistId, datetime), + ).resolves.toEqual(first); + expect(stored()).toEqual(before); + expect(appointmentUpdate).toHaveBeenCalledTimes(1); + }, + ); + + it.each([ + [StatusAgendamento.COMPLETED, specialistId, new Date()], + [StatusAgendamento.CANCELLED, specialistId, new Date()], + [StatusAgendamento.SCHEDULED, null, null], + [StatusAgendamento.SCHEDULED, 'another-specialist', new Date()], + ])( + 'does not treat status %s with confirmation actor %s as an initial confirmation retry', + async (status, actor, at) => { + const { service, stored } = makeService({ + status, + confirmed_by_id: actor, + confirmed_at: at, + appointment_datetime: new Date(futureIso), + }); + const before = stored(); + await expect( + service.confirmAppointment('process-1', specialistId, futureIso), + ).rejects.toThrow(BadRequestException); + expect(stored()).toEqual(before); + }, + ); + + it.each(['owner', 'status', 'appointment-client', 'appointment-owner'])( + 'rejects %s changed before the transactional reread', + async (change) => { + const { service, tx, stored, mutate } = makeService(); + tx.$queryRaw.mockImplementation(async () => { + mutate((process) => { + if (change === 'owner') process.specialist_id = 'other-specialist'; + if (change === 'status') + process.status = ProcessStatus.REJECTED as any; + if (change === 'appointment-client') + process.appointment.client_id = 'other-client'; + if (change === 'appointment-owner') + process.appointment.specialist_id = 'other-specialist'; + }); + tx.process.findUnique.mockImplementation(async () => stored()); + return [{ locked: null }]; + }); + await expect( + service.confirmAppointment('process-1', specialistId, futureIso), + ).rejects.toThrow( + change === 'owner' ? ForbiddenException : BadRequestException, + ); + expect(tx.process.updateMany).not.toHaveBeenCalled(); + expect(tx.appointment.update).not.toHaveBeenCalled(); + }, + ); + + it('rejects an instant equal to now after rereading without writes', async () => { + const { service, tx } = makeService(); + jest.useFakeTimers({ now: new Date(futureIso) }); + try { + await expect( + service.confirmAppointment('process-1', specialistId, futureIso), + ).rejects.toThrow(BadRequestException); + expect(tx.process.updateMany).not.toHaveBeenCalled(); + expect(tx.appointment.update).not.toHaveBeenCalled(); + } finally { + jest.useRealTimers(); + } + }); + + it.each([ + 'not-a-date', + '2020-01-01T13:00:00Z', + '2099-02-30T13:00:00Z', + '2099-01-01', + '2099-01-01T13:00:00', + ])( + 'rejects invalid or ambiguous instant %s before writes', + async (datetime) => { + const { service, stored, appointmentUpdate } = makeService(); + const before = stored(); + await expect( + service.confirmAppointment('process-1', specialistId, datetime), + ).rejects.toThrow(BadRequestException); + expect(stored()).toEqual(before); + expect(appointmentUpdate).not.toHaveBeenCalled(); + }, + ); + + it.each([clientId, 'other-specialist', 'admin-user'])( + 'rejects confirmation by unassigned actor %s before locking', + async (actorId) => { + const { service, tx } = makeService(); + await expect( + service.confirmAppointment('process-1', actorId, futureIso), + ).rejects.toThrow(ForbiddenException); + expect(tx.$queryRaw).not.toHaveBeenCalled(); + }, + ); + + it('rejects an appointment whose client is inconsistent with its process', async () => { + const { service, stored } = makeService({ client_id: 'other-client' }); + const before = stored(); + await expect( + service.confirmAppointment('process-1', specialistId, futureIso), + ).rejects.toThrow(BadRequestException); + expect(stored()).toEqual(before); + }); + + it('uses the appointment reread after the lock for the stored proposal', async () => { + const { service, tx, stored, mutate } = makeService({ + appointment_datetime: new Date(futureIso), + }); + tx.$queryRaw.mockImplementation(async () => { + mutate((process) => { + process.appointment.appointment_datetime = new Date( + '2020-01-01T10:00:00Z', + ) as any; + }); + tx.process.findUnique.mockImplementation(async () => stored()); + return [{ locked: null }]; + }); + await expect( + service.confirmAppointment('process-1', specialistId), + ).rejects.toThrow(BadRequestException); + expect(tx.appointment.update).not.toHaveBeenCalled(); + }); + + it('rolls back all state and returns no competing identities on a schedule conflict', async () => { + const { service, stored, tx, notifications } = makeService({ + appointment_datetime: new Date(futureIso), + }); + tx.appointment.findFirst.mockResolvedValue({ + id: 'competing-appointment', + client_id: 'competing-client', + process: { id: 'competing-process' }, + }); + const before = stored(); + const error = await service + .confirmAppointment('process-1', specialistId, futureIso) + .catch((error) => error); + expect(error).toBeInstanceOf(ConflictException); + expect(JSON.stringify(error.getResponse())).not.toMatch(/competing-/); + expect(stored()).toEqual(before); + expect(tx.appointment.update).not.toHaveBeenCalled(); + expect(tx.process.updateMany).not.toHaveBeenCalled(); + await new Promise((resolve) => setImmediate(resolve)); + expect(notifications.sendAppointmentConfirmedEmail).not.toHaveBeenCalled(); }); }); @@ -1368,3 +1691,252 @@ describe('ProcessesService — telefone da contraparte após confirmação', () expect(result.processes[0].client.phone).toBeNull(); }); }); + +describe('ProcessesService — matriz de contatos do cliente', () => { + const contact = { email: 'cliente@example.com', phone: '11987654321' }; + const cases = [ + [ + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + true, + ], + [ + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.CALENDLY, + ProcessStatus.SCHEDULING, + false, + ], + [StatusAgendamento.PENDING, null, ProcessStatus.SCHEDULING, false], + [ + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.REJECTED, + false, + ], + [ + StatusAgendamento.SCHEDULED, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + true, + ], + [ + StatusAgendamento.COMPLETED, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.NEGOTIATION, + true, + ], + [ + StatusAgendamento.CANCELLED, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + false, + ], + ] as const; + + function makeService( + status: StatusAgendamento, + method: AppointmentSchedulingMethod | null, + processStatus: ProcessStatus, + ) { + const process = { + id: 'process-1', + status: processStatus, + client_id: clientId, + specialist_id: specialistId, + product_type: null, + client: { + id: clientId, + name: 'Cliente', + consultant_id: 'consultant-1', + ...contact, + }, + specialist: { + id: specialistId, + name: 'Especialista', + phone: '11911112222', + speciality: ProductType.CAR, + }, + appointment: { + status, + scheduling_method: method, + appointment_datetime: new Date('2099-01-01T13:00:00Z'), + }, + car: null, + boat: null, + aircraft: null, + notes: null, + created_at: new Date(), + }; + const prisma = { + user: { + findUnique: jest + .fn() + .mockResolvedValue({ consultant_id: 'consultant-1' }), + }, + process: { + findUniqueOrThrow: jest.fn().mockResolvedValue(process), + findMany: jest.fn().mockResolvedValue([process]), + findFirst: jest.fn().mockResolvedValue({ id: process.id }), + count: jest.fn().mockResolvedValue(1), + groupBy: jest.fn().mockResolvedValue([]), + }, + $transaction: jest.fn((operations) => Promise.all(operations)), + } as any; + return new ProcessesService(prisma, {} as any); + } + + it.each(cases)( + 'assigned specialist list and detail expose contacts for %s/%s/%s: %s', + async (status, method, processStatus, visible) => { + const service = makeService(status, method, processStatus); + const detail = await service.getById( + 'process-1', + specialistId, + UserRole.SPECIALIST, + ); + const list = await service.getBySpecialistIdWithFilters( + specialistId, + {}, + { id: specialistId, role: UserRole.SPECIALIST }, + ); + const generic = await service.getAll({ + page: 1, + perPage: 20, + requester: { id: specialistId, role: UserRole.SPECIALIST }, + }); + for (const result of [detail, list.processes[0], generic.processes[0]]) { + if (visible) { + expect(result.client).toMatchObject(contact); + } else { + expect(result.client).not.toHaveProperty('email'); + expect(result.client.phone).toBeNull(); + } + } + }, + ); + + it.each([ + [UserRole.ADMIN, 'admin-1'], + [UserRole.CONSULTANT, 'consultant-1'], + [UserRole.OFFICE, 'office-1'], + [UserRole.SPECIALIST, 'other-specialist'], + [UserRole.CUSTOMER, clientId], + ] as const)( + 'specialist list gives %s no client contacts even after confirmation', + async (role, id) => { + for (const status of [ + StatusAgendamento.PENDING, + StatusAgendamento.SCHEDULED, + StatusAgendamento.COMPLETED, + ]) { + const result = await makeService( + status, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getBySpecialistIdWithFilters(specialistId, {}, { role, id }); + expect(result.processes[0].client).not.toHaveProperty('email'); + expect(result.processes[0].client.phone).toBeNull(); + } + }, + ); + + it.each([ + [UserRole.ADMIN, 'admin-1'], + [UserRole.CONSULTANT, 'consultant-1'], + [UserRole.CUSTOMER, clientId], + [undefined, undefined], + ] as const)('detail gives %s no client contacts', async (role, id) => { + const result = await makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getById('process-1', id, role); + expect(result.client).not.toHaveProperty('email'); + expect(result.client.phone).toBeNull(); + expect(result.specialist.phone).toBeNull(); + }); + + it.each([ + [UserRole.SPECIALIST, 'other-specialist'], + [UserRole.OFFICE, 'office-1'], + ] as const)('unassigned %s cannot read the detail', async (role, id) => { + await expect( + makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getById('process-1', id, role), + ).rejects.toThrow(ForbiddenException); + }); + + it('an actor with the specialist ID but another role cannot read client contacts', async () => { + const result = await makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getById('process-1', specialistId, UserRole.CONSULTANT); + expect(result.client).not.toHaveProperty('email'); + expect(result.client.phone).toBeNull(); + }); + + it('client list and unscoped legacy specialist projection contain no client contacts', async () => { + const service = makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ); + const client = await service.getByClientId( + clientId, + { page: 1, perPage: 20 }, + clientId, + UserRole.CUSTOMER, + ); + const legacy = await service.getBySpecialistId(specialistId, { + page: 1, + perPage: 20, + }); + for (const result of [client.processes[0], legacy.processes[0]]) { + expect(result.client).not.toHaveProperty('email'); + expect(result.client.phone ?? null).toBeNull(); + } + }); + + it.each([ + UserRole.ADMIN, + UserRole.CONSULTANT, + UserRole.OFFICE, + UserRole.CUSTOMER, + ])('generic list gives %s no early client contacts', async (role) => { + const result = await makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getAll({ + page: 1, + perPage: 20, + requester: { id: 'actor', role, companyId: 'company-1' }, + }); + expect(result.processes[0].client).not.toHaveProperty('email'); + expect(result.processes[0].client.phone).toBeNull(); + }); + + it.each([UserRole.ADMIN, UserRole.CONSULTANT, UserRole.SPECIALIST])( + 'client list gives unassigned %s no client contacts', + async (role) => { + const service = makeService( + StatusAgendamento.SCHEDULED, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ); + const result = await service.getByClientId( + clientId, + { page: 1, perPage: 20 }, + role === UserRole.CONSULTANT ? 'consultant-1' : 'unassigned-actor', + role, + ); + expect(result.processes[0].client).not.toHaveProperty('email'); + expect(result.processes[0].client.phone).toBeNull(); + }, + ); +}); diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts index 155811d..294f14b 100644 --- a/backend/src/features/processes/processes.service.ts +++ b/backend/src/features/processes/processes.service.ts @@ -35,6 +35,8 @@ import { import { validateSpecialistProductAssociation } from '../products/product-association-validator'; import { lockAndAssertNoActiveProcess } from './process-dedup-lock'; import { parseDate, isFutureDate } from 'src/shared/utils/date.utils'; +import { isISO8601 } from 'class-validator'; +import { PENDING_APPOINTMENT_DATETIME_PATTERN } from '../appointments/dto'; import { acquireSpecialistScheduleLock, assertSpecialistScheduleAvailable, @@ -141,6 +143,26 @@ export class ProcessesService { ); } + private projectClientContacts( + process: any, + requester?: { id?: string; role?: string }, + ): ProcessResponse['client'] { + const visible = + requester?.role === UserRole.SPECIALIST && + requester.id === process.specialist_id && + (this.isAppointmentContactVisible(process.appointment?.status) || + (process.status === ProcessStatus.SCHEDULING && + process.appointment?.status === StatusAgendamento.PENDING && + process.appointment?.scheduling_method === + AppointmentSchedulingMethod.EMAIL)); + return { + id: process.client_id, + name: process.client?.name ?? '', + ...(visible ? { email: process.client?.email ?? '' } : {}), + phone: visible ? (process.client?.phone ?? null) : null, + }; + } + /** * Helper: Retorna descrição formatada do produto para emails * @@ -737,11 +759,7 @@ export class ProcessesService { process.appointment?.specialist_rescheduled_from ?? null, product_type: process.product_type, product_id: this.getProductId(process), - client: { - id: process.client_id, - email: process.client?.email, - name: process.client?.name, - }, + client: this.projectClientContacts(process, requester), specialist: { especialidade: process.specialist.speciality, id: process.specialist.id, @@ -815,9 +833,8 @@ export class ProcessesService { process.appointment?.status, ); const isClient = userId === process.client_id; - const isSpecialist = userId === process.specialist_id; - const canSeeClientPhone = isSpecialist && contactVisible; - const canSeeSpecialistPhone = isClient && contactVisible; + const canSeeSpecialistPhone = + userRole === UserRole.CUSTOMER && isClient && contactVisible; return { id: process.id, @@ -833,12 +850,10 @@ export class ProcessesService { process.appointment?.specialist_rescheduled_from ?? null, product_type: process.product_type, product_id: this.getProductId(process), - client: { - id: process.client_id, - email: process.client?.email || '', - name: process.client?.name || '', - phone: canSeeClientPhone ? (process.client?.phone ?? null) : null, - }, + client: this.projectClientContacts(process, { + id: userId, + role: userRole, + }), specialist: { especialidade: process.specialist.speciality, id: process.specialist.id, @@ -930,11 +945,7 @@ export class ProcessesService { process.appointment?.specialist_rescheduled_from ?? null, product_type: process.product_type, product_id: this.getProductId(process), - client: { - id: process.client_id, - email: process.client?.email, - name: process.client?.name, - }, + client: this.projectClientContacts(process), specialist: { especialidade: process.specialist.speciality, id: process.specialist.id, @@ -979,8 +990,6 @@ export class ProcessesService { const skip = (pageNum - 1) * perPageNum; const sortBy = options.sortBy || 'created_at'; const order = options.order || 'desc'; - const canSeeClientPhone = - requester.role === UserRole.SPECIALIST && requester.id === specialistId; // Build where clause const where: any = { @@ -1054,16 +1063,7 @@ export class ProcessesService { process.appointment?.specialist_rescheduled_from ?? null, product_type: process.product_type, product_id: this.getProductId(process), - client: { - id: process.client_id, - email: process.client?.email, - name: process.client?.name, - phone: - canSeeClientPhone && - this.isAppointmentContactVisible(process.appointment?.status) - ? (process.client?.phone ?? null) - : null, - }, + client: this.projectClientContacts(process, requester), specialist: { especialidade: process.specialist.speciality, id: process.specialist.id, @@ -1789,11 +1789,10 @@ export class ProcessesService { process.appointment?.specialist_rescheduled_from ?? null, product_type: process.product_type, product_id: this.getProductId(process), - client: { - id: process.client_id, - email: process.client?.email, - name: process.client?.name, - }, + client: this.projectClientContacts(process, { + id: userId, + role: userRole, + }), specialist: { especialidade: process.specialist.speciality, id: process.specialist.id, @@ -1955,21 +1954,10 @@ export class ProcessesService { `[confirmAppointment] Confirmando agendamento do processo ${processId}`, ); - // Buscar processo com appointment, client, specialist e produtos + // A leitura inicial identifica apenas o especialista para o lock. const process = await this.prismaService.process.findUnique({ where: { id: processId }, - include: { - appointment: true, - client: { - select: { id: true, email: true, name: true, surname: true }, - }, - specialist: { - select: { id: true, email: true, name: true, surname: true }, - }, - car: true, - boat: true, - aircraft: true, - }, + select: { id: true, specialist_id: true }, }); if (!process) { @@ -1983,55 +1971,24 @@ export class ProcessesService { ); } - // Verificar se está em status SCHEDULING - if (process.status !== 'SCHEDULING') { - throw new BadRequestException( - 'Apenas processos em status SCHEDULING podem ter o agendamento confirmado', - ); - } - - // Verificar se tem appointment - if (!process.appointment) { - throw new NotFoundException( - 'Agendamento não encontrado para este processo', - ); - } - - if ( - process.appointment.status === StatusAgendamento.SCHEDULED || - process.appointment.status === StatusAgendamento.COMPLETED - ) { - throw new BadRequestException('Agendamento já foi confirmado'); - } - - if ( - process.appointment.scheduling_method === - AppointmentSchedulingMethod.EMAIL && - !appointmentDatetime - ) { - throw new BadRequestException( - 'Informe uma data e hora futura para confirmar o agendamento', - ); - } - - const requestedDate = parseDate( - appointmentDatetime ?? - process.appointment.appointment_datetime ?? - undefined, - ); - if (!requestedDate || !isFutureDate(requestedDate)) { - throw new BadRequestException( - 'Informe uma data e hora futura para confirmar o agendamento', - ); - } - // Confirmar appointment em transação (sem alterar status do processo) - const confirmedDate = await this.prismaService.$transaction(async (tx) => { + const confirmation = await this.prismaService.$transaction(async (tx) => { await acquireSpecialistScheduleLock(tx, process.specialist_id); const lockedProcess = await tx.process.findUnique({ where: { id: processId }, - include: { appointment: true }, + include: { + appointment: true, + client: { + select: { id: true, email: true, name: true, surname: true }, + }, + specialist: { + select: { id: true, email: true, name: true, surname: true }, + }, + car: true, + boat: true, + aircraft: true, + }, }); if (!lockedProcess) { throw new NotFoundException('Processo não encontrado'); @@ -2051,14 +2008,21 @@ export class ProcessesService { 'Agendamento não encontrado para este processo', ); } - if (lockedProcess.appointment.status !== StatusAgendamento.PENDING) { - throw new BadRequestException('Agendamento já foi confirmado'); + if ( + lockedProcess.appointment.specialist_id !== + lockedProcess.specialist_id || + lockedProcess.appointment.client_id !== lockedProcess.client_id || + lockedProcess.appointment.id !== lockedProcess.appointment_id + ) { + throw new BadRequestException( + 'Agendamento não corresponde aos participantes do processo', + ); } - if ( - lockedProcess.appointment.scheduling_method === - AppointmentSchedulingMethod.EMAIL && - !appointmentDatetime + appointmentDatetime !== undefined && + (typeof appointmentDatetime !== 'string' || + !PENDING_APPOINTMENT_DATETIME_PATTERN.test(appointmentDatetime) || + !isISO8601(appointmentDatetime, { strict: true })) ) { throw new BadRequestException( 'Informe uma data e hora futura para confirmar o agendamento', @@ -2070,6 +2034,26 @@ export class ProcessesService { lockedProcess.appointment.appointment_datetime ?? undefined, ); + const appointment = lockedProcess.appointment; + if ( + appointment.status === StatusAgendamento.SCHEDULED && + appointment.confirmed_by_id === userId && + appointment.confirmed_at && + lockedConfirmedDate && + appointment.appointment_datetime?.getTime() === + lockedConfirmedDate.getTime() + ) { + return { + changed: false, + confirmedDate: lockedConfirmedDate, + process: lockedProcess, + }; + } + if (appointment.status !== StatusAgendamento.PENDING) { + throw new BadRequestException( + 'Agendamento já foi confirmado ou cancelado', + ); + } if (!lockedConfirmedDate || !isFutureDate(lockedConfirmedDate)) { throw new BadRequestException( 'Informe uma data e hora futura para confirmar o agendamento', @@ -2083,28 +2067,27 @@ export class ProcessesService { lockedProcess.appointment.id, ); - // Atualizar appointment para SCHEDULED - await tx.appointment.update({ - where: { id: lockedProcess.appointment.id }, - data: { - status: StatusAgendamento.SCHEDULED, - appointment_datetime: lockedConfirmedDate, - confirmed_at: new Date(), - confirmed_by_id: userId, - }, - }); - - // Manter process em SCHEDULING e apenas registrar no histórico/notas + const confirmedAt = new Date(); + const proposal = + appointment.appointment_datetime?.toISOString() ?? + 'sem horário definido'; + const note = `Agendamento confirmado pelo especialista (${confirmedAt.toISOString()}); proposta: ${proposal}; horário confirmado: ${lockedConfirmedDate.toISOString()}`; + // Reivindicar Process antes de Appointment mantém a ordem de cancelamento. const processClaim = await tx.process.updateMany({ where: { id: processId, status: ProcessStatus.SCHEDULING, updated_at: lockedProcess.updated_at, + specialist_id: lockedProcess.specialist_id, + client_id: lockedProcess.client_id, + appointment_id: appointment.id, + notes: lockedProcess.notes, }, data: { notes: lockedProcess.notes - ? `${lockedProcess.notes}\n\nAgendamento confirmado pelo especialista (${new Date().toISOString()})` - : `Agendamento confirmado pelo especialista (${new Date().toISOString()})`, + ? `${lockedProcess.notes}\n\n${note}` + : note, + updated_at: confirmedAt, }, }); if (processClaim.count !== 1) { @@ -2113,7 +2096,21 @@ export class ProcessesService { ); } - return lockedConfirmedDate; + await tx.appointment.update({ + where: { id: appointment.id }, + data: { + status: StatusAgendamento.SCHEDULED, + appointment_datetime: lockedConfirmedDate, + confirmed_at: confirmedAt, + confirmed_by_id: userId, + }, + }); + + return { + changed: true, + confirmedDate: lockedConfirmedDate, + process: lockedProcess, + }; }); this.logger.log( @@ -2121,32 +2118,34 @@ export class ProcessesService { ); // Fire-and-forget email notification (async, non-blocking) - setImmediate(() => { - this.notificationService - .sendAppointmentConfirmedEmail({ - clientEmail: process.client.email, - clientName: - `${process.client.name} ${process.client.surname || ''}`.trim(), - specialistName: - `${process.specialist.name} ${process.specialist.surname || ''}`.trim(), - appointmentDate: confirmedDate, - productDetails: this.getProductDetails(process), - processId, - }) - .catch((err) => { - this.logger.error('Notification failed (non-critical)', { - method: 'confirmAppointment', + if (confirmation.changed) + setImmediate(() => { + const process = confirmation.process; + this.notificationService + .sendAppointmentConfirmedEmail({ + clientEmail: process.client.email, + clientName: + `${process.client.name} ${process.client.surname || ''}`.trim(), + specialistName: + `${process.specialist.name} ${process.specialist.surname || ''}`.trim(), + appointmentDate: confirmation.confirmedDate, + productDetails: this.getProductDetails(process), processId, - error: err.message, + }) + .catch((err) => { + this.logger.error('Notification failed (non-critical)', { + method: 'confirmAppointment', + processId, + error: err.message, + }); }); - }); - }); + }); return { processId, status: 'SCHEDULING', appointment_status: StatusAgendamento.SCHEDULED, - appointment_datetime: confirmedDate, + appointment_datetime: confirmation.confirmedDate, }; } From a3070dfb4e24fcd96c19e57708a79bfd92b290ac Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 09:06:54 -0300 Subject: [PATCH 10/60] feat: add safe email scheduling frontend contracts --- .../src/hooks/useCheckAppointment.test.tsx | 182 ++++++++++++++++++ frontend/src/hooks/useCheckAppointment.ts | 114 +++-------- frontend/src/lib/appointment-datetime.test.ts | 29 ++- frontend/src/lib/appointment-datetime.ts | 29 +++ frontend/src/lib/email-scheduling.test.ts | 75 ++++++++ frontend/src/lib/email-scheduling.ts | 48 +++++ frontend/src/lib/whatsapp.test.ts | 20 ++ frontend/src/lib/whatsapp.ts | 7 + .../src/services/appointments.service.test.ts | 93 +++++++++ frontend/src/services/appointments.service.ts | 114 +++++++---- .../src/services/specialists.service.test.ts | 7 + 11 files changed, 598 insertions(+), 120 deletions(-) create mode 100644 frontend/src/hooks/useCheckAppointment.test.tsx create mode 100644 frontend/src/lib/email-scheduling.test.ts create mode 100644 frontend/src/lib/email-scheduling.ts create mode 100644 frontend/src/lib/whatsapp.test.ts create mode 100644 frontend/src/lib/whatsapp.ts create mode 100644 frontend/src/services/appointments.service.test.ts diff --git a/frontend/src/hooks/useCheckAppointment.test.tsx b/frontend/src/hooks/useCheckAppointment.test.tsx new file mode 100644 index 0000000..1363abb --- /dev/null +++ b/frontend/src/hooks/useCheckAppointment.test.tsx @@ -0,0 +1,182 @@ +// @vitest-environment jsdom +import { act, cleanup, renderHook } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { checkExistingAppointment } from "../services/appointments.service"; +import type { ExistingAppointmentCheck } from "../services/appointments.service"; +import { useCheckAppointment } from "./useCheckAppointment"; +import { StrictMode } from "react"; +import { useAuth } from "../store/authStateManager"; + +const customer = { id: "customer-1", name: "João", surname: "Silva", email: "joao@example.com", cpf: "", rg: "", role: "CUSTOMER" as const }; + +vi.mock("../services/appointments.service", () => ({ checkExistingAppointment: vi.fn() })); + +const found: ExistingAppointmentCheck = { + exists: true, appointment_id: "appointment-1", process_id: "process-1", appointment_status: "PENDING", + scheduling_method: "EMAIL", appointment_datetime: "2099-10-20T17:30:00.000Z", +}; + +function deferred() { + let resolve!: (value: ExistingAppointmentCheck) => void; + let reject!: (reason: unknown) => void; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + // Old implementations may never attach a handler; keep the RED focused on state assertions. + void promise.catch(() => {}); + return { promise, resolve, reject }; +} + +async function advance(ms = 500) { + await act(async () => { await vi.advanceTimersByTimeAsync(ms); }); +} + +beforeEach(() => { useAuth.setState({ user: customer }); vi.useFakeTimers(); vi.mocked(checkExistingAppointment).mockResolvedValue({ exists: false }); }); +afterEach(() => { cleanup(); useAuth.setState({ user: null }); vi.useRealTimers(); vi.resetAllMocks(); }); + +describe("owned appointment check hook", () => { + it("debounces for 500ms and calls the own-only three-argument service", async () => { + vi.mocked(checkExistingAppointment).mockResolvedValue(found); + const { result } = renderHook(() => useCheckAppointment("specialist-1", "CAR", "car-1")); + expect(result.current).toEqual({ existingAppointment: null, isLoading: true, error: null }); + await advance(499); + expect(checkExistingAppointment).not.toHaveBeenCalled(); + await advance(1); + expect(checkExistingAppointment).toHaveBeenCalledWith("specialist-1", "CAR", "car-1"); + expect(result.current).toEqual({ existingAppointment: found, isLoading: false, error: null }); + }); + + it("exposes exists:false as a discriminated successful result", async () => { + const { result } = renderHook(() => useCheckAppointment("specialist-1", "CAR", "car-1")); + await advance(); + expect(result.current.existingAppointment).toEqual({ exists: false }); + expect(result.current.error).toBeNull(); + }); + + it.each([ + [undefined, "CAR", "car-1"], ["specialist-1", undefined, "car-1"], ["specialist-1", "CAR", undefined], + ] as const)("does not check missing parameters %j", async (specialistId, productType, productId) => { + const { result } = renderHook(() => useCheckAppointment(specialistId, productType, productId)); + await advance(); + expect(checkExistingAppointment).not.toHaveBeenCalled(); + expect(result.current).toEqual({ existingAppointment: null, isLoading: false, error: null }); + }); + + it("resets the debounce when the product changes", async () => { + const { rerender } = renderHook(({ productId }) => useCheckAppointment("specialist-1", "CAR", productId), { initialProps: { productId: "car-1" } }); + await advance(400); + rerender({ productId: "car-2" }); + await advance(100); + expect(checkExistingAppointment).not.toHaveBeenCalled(); + await advance(400); + expect(checkExistingAppointment).toHaveBeenCalledExactlyOnceWith("specialist-1", "CAR", "car-2"); + }); + + it("exposes the service error and clears it immediately for a new request", async () => { + vi.mocked(checkExistingAppointment).mockRejectedValueOnce(new Error("Sessão expirada")); + const { result, rerender } = renderHook(({ productId }) => useCheckAppointment("specialist-1", "CAR", productId), { initialProps: { productId: "car-1" } }); + await advance(); + expect(result.current).toEqual({ existingAppointment: null, isLoading: false, error: "Sessão expirada" }); + rerender({ productId: "car-2" }); + expect(result.current).toEqual({ existingAppointment: null, isLoading: true, error: null }); + await advance(); + expect(result.current.existingAppointment).toEqual({ exists: false }); + }); + + it("uses a readable fallback for a non-Error rejection", async () => { + vi.mocked(checkExistingAppointment).mockRejectedValueOnce({ status: 401 }); + const { result } = renderHook(() => useCheckAppointment("specialist-1", "CAR", "car-1")); + await advance(); + expect(result.current.error).toBe("Erro ao verificar agendamentos"); + }); + + it.each(["resolve", "reject"] as const)("ignores an earlier %s while the new request is loading", async (outcome) => { + const earlier = deferred(); + const latest = deferred(); + vi.mocked(checkExistingAppointment).mockReturnValueOnce(earlier.promise).mockReturnValueOnce(latest.promise); + const { result, rerender } = renderHook(({ productId }) => useCheckAppointment("specialist-1", "CAR", productId), { initialProps: { productId: "car-1" } }); + await advance(); + rerender({ productId: "car-2" }); + await advance(); + await act(async () => { if (outcome === "resolve") earlier.resolve(found); else earlier.reject(new Error("obsolete")); }); + expect(result.current).toEqual({ existingAppointment: null, isLoading: true, error: null }); + await act(async () => { latest.resolve({ exists: false }); }); + expect(result.current).toEqual({ existingAppointment: { exists: false }, isLoading: false, error: null }); + }); + + it("does not let an earlier success replace the latest result", async () => { + const earlier = deferred(); + vi.mocked(checkExistingAppointment).mockReturnValueOnce(earlier.promise).mockResolvedValueOnce({ exists: false }); + const { result, rerender } = renderHook(({ productId }) => useCheckAppointment("specialist-1", "CAR", productId), { initialProps: { productId: "car-1" } }); + await advance(); + rerender({ productId: "car-2" }); + await advance(); + await act(async () => { earlier.resolve(found); }); + expect(result.current).toEqual({ existingAppointment: { exists: false }, isLoading: false, error: null }); + }); + + it("invalidates an in-flight response when parameters become missing", async () => { + const pending = deferred(); + vi.mocked(checkExistingAppointment).mockReturnValueOnce(pending.promise); + const { result, rerender } = renderHook(({ productId }) => useCheckAppointment("specialist-1", "CAR", productId), { initialProps: { productId: "car-1" as string | undefined } }); + await advance(); + rerender({ productId: undefined }); + await act(async () => { pending.resolve(found); }); + expect(result.current).toEqual({ existingAppointment: null, isLoading: false, error: null }); + }); + + it("cleans up a pending debounce on unmount", async () => { + const { unmount } = renderHook(() => useCheckAppointment("specialist-1", "CAR", "car-1")); + unmount(); + await advance(); + expect(checkExistingAppointment).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); + }); + + it("ignores completion after unmount", async () => { + const pending = deferred(); + vi.mocked(checkExistingAppointment).mockReturnValueOnce(pending.promise); + const { result, unmount } = renderHook(() => useCheckAppointment("specialist-1", "CAR", "car-1")); + await advance(); + const state = result.current; + unmount(); + await act(async () => { pending.resolve(found); }); + expect(result.current).toBe(state); + }); + + it("survives StrictMode cleanup with exactly one current check", async () => { + const { result } = renderHook(() => useCheckAppointment("specialist-1", "CAR", "car-1"), { wrapper: StrictMode }); + await advance(); + expect(checkExistingAppointment).toHaveBeenCalledExactlyOnceWith("specialist-1", "CAR", "car-1"); + expect(result.current).toEqual({ existingAppointment: { exists: false }, isLoading: false, error: null }); + }); + + it("invalidates a former customer's in-flight response on account switch", async () => { + const earlier = deferred(); + vi.mocked(checkExistingAppointment).mockReturnValueOnce(earlier.promise).mockResolvedValueOnce({ exists: false }); + const { result } = renderHook(() => useCheckAppointment("specialist-1", "CAR", "car-1")); + await advance(); + act(() => { useAuth.setState({ user: { ...customer, id: "customer-2" } }); }); + expect(result.current).toEqual({ existingAppointment: null, isLoading: true, error: null }); + await act(async () => { earlier.resolve(found); }); + expect(result.current.existingAppointment).toBeNull(); + await advance(); + expect(checkExistingAppointment).toHaveBeenCalledTimes(2); + expect(result.current.existingAppointment).toEqual({ exists: false }); + }); + + it.each([null, { ...customer, role: "SPECIALIST" as const }])("does not check for a missing or non-customer identity", async (user) => { + useAuth.setState({ user }); + const { result } = renderHook(() => useCheckAppointment("specialist-1", "CAR", "car-1")); + await advance(); + expect(checkExistingAppointment).not.toHaveBeenCalled(); + expect(result.current).toEqual({ existingAppointment: null, isLoading: false, error: null }); + }); + + it("clears the owned snapshot when the authenticated role changes", async () => { + vi.mocked(checkExistingAppointment).mockResolvedValueOnce(found); + const { result } = renderHook(() => useCheckAppointment("specialist-1", "CAR", "car-1")); + await advance(); + expect(result.current.existingAppointment).toEqual(found); + act(() => { useAuth.setState({ user: { ...customer, role: "SPECIALIST" } }); }); + expect(result.current).toEqual({ existingAppointment: null, isLoading: false, error: null }); + }); +}); diff --git a/frontend/src/hooks/useCheckAppointment.ts b/frontend/src/hooks/useCheckAppointment.ts index bcfadd9..bdcc181 100644 --- a/frontend/src/hooks/useCheckAppointment.ts +++ b/frontend/src/hooks/useCheckAppointment.ts @@ -1,108 +1,54 @@ -import { useEffect, useState, useRef } from "react"; +import { useEffect, useRef, useState } from "react"; import { checkExistingAppointment } from "../services/appointments.service"; -import type { Appointment } from "../services/appointments.service"; +import type { ExistingAppointmentCheck } from "../services/appointments.service"; +import { useAuth } from "../store/authStateManager"; interface UseCheckAppointmentResult { - existingAppointment: Appointment | null; + existingAppointment: ExistingAppointmentCheck | null; isLoading: boolean; error: string | null; } -/** - * Hook para verificar se já existe agendamento entre cliente e especialista para um produto - * Usado para impedir agendamentos duplicados - * - * **Evita race conditions com debounce de 500ms** - * - * @param clientId - ID do cliente autenticado - * @param specialistId - ID do especialista - * @param productType - Tipo de produto (CAR, BOAT, AIRCRAFT) - * @param productId - ID do produto - * @returns { existingAppointment, isLoading, error } - * - * Exemplo: - * const { existingAppointment, isLoading } = useCheckAppointment( - * userId, - * specialist.id, - * "CAR", - * product.id - * ); - * - * if (isLoading) return
Verificando...
; - * if (existingAppointment) return
Você já tem agendamento marcado
; - */ +/** Debounced own-request check; null means unchecked/failed, exists:false means a successful absence. */ export function useCheckAppointment( - clientId: string | undefined, specialistId: string | undefined, productType: "CAR" | "BOAT" | "AIRCRAFT" | undefined, - productId: string | undefined + productId: string | undefined, ): UseCheckAppointmentResult { - const [existingAppointment, setExistingAppointment] = - useState(null); + const userId = useAuth((state) => state.user?.id); + const role = useAuth((state) => state.user?.role); + const [existingAppointment, setExistingAppointment] = useState(null); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); - const debounceTimerRef = useRef | null>(null); + const requestToken = useRef(0); useEffect(() => { - // Limpa timer anterior se existir - if (debounceTimerRef.current) { - clearTimeout(debounceTimerRef.current); - } - - // Não faz nada se faltam parâmetros - if (!clientId || !specialistId || !productType || !productId) { - setExistingAppointment(null); + const token = ++requestToken.current; + setExistingAppointment(null); + setError(null); + if (!userId || role !== "CUSTOMER" || !specialistId || !productType || !productId) { setIsLoading(false); - return; + return () => { requestToken.current = token + 1; }; } - - // Debounce de 500ms para evitar múltiplas requisições - debounceTimerRef.current = setTimeout(() => { - const checkAppointment = async () => { - setIsLoading(true); - setError(null); - - try { - console.log( - `[useCheckAppointment] Verificando: cliente=${clientId}, especialista=${specialistId}, tipo=${productType}, produto=${productId}` - ); - - const appointment = await checkExistingAppointment( - clientId, - specialistId, - productType, - productId - ); - - console.log( - `[useCheckAppointment] Resultado:`, - appointment ? `Agendamento encontrado (${appointment.id})` : "Nenhum agendamento" - ); - - setExistingAppointment(appointment); - } catch (err) { - console.error("Erro ao verificar agendamento:", err); - setError("Erro ao verificar agendamentos"); + setIsLoading(true); + const timer = setTimeout(async () => { + try { + const result = await checkExistingAppointment(specialistId, productType, productId); + if (token === requestToken.current) setExistingAppointment(result); + } catch (error) { + if (token === requestToken.current) { setExistingAppointment(null); - } finally { - setIsLoading(false); + setError(error instanceof Error ? error.message : "Erro ao verificar agendamentos"); } - }; - - checkAppointment(); + } finally { + if (token === requestToken.current) setIsLoading(false); + } }, 500); - - // Cleanup return () => { - if (debounceTimerRef.current) { - clearTimeout(debounceTimerRef.current); - } + requestToken.current = token + 1; + clearTimeout(timer); }; - }, [clientId, specialistId, productType, productId]); + }, [userId, role, specialistId, productType, productId]); - return { - existingAppointment, - isLoading, - error, - }; + return { existingAppointment, isLoading, error }; } diff --git a/frontend/src/lib/appointment-datetime.test.ts b/frontend/src/lib/appointment-datetime.test.ts index 99d52d9..9acc501 100644 --- a/frontend/src/lib/appointment-datetime.test.ts +++ b/frontend/src/lib/appointment-datetime.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { browserTimeZone, localDateTimeToIso } from "./appointment-datetime"; +import { browserTimeZone, isoToLocalDateTimeInput, localDateTimeToIso, parseAppointmentIso } from "./appointment-datetime"; describe("appointment datetime helpers", () => { it("converts a future local datetime to ISO", () => { @@ -23,4 +23,31 @@ describe("appointment datetime helpers", () => { it("returns a visible browser timezone label", () => { expect(browserTimeZone().trim().length).toBeGreaterThan(0); }); + + it.each([ + "2026-10-20T17:30:45.123Z", + "2026-11-01T05:30:45.123Z", + "2026-11-01T06:30:45.123Z", + ])("renders existing instant %s using local calendar fields rather than UTC", (iso) => { + const date = new Date(iso); + const pad = (value: number) => String(value).padStart(2, "0"); + expect(isoToLocalDateTimeInput(iso)).toBe( + `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`, + ); + }); + + it.each(["", "invalid"])("rejects an invalid existing ISO %j", (iso) => { + expect(() => isoToLocalDateTimeInput(iso)).toThrow("Selecione uma data e hora válidas"); + }); + + it.each([ + ["2026-10-20T14:30:45.123-03:00", "2026-10-20T17:30:45.123Z"], + ["2028-02-29T17:30Z", "2028-02-29T17:30:00.000Z"], + ])("parses valid explicit-offset instant %s", (iso, expected) => { + expect(parseAppointmentIso(iso).toISOString()).toBe(expected); + }); + + it.each(["2026-02-29T17:30Z", "2026-00-20T17:30Z", "2026-10-20T17:60Z", "2026-10-20T17:30:60Z", "2026-10-20T17:30", "2026-10-20T17:30+03:60"])("rejects impossible or offsetless ISO %s", (iso) => { + expect(() => parseAppointmentIso(iso)).toThrow("Selecione uma data e hora válidas"); + }); }); diff --git a/frontend/src/lib/appointment-datetime.ts b/frontend/src/lib/appointment-datetime.ts index ae8167d..0b6d749 100644 --- a/frontend/src/lib/appointment-datetime.ts +++ b/frontend/src/lib/appointment-datetime.ts @@ -15,3 +15,32 @@ export function localDateTimeToIso(value: string): string { export function browserTimeZone(): string { return Intl.DateTimeFormat().resolvedOptions().timeZone || "horário local"; } + +/** Parses an ISO instant with an explicit offset, rejecting normalized invalid calendar dates. */ +export function parseAppointmentIso(value: string): Date { + const match = typeof value === "string" + ? /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})$/.exec(value) + : null; + if (!match) throw new Error("Selecione uma data e hora válidas"); + + const [, yearText, monthText, dayText, hourText, minuteText, secondText] = match; + const year = Number(yearText); + const month = Number(monthText); + const day = Number(dayText); + const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + const parsed = new Date(value); + if (month < 1 || month > 12 || day < 1 || day > daysInMonth[month - 1] + || Number(hourText) > 23 || Number(minuteText) > 59 || Number(secondText ?? 0) > 59 + || Number.isNaN(parsed.getTime())) { + throw new Error("Selecione uma data e hora válidas"); + } + return parsed; +} + +/** Local wall-clock value; callers retain the original ISO when this value is unchanged. */ +export function isoToLocalDateTimeInput(iso: string): string { + const date = parseAppointmentIso(iso); + const pad = (value: number) => String(value).padStart(2, "0"); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`; +} diff --git a/frontend/src/lib/email-scheduling.test.ts b/frontend/src/lib/email-scheduling.test.ts new file mode 100644 index 0000000..2ef0478 --- /dev/null +++ b/frontend/src/lib/email-scheduling.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vitest"; +import { buildEmailSchedulingLinks } from "./email-scheduling"; + +const input = { + recipient: "ana@example.com", + specialistName: "Ana", + clientName: "João", + productLabel: "Carro A&B?#", + appointmentDatetime: "2026-10-20T17:30:00.000Z", + timeZone: "America/Sao_Paulo", +}; + +describe("email scheduling links", () => { + it("encodes each field independently for mailto and Gmail", () => { + const links = buildEmailSchedulingLinks(input); + const mailto = new URL(links.mailtoHref); + const gmail = new URL(links.gmailHref); + expect(decodeURIComponent(mailto.pathname)).toBe(input.recipient); + expect(mailto.searchParams.get("subject")).toBe(links.subject); + expect(mailto.searchParams.get("body")).toBe(links.body); + expect(links.subject).toContain(input.productLabel); + expect(links.body).toContain(input.clientName); + expect(links.body).toContain(input.specialistName); + expect(links.body).toContain(input.productLabel); + expect(mailto.searchParams.size).toBe(2); + expect(links.mailtoHref).toContain("%26B%3F%23"); + expect(gmail.origin + gmail.pathname).toBe("https://mail.google.com/mail/"); + expect(gmail.searchParams.get("view")).toBe("cm"); + expect(gmail.searchParams.get("fs")).toBe("1"); + expect(gmail.searchParams.get("to")).toBe(input.recipient); + expect(gmail.searchParams.get("su")).toBe(links.subject); + expect(gmail.searchParams.get("body")).toBe(links.body); + }); + + it("shows the proposed instant in the provided IANA timezone", () => { + const { body } = buildEmailSchedulingLinks(input); + expect(body).toContain("20/10/2026 14:30 (America/Sao_Paulo)"); + expect(body).toContain("\n"); + }); + + it("removes header line breaks and encodes hostile recipient delimiters", () => { + const links = buildEmailSchedulingLinks({ + ...input, + recipient: "ana@example.com\r\nBcc:evil@example.com?subject=evil&bcc=x#y", + productLabel: "Carro\r\nBcc:evil@example.com", + }); + // Body line breaks are intentional; sanitize only the recipient and subject headers. + expect(decodeURIComponent(new URL(links.mailtoHref).pathname)).not.toContain("\r\nBcc:"); + expect(links.subject).not.toMatch(/[\r\n]/); + expect(new URL(links.mailtoHref).searchParams.size).toBe(2); + expect(new URL(links.gmailHref).searchParams.get("to")).not.toMatch(/[\r\n]/); + }); + + it("bounds the subject and body without breaking Unicode encoding", () => { + const links = buildEmailSchedulingLinks({ + ...input, + productLabel: "🚗".repeat(1000), + clientName: "á".repeat(3000), + }); + expect(Array.from(links.subject).length).toBeLessThanOrEqual(160); + expect(Array.from(links.body).length).toBeLessThanOrEqual(1800); + expect(links.body).toContain("20/10/2026 14:30 (America/Sao_Paulo)"); + expect(links.body).toContain(input.specialistName); + expect(links.body).toContain("á"); + expect(links.body).toContain("🚗"); + expect(new URL(links.mailtoHref).searchParams.get("subject")).toBe(links.subject); + expect(new URL(links.gmailHref).searchParams.get("body")).toBe(links.body); + }); + + it("rejects an invalid instant or timezone", () => { + expect(() => buildEmailSchedulingLinks({ ...input, appointmentDatetime: "invalid" })).toThrow(); + expect(() => buildEmailSchedulingLinks({ ...input, timeZone: "invalid" })).toThrow(); + expect(() => buildEmailSchedulingLinks({ ...input, timeZone: "" })).toThrow(); + }); +}); diff --git a/frontend/src/lib/email-scheduling.ts b/frontend/src/lib/email-scheduling.ts new file mode 100644 index 0000000..af51c68 --- /dev/null +++ b/frontend/src/lib/email-scheduling.ts @@ -0,0 +1,48 @@ +import { parseAppointmentIso } from "./appointment-datetime"; + +export interface EmailSchedulingInput { + recipient: string; + specialistName: string; + clientName: string; + productLabel: string; + appointmentDatetime: string; + timeZone: string; +} + +function truncate(value: string, limit: number): string { + return Array.from(value).slice(0, limit).join(""); +} + +export function buildEmailSchedulingLinks(input: EmailSchedulingInput): { + mailtoHref: string; + gmailHref: string; + subject: string; + body: string; +} { + const date = parseAppointmentIso(input.appointmentDatetime); + if (!input.timeZone.trim()) throw new Error("Selecione um fuso horário válido"); + const formatter = new Intl.DateTimeFormat("pt-BR", { + timeZone: input.timeZone, + year: "numeric", month: "2-digit", day: "2-digit", + hour: "2-digit", minute: "2-digit", hourCycle: "h23", + }); + const parts = formatter.formatToParts(date); + const part = (type: Intl.DateTimeFormatPartTypes) => parts.find((item) => item.type === type)?.value; + const when = `${part("day")}/${part("month")}/${part("year")} ${part("hour")}:${part("minute")} (${input.timeZone})`; + const recipient = input.recipient.replace(/[\r\n]/g, "").trim(); + const subject = truncate(`Interesse no produto: ${input.productLabel}`.replace(/[\r\n]/g, ""), 160); + // Cap variable fields first so a large name/product cannot remove the proposed instant. + const body = truncate( + `Olá, ${truncate(input.specialistName, 120)}!\n\nMeu nome é ${truncate(input.clientName, 120)} e tenho interesse no produto ${truncate(input.productLabel, 1000)}.\n\nGostaria de solicitar uma reunião para ${when}.\n\nPodemos confirmar esse horário?\n\nObrigado(a)!`, + 1800, + ); + const to = encodeURIComponent(recipient); + const encodedSubject = encodeURIComponent(subject); + const encodedBody = encodeURIComponent(body); + return { + mailtoHref: `mailto:${to}?subject=${encodedSubject}&body=${encodedBody}`, + gmailHref: `https://mail.google.com/mail/?view=cm&fs=1&to=${to}&su=${encodedSubject}&body=${encodedBody}`, + subject, + body, + }; +} diff --git a/frontend/src/lib/whatsapp.test.ts b/frontend/src/lib/whatsapp.test.ts new file mode 100644 index 0000000..99aa7e3 --- /dev/null +++ b/frontend/src/lib/whatsapp.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from "vitest"; +import { buildWhatsAppHref } from "./whatsapp"; + +describe("WhatsApp contact links", () => { + it.each([ + ["(11) 98765-4321", "5511987654321"], + ["+55 11 98765-4321", "5511987654321"], + ["(11) 3456-7890", "551134567890"], + ["55 11 3456-7890", "551134567890"], + ["(55) 98765-4321", "5555987654321"], + ])("normalizes Brazilian contact %s", (phone, digits) => { + expect(buildWhatsAppHref(phone)).toBe(`https://wa.me/${digits}`); + }); + + it.each(["", "123", "abc", "+1 234 567 89012", "551198765432100", "123456789012"])( + "does not link invalid contact %j", (phone) => { + expect(buildWhatsAppHref(phone)).toBeNull(); + }, + ); +}); diff --git a/frontend/src/lib/whatsapp.ts b/frontend/src/lib/whatsapp.ts new file mode 100644 index 0000000..6afa82a --- /dev/null +++ b/frontend/src/lib/whatsapp.ts @@ -0,0 +1,7 @@ +export function buildWhatsAppHref(phone: string): string | null { + const digits = phone.replace(/\D/g, ""); + const normalized = /^\d{10,11}$/.test(digits) + ? `55${digits}` + : /^55\d{10,11}$/.test(digits) ? digits : null; + return normalized ? `https://wa.me/${normalized}` : null; +} diff --git a/frontend/src/services/appointments.service.test.ts b/frontend/src/services/appointments.service.test.ts new file mode 100644 index 0000000..5db8407 --- /dev/null +++ b/frontend/src/services/appointments.service.test.ts @@ -0,0 +1,93 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import api from "./api"; +import { checkExistingAppointment, createPendingAppointment, createConsultancyAppointment } from "./appointments.service"; +import * as service from "./appointments.service"; +import type { ProductPendingAppointmentInput } from "./appointments.service"; + +vi.mock("./api", () => ({ default: { get: vi.fn(), post: vi.fn() } })); +afterEach(() => vi.resetAllMocks()); + +const base = { + client_id: "customer-1", specialist_id: "specialist-1", product_type: "CAR" as const, product_id: "car-1", +}; +const snapshot = { + appointment_id: "appointment-1", process_id: "process-1", appointment_status: "PENDING" as const, + scheduling_method: "EMAIL" as const, appointment_datetime: "2099-10-20T17:30:00.000Z", +}; + +describe("owned existing appointment check", () => { + it.each([{ exists: false }, { exists: true, ...snapshot }])("returns the discriminated result without sending client identity", async (result) => { + vi.mocked(api.get).mockResolvedValue({ data: { success: true, message: "Consulta realizada com sucesso", data: result } }); + await expect(checkExistingAppointment("specialist-1", "CAR", "car-1")).resolves.toEqual(result); + expect(api.get).toHaveBeenCalledWith("/appointments/check", { + withCredentials: true, + params: { specialist_id: "specialist-1", product_type: "CAR", product_id: "car-1" }, + }); + }); + + it("propagates API failures so failed checks cannot become false negatives", async () => { + const error = new Error("Sessão expirada"); + vi.mocked(api.get).mockRejectedValue(error); + await expect(checkExistingAppointment("specialist-1", "CAR", "car-1")).rejects.toBe(error); + }); +}); + +describe("pending product request contracts", () => { + it("sends a dated EMAIL proposal and returns its process ID", async () => { + const input: ProductPendingAppointmentInput = { ...base, scheduling_method: "EMAIL", appointment_datetime: snapshot.appointment_datetime }; + const created = { ...base, id: snapshot.appointment_id, process_id: snapshot.process_id, status: "PENDING" as const, appointment_datetime: snapshot.appointment_datetime, scheduling_method: "EMAIL" as const, created_at: "2026-10-14T12:00:00Z", updated_at: "2026-10-14T12:00:00Z" }; + vi.mocked(api.post).mockResolvedValue({ data: { success: true, data: created } }); + await expect(createPendingAppointment(input)).resolves.toEqual(created); + expect(api.post).toHaveBeenCalledWith("/appointments/pending", input, { withCredentials: true }); + }); + + it.each([undefined, "", "invalid", "2000-01-01T00:00:00.000Z", "2099-10-20T17:30", "2099-02-30T17:30:00Z", "2099-01-01T24:00:00Z"])("rejects EMAIL with absent/invalid/past/non-ISO datetime %j before HTTP", async (appointment_datetime) => { + // Simulates untyped callers crossing the runtime boundary. + await expect(createPendingAppointment({ ...base, scheduling_method: "EMAIL", appointment_datetime } as ProductPendingAppointmentInput)).rejects.toThrow(); + expect(api.post).not.toHaveBeenCalled(); + }); + + it("rejects client datetime on a CALENDLY request at runtime", async () => { + const input = { ...base, scheduling_method: "CALENDLY", appointment_datetime: snapshot.appointment_datetime }; + await expect(createPendingAppointment(input as unknown as ProductPendingAppointmentInput)).rejects.toThrow(); + expect(api.post).not.toHaveBeenCalled(); + }); + + it("preserves CALENDLY product creation without datetime", async () => { + vi.mocked(api.post).mockResolvedValue({ data: { data: { id: "appointment-1", process_id: "process-1" } } }); + await createPendingAppointment({ ...base, scheduling_method: "CALENDLY" }); + expect(api.post).toHaveBeenCalledWith("/appointments/pending", { ...base, scheduling_method: "CALENDLY" }, { withCredentials: true }); + }); + + it("preserves consultancy EMAIL without datetime", async () => { + vi.mocked(api.post).mockResolvedValue({ data: { data: { id: "appointment-1" } } }); + await createConsultancyAppointment({ client_id: base.client_id, specialist_id: base.specialist_id, scheduling_method: "EMAIL" }); + expect(api.post).toHaveBeenCalledWith("/appointments/pending", { client_id: base.client_id, specialist_id: base.specialist_id, scheduling_method: "EMAIL" }, { withCredentials: true }); + }); +}); + +describe("duplicate recovery", () => { + it.each([snapshot, { ...snapshot, appointment_id: null, appointment_status: null, scheduling_method: null, appointment_datetime: null }])("reads only the owned snapshot at error.details.existing_request", (existing_request) => { + expect(service.getActiveProcessSnapshot({ response: { status: 409, data: { error: { code: "ACTIVE_PROCESS_EXISTS", details: { existing_request } } } } })).toEqual(existing_request); + }); + + it.each([ + { response: { status: 409, data: { message: "Conflito" } } }, + { response: { status: 409, data: { error: { code: "CALENDLY_UNAVAILABLE", details: { existing_request: snapshot } } } } }, + { response: { status: 400, data: { error: { code: "ACTIVE_PROCESS_EXISTS", details: { existing_request: snapshot } } } } }, + { response: { status: 409, data: { code: "ACTIVE_PROCESS_EXISTS", existing_request: snapshot } } }, + { response: { status: 409, data: { error: { code: "ACTIVE_PROCESS_EXISTS", details: { existing_request: { appointment_id: "a" } } } } } }, + null, + ])("leaves ordinary errors and malformed duplicate payloads unrecovered", (error) => { + expect(service.getActiveProcessSnapshot(error)).toBeNull(); + }); +}); + +// Compile-time boundary: the product union requires EMAIL datetime and forbids CALENDLY datetime. +const emailInput: ProductPendingAppointmentInput = { ...base, scheduling_method: "EMAIL", appointment_datetime: snapshot.appointment_datetime }; +const calendlyInput: ProductPendingAppointmentInput = { ...base, scheduling_method: "CALENDLY" }; +// @ts-expect-error EMAIL product proposals require a datetime. +const missingEmailDatetime: ProductPendingAppointmentInput = { ...base, scheduling_method: "EMAIL" }; +// @ts-expect-error CALENDLY datetime is supplied by synchronized callbacks only. +const clientCalendlyDatetime: ProductPendingAppointmentInput = { ...base, scheduling_method: "CALENDLY", appointment_datetime: snapshot.appointment_datetime }; +void [emailInput, calendlyInput, missingEmailDatetime, clientCalendlyDatetime]; diff --git a/frontend/src/services/appointments.service.ts b/frontend/src/services/appointments.service.ts index d5a201f..b12486f 100644 --- a/frontend/src/services/appointments.service.ts +++ b/frontend/src/services/appointments.service.ts @@ -1,5 +1,6 @@ import api from "./api"; import type { ProductCurrency } from "../types/types"; +import { parseAppointmentIso } from "../lib/appointment-datetime"; export type AppointmentSchedulingMethod = "CALENDLY" | "EMAIL" | "PLATFORM"; @@ -54,6 +55,61 @@ export interface ApiResponse { data: T; } +export type ExistingAppointmentCheck = + | { exists: false } + | { + exists: true; + appointment_id: string; + process_id: string; + appointment_status: Appointment["status"]; + scheduling_method: AppointmentSchedulingMethod | null; + appointment_datetime: string | null; + }; + +export interface ActiveProcessSnapshot { + process_id: string; + appointment_id: string | null; + appointment_status: Appointment["status"] | null; + scheduling_method: AppointmentSchedulingMethod | null; + appointment_datetime: string | null; +} + +interface BaseProductRequest { + client_id: string; + specialist_id: string; + product_type: "CAR" | "BOAT" | "AIRCRAFT"; + product_id: string; + notes?: string; +} + +export type ProductPendingAppointmentInput = + | (BaseProductRequest & { scheduling_method: "EMAIL"; appointment_datetime: string }) + | (BaseProductRequest & { scheduling_method: "CALENDLY"; appointment_datetime?: never }); + +export type PendingAppointmentCreated = Appointment & { process_id: string }; + +/** Only the backend's dedicated owned-duplicate response can recover an active request. */ +export function getActiveProcessSnapshot(error: unknown): ActiveProcessSnapshot | null { + const record = (value: unknown): Record | null => + typeof value === "object" && value !== null ? value as Record : null; + const response = record(record(error)?.response); + const payload = record(record(response?.data)?.error); + if (response?.status !== 409 || payload?.code !== "ACTIVE_PROCESS_EXISTS") return null; + const snapshot = record(record(payload.details)?.existing_request); + if (!snapshot || typeof snapshot.process_id !== "string" || !snapshot.process_id + || !(snapshot.appointment_id === null || typeof snapshot.appointment_id === "string") + || !(snapshot.appointment_datetime === null || typeof snapshot.appointment_datetime === "string") + || !(snapshot.appointment_status === null || ["PENDING", "SCHEDULED", "COMPLETED", "CANCELLED"].includes(snapshot.appointment_status as string)) + || !(snapshot.scheduling_method === null || ["EMAIL", "CALENDLY", "PLATFORM"].includes(snapshot.scheduling_method as string))) return null; + return { + process_id: snapshot.process_id, + appointment_id: snapshot.appointment_id as string | null, + appointment_status: snapshot.appointment_status as ActiveProcessSnapshot["appointment_status"], + scheduling_method: snapshot.scheduling_method as ActiveProcessSnapshot["scheduling_method"], + appointment_datetime: snapshot.appointment_datetime as string | null, + }; +} + export interface RegisterCalendlyScheduledPayload { event_uri: string; invitee_uri: string; @@ -78,53 +134,41 @@ export interface CalendlyOAuthStatus { } /** - * Verifica se existe um agendamento entre cliente e especialista para um produto específico - * @param clientId - ID do cliente - * @param specialistId - ID do especialista - * @param productType - Tipo do produto (CAR, BOAT, AIRCRAFT) - * @param productId - ID do produto - * @returns true se existe agendamento ativo, false caso contrário + * Consulta o próprio pedido; a identidade do cliente vem exclusivamente do JWT. */ export async function checkExistingAppointment( - clientId: string, specialistId: string, productType: "CAR" | "BOAT" | "AIRCRAFT", productId: string, -): Promise { - try { - const response = await api.get>( - `/appointments/check`, - { - withCredentials: true, - params: { - client_id: clientId, - specialist_id: specialistId, - product_type: productType, - product_id: productId, - }, +): Promise { + const response = await api.get>( + "/appointments/check", + { + withCredentials: true, + params: { + specialist_id: specialistId, + product_type: productType, + product_id: productId, }, - ); - return response.data.data; - } catch (error) { - console.error("Erro ao verificar agendamento:", error); - return null; - } + }, + ); + return response.data.data; } /** - * Cria um agendamento PENDING (cliente clicou no link do Calendly) + * Cria um pedido PENDING por e-mail com data proposta ou pelo Calendly sem data do cliente. * @param data - Dados do agendamento * @returns O agendamento criado em status PENDING */ -export async function createPendingAppointment(data: { - client_id: string; - specialist_id: string; - product_type: "CAR" | "BOAT" | "AIRCRAFT"; - product_id: string; - scheduling_method: "CALENDLY" | "EMAIL"; - notes?: string; -}): Promise { - const response = await api.post>( +export async function createPendingAppointment(data: ProductPendingAppointmentInput): Promise { + if (data.scheduling_method === "CALENDLY" && data.appointment_datetime !== undefined) { + throw new Error("O horário Calendly é definido pela integração"); + } + if (data.scheduling_method === "EMAIL") { + const parsed = parseAppointmentIso(data.appointment_datetime); + if (parsed.getTime() <= Date.now()) throw new Error("Selecione uma data e hora futuras"); + } + const response = await api.post>( "/appointments/pending", data, { withCredentials: true }, diff --git a/frontend/src/services/specialists.service.test.ts b/frontend/src/services/specialists.service.test.ts index 760bdf5..1e49374 100644 --- a/frontend/src/services/specialists.service.test.ts +++ b/frontend/src/services/specialists.service.test.ts @@ -28,6 +28,13 @@ describe("public specialist profile", () => { "/specialists/specialist-1/public-profile", ); }); + + it("propagates public-profile errors instead of falling back to a private endpoint", async () => { + const error = new Error("Perfil indisponível"); + vi.mocked(api.get).mockRejectedValueOnce(error); + await expect(specialistService.getPublicSpecialistById("specialist-1")).rejects.toBe(error); + expect(api.get).toHaveBeenCalledExactlyOnceWith("/specialists/specialist-1/public-profile"); + }); }); const createBase = { From 5ddfb15fb4119192d92b3a910d350569d4848924 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 09:29:35 -0300 Subject: [PATCH 11/60] feat: unify no-Calendly email request flow --- .../EmailSchedulingSuccess.test.tsx | 307 +++++++ .../appointments/EmailSchedulingSuccess.tsx | 159 ++++ .../NoCalendlySchedulingActions.test.tsx | 101 +-- .../NoCalendlySchedulingActions.tsx | 93 +- .../src/pages/catalog/ProductPage.test.tsx | 781 +++++++++++++--- frontend/src/pages/catalog/ProductPage.tsx | 841 ++++++++---------- 6 files changed, 1520 insertions(+), 762 deletions(-) create mode 100644 frontend/src/components/appointments/EmailSchedulingSuccess.test.tsx create mode 100644 frontend/src/components/appointments/EmailSchedulingSuccess.tsx diff --git a/frontend/src/components/appointments/EmailSchedulingSuccess.test.tsx b/frontend/src/components/appointments/EmailSchedulingSuccess.test.tsx new file mode 100644 index 0000000..7733032 --- /dev/null +++ b/frontend/src/components/appointments/EmailSchedulingSuccess.test.tsx @@ -0,0 +1,307 @@ +// @vitest-environment jsdom + +import { StrictMode } from "react"; +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import EmailSchedulingSuccess from "./EmailSchedulingSuccess"; +import { buildEmailSchedulingLinks } from "../../lib/email-scheduling"; + +const props = { + appointmentId: "appointment-default", + recipient: "especialista@example.com", + specialistName: "Ana Silva", + clientName: "João Cliente", + productLabel: "Carro A&B?#", + appointmentDatetime: "2099-10-20T17:30:00.000Z", + timeZone: "America/Sao_Paulo", +}; + +describe("EmailSchedulingSuccess", () => { + const writeText = vi.fn(); + + beforeEach(() => { + sessionStorage.clear(); + Object.defineProperty(navigator, "clipboard", { + configurable: true, + value: { writeText }, + }); + writeText.mockResolvedValue(undefined); + }); + + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + vi.clearAllMocks(); + }); + + it("announces the persisted proposal with every email and process fallback", () => { + render(); + const links = buildEmailSchedulingLinks(props); + expect(screen.getByRole("status").getAttribute("aria-live")).toBe("polite"); + expect( + screen.getByRole("heading", { + name: "Solicitação de reunião registrada", + }), + ).toBeTruthy(); + expect( + screen.getByText(/aguardando confirmação do especialista/i), + ).toBeTruthy(); + expect( + screen + .getByRole("link", { name: "Abrir aplicativo de e-mail" }) + .getAttribute("href"), + ).toBe(links.mailtoHref); + const gmail = screen.getByRole("link", { name: "Abrir no Gmail" }); + expect(gmail.getAttribute("href")).toBe(links.gmailHref); + expect(gmail.getAttribute("target")).toBe("_blank"); + expect(gmail.getAttribute("rel")).toBe("noopener noreferrer"); + expect( + screen + .getByRole("link", { name: "Acompanhar processo" }) + .getAttribute("href"), + ).toBe("/customer/processes"); + const address = screen.getByRole("textbox", { + name: "E-mail do especialista", + }) as HTMLInputElement; + expect(address.value).toBe(props.recipient); + expect(address.readOnly).toBe(true); + }); + + it("opens only after success is committed and focuses its heading", async () => { + let committedAtOpen = false; + let markerAtOpen: string | null = null; + const openMailClient = vi.fn(() => { + committedAtOpen = Boolean(screen.queryByRole("status")); + markerAtOpen = sessionStorage.getItem( + "email-request-opened:appointment-focus", + ); + }); + render( + , + ); + await waitFor(() => expect(openMailClient).toHaveBeenCalledOnce()); + expect(committedAtOpen).toBe(true); + expect(markerAtOpen).toBe("1"); + expect(openMailClient).toHaveBeenCalledWith( + buildEmailSchedulingLinks(props).mailtoHref, + ); + expect(document.activeElement).toBe( + screen.getByRole("heading", { + name: "Solicitação de reunião registrada", + }), + ); + }); + + it("does not repeat automatic opening on rerender, StrictMode or remount", async () => { + const openMailClient = vi.fn(); + const view = render( + + + , + ); + await waitFor(() => expect(openMailClient).toHaveBeenCalledOnce()); + view.rerender( + + + , + ); + view.unmount(); + render( + , + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(openMailClient).toHaveBeenCalledOnce(); + }); + + it("honors the session marker even on a first render in this module", async () => { + sessionStorage.setItem("email-request-opened:appointment-session", "1"); + const openMailClient = vi.fn(); + render( + , + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(openMailClient).not.toHaveBeenCalled(); + }); + + it("recovers fallbacks without automatic opening or focus theft", async () => { + const openMailClient = vi.fn(); + render( + , + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(openMailClient).not.toHaveBeenCalled(); + expect( + sessionStorage.getItem("email-request-opened:appointment-recovered"), + ).toBeNull(); + expect(document.activeElement).not.toBe( + screen.getByRole("heading", { + name: "Solicitação de reunião registrada", + }), + ); + expect( + screen.getByRole("link", { name: "Abrir aplicativo de e-mail" }), + ).toBeTruthy(); + }); + + it("keeps an in-memory one-shot across remount when session storage is blocked", async () => { + vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => { + throw new Error("blocked"); + }); + vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { + throw new Error("blocked"); + }); + const openMailClient = vi.fn(); + const view = render( + , + ); + await waitFor(() => expect(openMailClient).toHaveBeenCalledOnce()); + view.unmount(); + render( + , + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(openMailClient).toHaveBeenCalledOnce(); + }); + + it("preserves fallbacks and the one-shot marker when the opener throws", async () => { + const openMailClient = vi.fn(() => { + throw new Error("mail app unavailable"); + }); + const view = render( + , + ); + await waitFor(() => expect(openMailClient).toHaveBeenCalledOnce()); + expect(screen.getByRole("status")).toBeTruthy(); + expect(screen.getByRole("link", { name: "Abrir no Gmail" })).toBeTruthy(); + expect( + sessionStorage.getItem("email-request-opened:appointment-throw"), + ).toBe("1"); + view.rerender( + , + ); + expect(openMailClient).toHaveBeenCalledOnce(); + }); + + it("cancels an automatic attempt when the panel unmounts before it runs", async () => { + const openMailClient = vi.fn(); + const view = render( + , + ); + view.unmount(); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(openMailClient).not.toHaveBeenCalled(); + expect( + sessionStorage.getItem("email-request-opened:appointment-cancelled"), + ).toBeNull(); + }); + + it("uses the browser mail client by default after committing the panel", async () => { + const open = vi.spyOn(window, "open").mockImplementation(() => null); + render( + , + ); + await waitFor(() => + expect(open).toHaveBeenCalledWith( + buildEmailSchedulingLinks(props).mailtoHref, + "_self", + ), + ); + }); + + it("announces successful clipboard copying", async () => { + render(); + fireEvent.click(screen.getByRole("button", { name: "Copiar e-mail" })); + await waitFor(() => + expect(writeText).toHaveBeenCalledWith(props.recipient), + ); + expect(await screen.findByText("E-mail copiado")).toBeTruthy(); + }); + + it.each(["unavailable", "rejected"])( + "announces %s clipboard failure while preserving a selectable address", + async (kind) => { + if (kind === "unavailable") + Object.defineProperty(navigator, "clipboard", { + configurable: true, + value: undefined, + }); + else writeText.mockRejectedValue(new Error("denied")); + render(); + fireEvent.click(screen.getByRole("button", { name: "Copiar e-mail" })); + expect((await screen.findByRole("alert")).textContent).toMatch( + /não foi possível copiar/i, + ); + const address = screen.getByRole("textbox", { + name: "E-mail do especialista", + }) as HTMLInputElement; + address.focus(); + address.select(); + expect(address.selectionEnd).toBe(props.recipient.length); + }, + ); +}); diff --git a/frontend/src/components/appointments/EmailSchedulingSuccess.tsx b/frontend/src/components/appointments/EmailSchedulingSuccess.tsx new file mode 100644 index 0000000..5afd849 --- /dev/null +++ b/frontend/src/components/appointments/EmailSchedulingSuccess.tsx @@ -0,0 +1,159 @@ +import { useEffect, useRef, useState } from "react"; +import { Check, Copy, ExternalLink, Mail } from "lucide-react"; +import { + buildEmailSchedulingLinks, + type EmailSchedulingInput, +} from "../../lib/email-scheduling"; +import Button from "../ui/button"; +import { Alert } from "../ui/alert"; + +interface EmailSchedulingSuccessProps extends EmailSchedulingInput { + appointmentId: string; + autoOpen?: boolean; + openMailClient?(href: string): void; +} + +// Storage may be unavailable; retain the one-shot for this browser document too. +const openedAppointments = new Set(); +const openBrowserMailClient = (href: string) => { + window.open(href, "_self"); +}; + +export default function EmailSchedulingSuccess({ + appointmentId, + autoOpen = false, + openMailClient = openBrowserMailClient, + ...input +}: EmailSchedulingSuccessProps) { + const headingRef = useRef(null); + const [copyState, setCopyState] = useState<"idle" | "copied" | "failed">( + "idle", + ); + const { mailtoHref, gmailHref } = buildEmailSchedulingLinks(input); + + useEffect(() => { + if (!autoOpen) return; + const timer = setTimeout(() => { + const sessionKey = `email-request-opened:${appointmentId}`; + if (openedAppointments.has(appointmentId)) return; + try { + if (sessionStorage.getItem(sessionKey) === "1") return; + } catch { + /* The in-memory marker remains available. */ + } + + // Consume only a committed attempt, never an effect cancelled by StrictMode. + openedAppointments.add(appointmentId); + try { + sessionStorage.setItem(sessionKey, "1"); + } catch { + /* Optional persistence. */ + } + headingRef.current?.focus(); + try { + openMailClient(mailtoHref); + } catch { + /* The persisted request and links remain valid. */ + } + }, 0); + return () => clearTimeout(timer); + }, [appointmentId, autoOpen, mailtoHref, openMailClient]); + + const handleCopy = async () => { + try { + await navigator.clipboard.writeText(input.recipient); + setCopyState("copied"); + } catch { + setCopyState("failed"); + } + }; + + const linkClassName = + "inline-flex items-center justify-center gap-2 rounded-lg border border-border px-4 py-3 text-sm font-semibold text-ink focus:outline-none focus:ring-2 focus:ring-focus-ring"; + return ( +
+
+

+ Solicitação de reunião registrada +

+

+ Aguardando confirmação do especialista. O horário sugerido ainda não + está reservado. +

+

+ Data proposta:{" "} + {" "} + ({input.timeZone}) +

+
+

+ Envie a mensagem pelo aplicativo de e-mail ou pelo Gmail para combinar a + reunião. O envio é concluído no aplicativo escolhido. +

+ +
+ + + {copyState === "copied" && ( +

+ E-mail copiado +

+ )} + {copyState === "failed" && ( + + Não foi possível copiar. Selecione o endereço de e-mail acima e + copie manualmente. + + )} +
+ + Acompanhar processo + +
+ ); +} diff --git a/frontend/src/components/appointments/NoCalendlySchedulingActions.test.tsx b/frontend/src/components/appointments/NoCalendlySchedulingActions.test.tsx index d34628c..0eb43d8 100644 --- a/frontend/src/components/appointments/NoCalendlySchedulingActions.test.tsx +++ b/frontend/src/components/appointments/NoCalendlySchedulingActions.test.tsx @@ -1,88 +1,33 @@ // @vitest-environment jsdom -import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; import NoCalendlySchedulingActions from "./NoCalendlySchedulingActions"; -describe("NoCalendlySchedulingActions", () => { - const writeText = vi.fn(); - - beforeEach(() => { - Object.defineProperty(navigator, "clipboard", { - configurable: true, - value: { writeText }, - }); - writeText.mockResolvedValue(undefined); - }); - - afterEach(() => { - cleanup(); - vi.clearAllMocks(); - }); - - it("offers both scheduling paths and a permanent email fallback", async () => { - const onEmail = vi.fn(); - const onChooseDateTime = vi.fn(); - render( - , - ); - - fireEvent.click(screen.getByRole("button", { name: "Enviar e-mail" })); - fireEvent.click( - screen.getByRole("button", { name: "Escolher data e hora" }), - ); - - expect(onEmail).toHaveBeenCalledOnce(); - expect(onChooseDateTime).toHaveBeenCalledOnce(); - expect( - screen.getByRole("link", { name: "especialista@example.com" }), - ).toBeTruthy(); +afterEach(cleanup); - fireEvent.click(screen.getByRole("button", { name: "Copiar e-mail" })); - await waitFor(() => { - expect(writeText).toHaveBeenCalledWith("especialista@example.com"); - }); - expect(await screen.findByText("E-mail copiado")).toBeTruthy(); - }); - - it("disables both actions while a request is running", () => { - render( - , - ); - - expect( - (screen.getByRole("button", { name: "Enviar e-mail" }) as HTMLButtonElement) - .disabled, - ).toBe(true); +describe("NoCalendlySchedulingActions", () => { + it("offers one request action and explains that the chosen time is a proposal", () => { + const onRequest = vi.fn(); + render(); + fireEvent.click(screen.getByRole("button", { name: "Solicitar reunião" })); + expect(onRequest).toHaveBeenCalledOnce(); + expect(screen.getAllByRole("button")).toHaveLength(1); + expect(screen.getByText(/confirmação do especialista/i)).toBeTruthy(); + expect(screen.queryByRole("button", { name: "Enviar e-mail" })).toBeNull(); expect( - (screen.getByRole("button", { - name: "Escolher data e hora", - }) as HTMLButtonElement).disabled, - ).toBe(true); + screen.queryByRole("button", { name: "Escolher data e hora" }), + ).toBeNull(); }); - it("can preserve only the copyable email after creating the request", () => { - render( - , - ); - - expect(screen.queryByRole("button", { name: "Enviar e-mail" })).toBeNull(); - expect( - screen.getByRole("link", { name: "especialista@example.com" }), - ).toBeTruthy(); + it("disables the request action while busy", () => { + const onRequest = vi.fn(); + render(); + const button = screen.getByRole("button", { + name: "Solicitar reunião", + }) as HTMLButtonElement; + expect(button.disabled).toBe(true); + fireEvent.click(button); + expect(onRequest).not.toHaveBeenCalled(); }); }); diff --git a/frontend/src/components/appointments/NoCalendlySchedulingActions.tsx b/frontend/src/components/appointments/NoCalendlySchedulingActions.tsx index c175be4..f82a6f3 100644 --- a/frontend/src/components/appointments/NoCalendlySchedulingActions.tsx +++ b/frontend/src/components/appointments/NoCalendlySchedulingActions.tsx @@ -1,86 +1,35 @@ -import { useState } from "react"; -import { CalendarClock, Check, Copy, Loader2, Mail } from "lucide-react"; +import { CalendarClock, Loader2 } from "lucide-react"; import Button from "../ui/button"; interface NoCalendlySchedulingActionsProps { - specialistEmail: string; busy?: boolean; - showActions?: boolean; - onEmail(): void; - onChooseDateTime(): void; + onRequest(): void; } export default function NoCalendlySchedulingActions({ - specialistEmail, busy = false, - showActions = true, - onEmail, - onChooseDateTime, + onRequest, }: NoCalendlySchedulingActionsProps) { - const [copied, setCopied] = useState(false); - - const handleCopy = async () => { - try { - await navigator.clipboard.writeText(specialistEmail); - setCopied(true); - } catch { - setCopied(false); - } - }; - return (
- {showActions && ( - <> -

- Este especialista não usa agenda online. Você pode combinar o horário - por e-mail ou escolher agora uma data e hora para a reunião na - plataforma. -

- -
- - -
- - )} - -
-

E-mail do especialista

-
- - {specialistEmail} - - -
-
+

+ Proponha uma data e hora para a reunião. O pedido ficará aguardando + confirmação do especialista e você poderá enviar uma mensagem por + e-mail. +

+
); } diff --git a/frontend/src/pages/catalog/ProductPage.test.tsx b/frontend/src/pages/catalog/ProductPage.test.tsx index e675826..505a600 100644 --- a/frontend/src/pages/catalog/ProductPage.test.tsx +++ b/frontend/src/pages/catalog/ProductPage.test.tsx @@ -1,48 +1,66 @@ // @vitest-environment jsdom -import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; -import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { MemoryRouter, Route, Routes, useNavigate } from "react-router-dom"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import ProductPage from "./ProductPage"; import { getCarById } from "../../services/cars.service"; import { getUserById } from "../../services/users.service"; -import { getPublicSpecialistById, type PublicSpecialistProfile } from "../../services/specialists.service"; +import { + getPublicSpecialistById, + type PublicSpecialistProfile, +} from "../../services/specialists.service"; import { checkExistingAppointment, createPendingAppointment, createPlatformAppointment, + type ActiveProcessSnapshot, + type PendingAppointmentCreated, } from "../../services/appointments.service"; +const { authState, openPopup } = vi.hoisted(() => ({ + authState: { + user: { + id: "customer-1", + role: "CUSTOMER", + name: "Cliente", + surname: "Teste", + email: "cliente@example.com", + }, + }, + openPopup: vi.fn(), +})); + vi.mock("../../services/cars.service", () => ({ getCarById: vi.fn() })); vi.mock("../../services/boats.service", () => ({ getBoatById: vi.fn() })); -vi.mock("../../services/aircrafts.service", () => ({ getAircraftById: vi.fn() })); +vi.mock("../../services/aircrafts.service", () => ({ + getAircraftById: vi.fn(), +})); vi.mock("../../services/users.service", () => ({ getUserById: vi.fn() })); -vi.mock("../../services/specialists.service", () => ({ getPublicSpecialistById: vi.fn() })); +vi.mock("../../services/specialists.service", () => ({ + getPublicSpecialistById: vi.fn(), +})); vi.mock("../../services/processes.service", () => ({ getProcessesByClient: vi.fn().mockResolvedValue([]), })); -vi.mock("../../services/appointments.service", () => ({ +vi.mock("../../services/appointments.service", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../services/appointments.service") + >()), checkExistingAppointment: vi.fn(), createPendingAppointment: vi.fn(), createPlatformAppointment: vi.fn(), })); vi.mock("../../store/authStateManager", () => ({ - useAuth: () => ({ - user: { - id: "customer-1", - role: "CUSTOMER", - name: "Cliente", - surname: "Teste", - email: "cliente@example.com", - }, - }), -})); -vi.mock("../../hooks/useCheckAppointment", () => ({ - useCheckAppointment: () => ({ - existingAppointment: null, - isLoading: false, - error: null, - }), + useAuth: (selector?: (state: typeof authState) => unknown) => + selector ? selector(authState) : authState, })); vi.mock("../../hooks/useCalendlyScheduling", () => ({ useCalendlyScheduling: () => ({ @@ -50,7 +68,7 @@ vi.mock("../../hooks/useCalendlyScheduling", () => ({ modalUrl: null, syncState: "idle", syncMessage: null, - openPopup: vi.fn(), + openPopup, closePopup: vi.fn(), }), })); @@ -75,7 +93,6 @@ const product = { created_at: "2026-01-01T00:00:00.000Z", updated_at: "2026-01-01T00:00:00.000Z", }; - const specialist: PublicSpecialistProfile = { id: "specialist-1", name: "Especialista", @@ -85,197 +102,687 @@ const specialist: PublicSpecialistProfile = { speciality: "CAR", calendly_scheduling_available: false, }; - -const appointment = { - id: "appointment-1", +const appointment: PendingAppointmentCreated = { + id: "appointment-product-created", + process_id: "process-1", client_id: "customer-1", specialist_id: "specialist-1", - product_type: "CAR" as const, + product_type: "CAR", product_id: "car-1", appointment_datetime: "2099-09-20T17:30:00.000Z", - status: "SCHEDULED" as const, + status: "PENDING", + scheduling_method: "EMAIL", created_at: "2026-01-01T00:00:00.000Z", updated_at: "2026-01-01T00:00:00.000Z", }; +const existingRequest: ActiveProcessSnapshot = { + appointment_id: "appointment-recovered", + process_id: "process-1", + appointment_status: "PENDING", + scheduling_method: "EMAIL", + appointment_datetime: appointment.appointment_datetime ?? null, +}; -function renderPage() { - return render( +function ChangeProductButton() { + const navigate = useNavigate(); + return ( + + ); +} + +function page() { + return ( + } /> - Meus processos} - /> + Meus processos} /> - , + + ); +} + +async function chooseDateTime() { + fireEvent.click( + await screen.findByRole( + "button", + { name: "Solicitar reunião" }, + { timeout: 2000 }, + ), ); + fireEvent.change(screen.getByLabelText("Data e hora"), { + target: { value: "2099-09-20T14:30" }, + }); + fireEvent.click(screen.getByRole("button", { name: "Enviar solicitação" })); +} + +function duplicate(snapshot: ActiveProcessSnapshot) { + return { + response: { + status: 409, + data: { + error: { + code: "ACTIVE_PROCESS_EXISTS", + details: { existing_request: snapshot }, + }, + }, + }, + }; } describe("ProductPage scheduling", () => { beforeEach(() => { + sessionStorage.clear(); + authState.user = { + id: "customer-1", + role: "CUSTOMER", + name: "Cliente", + surname: "Teste", + email: "cliente@example.com", + }; vi.mocked(getCarById).mockResolvedValue(product); vi.mocked(getPublicSpecialistById).mockResolvedValue(specialist); - vi.mocked(getUserById).mockResolvedValue(specialist as never); - vi.mocked(checkExistingAppointment).mockResolvedValue(null); - vi.mocked(createPendingAppointment).mockResolvedValue({ - ...appointment, - status: "PENDING", - appointment_datetime: null, - }); - vi.mocked(createPlatformAppointment).mockResolvedValue(appointment); - }); - - it("loads specialist contact through the public profile without private user access", async () => { - renderPage(); - expect(await screen.findByRole("link", { name: "especialista@example.com" })).toBeTruthy(); - expect(getPublicSpecialistById).toHaveBeenCalledWith("specialist-1"); - expect(getUserById).not.toHaveBeenCalled(); + vi.mocked(checkExistingAppointment).mockResolvedValue({ exists: false }); + vi.mocked(createPendingAppointment).mockResolvedValue(appointment); + vi.spyOn(window, "open").mockImplementation(() => null); }); afterEach(() => { cleanup(); + vi.restoreAllMocks(); vi.clearAllMocks(); }); - it("keeps Calendly as the only path when it is configured", async () => { + it("loads the public specialist projection and checks the own request without a client ID", async () => { + render(page()); + expect( + await screen.findByRole( + "button", + { name: "Solicitar reunião" }, + { timeout: 2000 }, + ), + ).toBeTruthy(); + expect(getPublicSpecialistById).toHaveBeenCalledWith("specialist-1"); + expect(getUserById).not.toHaveBeenCalled(); + expect(checkExistingAppointment).toHaveBeenCalledWith( + "specialist-1", + "CAR", + "car-1", + ); + }); + + it("uses the false capability even when a stale Calendly URL remains", async () => { vi.mocked(getPublicSpecialistById).mockResolvedValue({ ...specialist, - calendly_url: "https://calendly.com/especialista", - calendly_scheduling_available: true, + calendly_url: "https://calendly.com/stale", }); - - renderPage(); - + render(page()); + expect( + await screen.findByRole( + "button", + { name: "Solicitar reunião" }, + { timeout: 2000 }, + ), + ).toBeTruthy(); expect( - await screen.findByRole("button", { + screen.queryByRole("button", { name: "Agendar reunião com o especialista", }), - ).toBeTruthy(); + ).toBeNull(); expect(screen.queryByRole("button", { name: "Enviar e-mail" })).toBeNull(); expect( screen.queryByRole("button", { name: "Escolher data e hora" }), ).toBeNull(); }); - it("creates the email request with its explicit scheduling method", async () => { - const openSpy = vi.spyOn(window, "open").mockImplementation(() => null); + it("keeps the active Calendly path and opens its popup only after creation", async () => { + vi.mocked(getPublicSpecialistById).mockResolvedValue({ + ...specialist, + calendly_url: "https://calendly.com/especialista", + calendly_scheduling_available: true, + }); vi.mocked(createPendingAppointment).mockResolvedValue({ ...appointment, - status: "PENDING", + scheduling_method: "CALENDLY", appointment_datetime: null, - scheduling_method: "EMAIL", }); - renderPage(); - - expect( - await screen.findByRole("link", { name: "especialista@example.com" }), - ).toBeTruthy(); + render(page()); fireEvent.click( - screen.getByRole("button", { name: "Enviar e-mail" }), + await screen.findByRole( + "button", + { name: "Agendar reunião com o especialista" }, + { timeout: 2000 }, + ), ); + await waitFor(() => + expect(openPopup).toHaveBeenCalledWith( + appointment.id, + "https://calendly.com/especialista", + ), + ); + const payload = vi.mocked(createPendingAppointment).mock.calls[0][0]; + expect(payload.scheduling_method).toBe("CALENDLY"); + expect(payload).not.toHaveProperty("appointment_datetime"); + expect( + screen.queryByRole("button", { name: "Solicitar reunião" }), + ).toBeNull(); + expect(window.open).not.toHaveBeenCalled(); + }); - await waitFor(() => { - expect(createPendingAppointment).toHaveBeenCalledWith( - expect.objectContaining({ scheduling_method: "EMAIL" }), - ); - expect(openSpy).toHaveBeenCalledWith( - expect.stringMatching(/^mailto:especialista@example\.com/), - "_self", - ); + it("uses only the true capability when its URL is unexpectedly missing", async () => { + vi.mocked(getPublicSpecialistById).mockResolvedValue({ + ...specialist, + calendly_scheduling_available: true, }); + render(page()); + fireEvent.click( + await screen.findByRole( + "button", + { name: "Agendar reunião com o especialista" }, + { timeout: 2000 }, + ), + ); expect( - screen.getByRole("link", { name: "especialista@example.com" }), - ).toBeTruthy(); - expect( - screen.getByRole("button", { name: "Acompanhar em Meus Processos" }), + await screen.findByText( + /Não foi possível abrir a agenda do especialista/, + ), ).toBeTruthy(); expect( - vi.mocked(createPendingAppointment).mock.invocationCallOrder[0], - ).toBeLessThan(openSpy.mock.invocationCallOrder[0]); + screen.queryByRole("button", { name: "Solicitar reunião" }), + ).toBeNull(); + expect(createPendingAppointment).not.toHaveBeenCalled(); }); - it("creates an internal appointment with the selected datetime", async () => { - renderPage(); - - fireEvent.click( - await screen.findByRole("button", { name: "Escolher data e hora" }), - ); - fireEvent.change(screen.getByLabelText("Data e hora"), { - target: { value: "2099-09-20T14:30" }, + it("keeps a generic Calendly 409 as an error without opening its popup or mail", async () => { + vi.mocked(getPublicSpecialistById).mockResolvedValue({ + ...specialist, + calendly_url: "https://calendly.com/especialista", + calendly_scheduling_available: true, + }); + vi.mocked(createPendingAppointment).mockRejectedValue({ + response: { status: 409 }, + friendlyMessage: "Agenda indisponível", }); + render(page()); fireEvent.click( - screen.getByRole("button", { name: "Confirmar agendamento" }), + await screen.findByRole( + "button", + { name: "Agendar reunião com o especialista" }, + { timeout: 2000 }, + ), ); - - await waitFor(() => { - expect(createPlatformAppointment).toHaveBeenCalledWith( - expect.objectContaining({ - appointment_datetime: new Date("2099-09-20T14:30").toISOString(), - }), - ); - expect(screen.getByText("Meus processos")).toBeTruthy(); - }); + expect(await screen.findByText("Agenda indisponível")).toBeTruthy(); + expect(openPopup).not.toHaveBeenCalled(); + expect(window.open).not.toHaveBeenCalled(); + expect(checkExistingAppointment).toHaveBeenCalledOnce(); + await new Promise((resolve) => setTimeout(resolve, 950)); + expect(screen.queryByText("Meus processos")).toBeNull(); }); - it("redirects to the existing process on a duplicate conflict", async () => { - vi.mocked(createPlatformAppointment).mockRejectedValue({ - response: { status: 409 }, - friendlyMessage: "Já existe processo ativo para este produto.", + it("prevents a second Calendly submission while its creation is unresolved", async () => { + vi.mocked(getPublicSpecialistById).mockResolvedValue({ + ...specialist, + calendly_url: "https://calendly.com/especialista", + calendly_scheduling_available: true, }); - vi.mocked(checkExistingAppointment).mockResolvedValue(appointment); - renderPage(); + let resolve!: (value: PendingAppointmentCreated) => void; + vi.mocked(createPendingAppointment).mockReturnValue( + new Promise((done) => { + resolve = done; + }), + ); + render(page()); + fireEvent.click( + await screen.findByRole( + "button", + { name: "Agendar reunião com o especialista" }, + { timeout: 2000 }, + ), + ); + await waitFor(() => + expect(createPendingAppointment).toHaveBeenCalledOnce(), + ); + expect( + ( + screen.getByRole("button", { + name: "Criando solicitação...", + }) as HTMLButtonElement + ).disabled, + ).toBe(true); + fireEvent.click( + screen.getByRole("button", { name: "Criando solicitação..." }), + ); + expect(createPendingAppointment).toHaveBeenCalledOnce(); + expect(openPopup).not.toHaveBeenCalled(); + await act(async () => + resolve({ + ...appointment, + scheduling_method: "CALENDLY", + appointment_datetime: null, + }), + ); + expect(openPopup).toHaveBeenCalledOnce(); + }); + it("collects a proposal without creating or opening an email before submit", async () => { + render(page()); fireEvent.click( - await screen.findByRole("button", { name: "Escolher data e hora" }), + await screen.findByRole( + "button", + { name: "Solicitar reunião" }, + { timeout: 2000 }, + ), + ); + expect(screen.getByRole("dialog").textContent).toMatch( + /confirmação do especialista/i, ); - fireEvent.change(screen.getByLabelText("Data e hora"), { - target: { value: "2099-09-20T14:30" }, + expect( + ( + screen.getByRole("button", { + name: "Enviar solicitação", + }) as HTMLButtonElement + ).disabled, + ).toBe(true); + expect(createPendingAppointment).not.toHaveBeenCalled(); + expect(createPlatformAppointment).not.toHaveBeenCalled(); + expect(window.open).not.toHaveBeenCalled(); + }); + + it("creates PENDING EMAIL with the chosen ISO and commits a persistent panel before opening", async () => { + vi.mocked(createPendingAppointment).mockResolvedValue({ + ...appointment, + id: "appointment-product-initial-success", }); - fireEvent.click( - screen.getByRole("button", { name: "Confirmar agendamento" }), + let panelCommittedAtOpen = false; + let modalUnmountedAtOpen = false; + vi.mocked(window.open).mockImplementation(() => { + panelCommittedAtOpen = Boolean(screen.queryByRole("status")); + modalUnmountedAtOpen = screen.queryByRole("dialog") === null; + return null; + }); + render(page()); + await chooseDateTime(); + await waitFor(() => expect(window.open).toHaveBeenCalledOnce()); + expect(panelCommittedAtOpen).toBe(true); + expect(modalUnmountedAtOpen).toBe(true); + expect(createPendingAppointment).toHaveBeenCalledWith( + expect.objectContaining({ + client_id: "customer-1", + specialist_id: "specialist-1", + product_id: "car-1", + product_type: "CAR", + scheduling_method: "EMAIL", + appointment_datetime: new Date("2099-09-20T14:30").toISOString(), + }), + ); + expect(createPlatformAppointment).not.toHaveBeenCalled(); + expect(screen.getByRole("link", { name: "Abrir no Gmail" })).toBeTruthy(); + expect( + screen + .getByRole("link", { name: "Acompanhar processo" }) + .getAttribute("href"), + ).toBe("/customer/processes"); + expect(screen.queryByText("Meus processos")).toBeNull(); + expect(document.activeElement).toBe( + screen.getByRole("heading", { + name: "Solicitação de reunião registrada", + }), ); + }); - expect(await screen.findByText("Meus processos")).toBeTruthy(); + it("waits for the 201 response and prevents double submission while busy", async () => { + let resolve!: (value: PendingAppointmentCreated) => void; + vi.mocked(createPendingAppointment).mockReturnValue( + new Promise((done) => { + resolve = done; + }), + ); + render(page()); + await chooseDateTime(); + const submit = screen.getByRole("button", { + name: "Enviar solicitação", + }) as HTMLButtonElement; + expect(submit.disabled).toBe(true); + expect( + (screen.getByRole("button", { name: "Cancelar" }) as HTMLButtonElement) + .disabled, + ).toBe(true); + fireEvent.click(submit); + fireEvent.submit(submit.closest("form")!); + expect(createPendingAppointment).toHaveBeenCalledOnce(); + expect(window.open).not.toHaveBeenCalled(); + expect(screen.queryByRole("status")).toBeNull(); + await act(async () => + resolve({ ...appointment, id: "appointment-delayed" }), + ); + await waitFor(() => expect(window.open).toHaveBeenCalledOnce()); }); - it("redirects when an active process exists without an appointment", async () => { - vi.mocked(createPlatformAppointment).mockRejectedValue({ + it.each([ + { response: { status: 409 }, friendlyMessage: "Conflito genérico" }, + { response: { status: 409, - data: { error: { code: "ACTIVE_PROCESS_EXISTS" } }, + data: { + error: { + code: "EMAIL_FLOW_UNAVAILABLE", + message: "Conflito genérico", + }, + }, }, - }); - renderPage(); + }, + { + response: { + status: 409, + data: { + error: { + code: "ACTIVE_PROCESS_EXISTS", + message: "Conflito genérico", + }, + }, + }, + }, + { + response: { + status: 409, + data: { + code: "ACTIVE_PROCESS_EXISTS", + existing_request: existingRequest, + }, + }, + friendlyMessage: "Conflito genérico", + }, + { + response: { + status: 409, + data: { + error: { + code: "ACTIVE_PROCESS_EXISTS", + message: "Conflito genérico", + details: { existing_request: { process_id: "process-1" } }, + }, + }, + }, + }, + ])( + "keeps a generic or malformed 409 as an inline error (%#)", + async (error) => { + vi.mocked(createPendingAppointment).mockRejectedValue(error); + render(page()); + await chooseDateTime(); + expect(await screen.findByText("Conflito genérico")).toBeTruthy(); + expect(screen.getByRole("dialog")).toBeTruthy(); + expect(screen.queryByRole("status")).toBeNull(); + expect(window.open).not.toHaveBeenCalled(); + expect(checkExistingAppointment).toHaveBeenCalledOnce(); + }, + ); - fireEvent.click( - await screen.findByRole("button", { name: "Escolher data e hora" }), + it("does not open email after a creation failure", async () => { + vi.mocked(createPendingAppointment).mockRejectedValue( + new Error("Falha de rede"), ); - fireEvent.change(screen.getByLabelText("Data e hora"), { - target: { value: "2099-09-20T14:30" }, - }); - fireEvent.click( - screen.getByRole("button", { name: "Confirmar agendamento" }), + render(page()); + await chooseDateTime(); + expect(await screen.findByText("Falha de rede")).toBeTruthy(); + expect(window.open).not.toHaveBeenCalled(); + expect(screen.queryByRole("status")).toBeNull(); + }); + + it("recovers the strict owned duplicate snapshot without refetching or automatic opening", async () => { + vi.mocked(createPendingAppointment).mockRejectedValue( + duplicate(existingRequest), ); + render(page()); + await chooseDateTime(); + expect( + await screen.findByRole("heading", { + name: "Solicitação de reunião registrada", + }), + ).toBeTruthy(); + expect(screen.getByRole("link", { name: "Abrir no Gmail" })).toBeTruthy(); + expect( + screen + .getByRole("link", { name: "Acompanhar processo" }) + .getAttribute("href"), + ).toBe("/customer/processes"); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(window.open).not.toHaveBeenCalled(); + expect(checkExistingAppointment).toHaveBeenCalledOnce(); + expect( + sessionStorage.getItem("email-request-opened:appointment-recovered"), + ).toBeNull(); + }); - expect(await screen.findByText("Meus processos")).toBeTruthy(); + it("recovers the same email panel after a reload without automatic opening", async () => { + const view = render(page()); + await chooseDateTime(); + await waitFor(() => expect(window.open).toHaveBeenCalledOnce()); + view.unmount(); + vi.mocked(checkExistingAppointment).mockResolvedValue({ + ...existingRequest, + exists: true, + appointment_id: appointment.id, + appointment_status: "PENDING", + }); + render(page()); + expect( + await screen.findByRole( + "link", + { name: "Abrir aplicativo de e-mail" }, + { timeout: 2000 }, + ), + ).toBeTruthy(); + expect( + screen + .getByRole("link", { name: "Acompanhar processo" }) + .getAttribute("href"), + ).toBe("/customer/processes"); + await new Promise((resolve) => setTimeout(resolve, 30)); + expect(window.open).toHaveBeenCalledOnce(); + expect( + screen.queryByRole("button", { name: "Solicitar reunião" }), + ).toBeNull(); }); - it("does not open email when an active process already exists", async () => { - const openSpy = vi.spyOn(window, "open").mockImplementation(() => null); - vi.mocked(createPendingAppointment).mockRejectedValue({ - response: { - status: 409, - data: { error: { code: "ACTIVE_PROCESS_EXISTS" } }, - }, + it("recovers an own pending request on the initial visit even without a session marker", async () => { + vi.mocked(checkExistingAppointment).mockResolvedValue({ + ...existingRequest, + exists: true, + appointment_id: "appointment-own-initial", + appointment_status: "PENDING", }); - renderPage(); + render(page()); + expect( + await screen.findByRole( + "link", + { name: "Abrir no Gmail" }, + { timeout: 2000 }, + ), + ).toBeTruthy(); + expect(window.open).not.toHaveBeenCalled(); + expect(document.activeElement).not.toBe( + screen.getByRole("heading", { + name: "Solicitação de reunião registrada", + }), + ); + }); + + it.each([ + { + ...existingRequest, + appointment_id: null, + appointment_status: null, + scheduling_method: null, + appointment_datetime: null, + }, + { ...existingRequest, scheduling_method: "CALENDLY" as const }, + { ...existingRequest, appointment_status: "SCHEDULED" as const }, + { ...existingRequest, appointment_datetime: null }, + { ...existingRequest, appointment_datetime: "invalid" }, + ])( + "guides other owned active process snapshots without offering email composition (%#)", + async (snapshot) => { + vi.mocked(createPendingAppointment).mockRejectedValue( + duplicate(snapshot), + ); + render(page()); + await chooseDateTime(); + expect( + await screen.findByRole("link", { name: "Acompanhar processo" }), + ).toBeTruthy(); + expect(screen.queryByRole("link", { name: "Abrir no Gmail" })).toBeNull(); + expect(window.open).not.toHaveBeenCalled(); + expect(screen.queryByRole("dialog")).toBeNull(); + }, + ); + + it.each([ + { + appointment_status: "PENDING" as const, + scheduling_method: "CALENDLY" as const, + message: "Aguardando confirmação do especialista", + }, + { + appointment_status: "SCHEDULED" as const, + scheduling_method: "EMAIL" as const, + message: "Agendamento já realizado", + }, + ])( + "preserves $appointment_status/$scheduling_method existing appointment messaging", + async ({ appointment_status, scheduling_method, message }) => { + vi.mocked(checkExistingAppointment).mockResolvedValue({ + ...existingRequest, + exists: true, + appointment_id: "existing-other", + appointment_status, + scheduling_method, + }); + render(page()); + expect( + await screen.findByText(message, {}, { timeout: 2000 }), + ).toBeTruthy(); + expect(screen.queryByRole("link", { name: "Abrir no Gmail" })).toBeNull(); + expect( + screen.queryByRole("button", { name: "Solicitar reunião" }), + ).toBeNull(); + }, + ); + it("blocks creation when the own-request check fails", async () => { + vi.mocked(checkExistingAppointment).mockRejectedValue( + new Error("check unavailable"), + ); + render(page()); + expect( + await screen.findByText( + /Não foi possível validar seus agendamentos agora/, + {}, + { timeout: 2000 }, + ), + ).toBeTruthy(); + expect( + screen.queryByRole("button", { name: "Solicitar reunião" }), + ).toBeNull(); + }); + + it("ignores a late created request after the authenticated customer changes", async () => { + let resolve!: (value: PendingAppointmentCreated) => void; + vi.mocked(createPendingAppointment).mockReturnValue( + new Promise((done) => { + resolve = done; + }), + ); + const view = render(page()); + await chooseDateTime(); + authState.user = { ...authState.user, id: "customer-2", name: "Outro" }; + view.rerender(page()); + await act(async () => + resolve({ ...appointment, id: "appointment-old-customer" }), + ); + expect( + await screen.findByRole( + "button", + { name: "Solicitar reunião" }, + { timeout: 2000 }, + ), + ).toBeTruthy(); + expect(screen.queryByRole("link", { name: "Abrir no Gmail" })).toBeNull(); + expect(window.open).not.toHaveBeenCalled(); + expect(screen.queryByRole("dialog")).toBeNull(); + }); + + it("ignores a late created request after the authenticated role changes", async () => { + let resolve!: (value: PendingAppointmentCreated) => void; + vi.mocked(createPendingAppointment).mockReturnValue( + new Promise((done) => { + resolve = done; + }), + ); + const view = render(page()); + await chooseDateTime(); + authState.user = { ...authState.user, role: "SPECIALIST" }; + view.rerender(page()); + await act(async () => + resolve({ ...appointment, id: "appointment-old-role" }), + ); + expect( + screen.getByText(/Apenas clientes podem agendar reuniões/), + ).toBeTruthy(); + expect(screen.queryByRole("link", { name: "Abrir no Gmail" })).toBeNull(); + expect(window.open).not.toHaveBeenCalled(); + }); + + it("ignores a late created request after the selected product changes", async () => { + let resolve!: (value: PendingAppointmentCreated) => void; + vi.mocked(createPendingAppointment).mockReturnValue( + new Promise((done) => { + resolve = done; + }), + ); + render(page()); + await chooseDateTime(); + vi.mocked(getCarById).mockResolvedValue({ + ...product, + id: "car-2", + modelo: "Outro Modelo", + }); fireEvent.click( - await screen.findByRole("button", { name: "Enviar e-mail" }), + screen.getByRole("button", { name: "Ver outro produto", hidden: true }), ); + await act(async () => + resolve({ ...appointment, id: "appointment-old-product" }), + ); + expect( + await screen.findByRole("heading", { name: "Marca Outro Modelo" }), + ).toBeTruthy(); + expect( + await screen.findByRole( + "button", + { name: "Solicitar reunião" }, + { timeout: 2000 }, + ), + ).toBeTruthy(); + expect(screen.queryByRole("link", { name: "Abrir no Gmail" })).toBeNull(); + expect(window.open).not.toHaveBeenCalled(); + expect(screen.queryByRole("dialog")).toBeNull(); + }); - expect(await screen.findByText("Meus processos")).toBeTruthy(); - expect(openSpy).not.toHaveBeenCalled(); + it("does not open an email after unmount during creation", async () => { + let resolve!: (value: PendingAppointmentCreated) => void; + vi.mocked(createPendingAppointment).mockReturnValue( + new Promise((done) => { + resolve = done; + }), + ); + const view = render(page()); + await chooseDateTime(); + view.unmount(); + await act(async () => + resolve({ ...appointment, id: "appointment-unmounted" }), + ); + expect(window.open).not.toHaveBeenCalled(); }); }); diff --git a/frontend/src/pages/catalog/ProductPage.tsx b/frontend/src/pages/catalog/ProductPage.tsx index 4de1829..964ac7e 100644 --- a/frontend/src/pages/catalog/ProductPage.tsx +++ b/frontend/src/pages/catalog/ProductPage.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { ArrowLeft, CheckCircle, ExternalLink, Loader2 } from "lucide-react"; import { PopupModal } from "react-calendly"; @@ -8,14 +8,22 @@ import { getAircraftById, type RawAircraft, } from "../../services/aircrafts.service"; -import { getPublicSpecialistById } from "../../services/specialists.service"; import { - checkExistingAppointment, + getPublicSpecialistById, + type PublicSpecialistProfile, +} from "../../services/specialists.service"; +import { createPendingAppointment, - createPlatformAppointment, - type Appointment, + getActiveProcessSnapshot, + type ActiveProcessSnapshot, + type ProductPendingAppointmentInput, + type PendingAppointmentCreated, } from "../../services/appointments.service"; import { getProcessesByClient } from "../../services/processes.service"; +import { + browserTimeZone, + parseAppointmentIso, +} from "../../lib/appointment-datetime"; import ProductDetails from "../../components/product/ProductDetails"; import Loading from "../../components/ui/Loading"; import Button from "../../components/ui/button"; @@ -26,65 +34,114 @@ import { PageHeader } from "../../components/patterns/PageHeader"; import StartProcessForClientModal from "../../components/processes/StartProcessForClientModal"; import AppointmentDateTimeModal from "../../components/appointments/AppointmentDateTimeModal"; import NoCalendlySchedulingActions from "../../components/appointments/NoCalendlySchedulingActions"; +import EmailSchedulingSuccess from "../../components/appointments/EmailSchedulingSuccess"; import { useAuth } from "../../store/authStateManager"; import { useCheckAppointment } from "../../hooks/useCheckAppointment"; import { useCalendlyScheduling } from "../../hooks/useCalendlyScheduling"; import type { Product } from "../../types/types"; -interface Specialist { - id: string; - name: string; - surname: string; - email: string; - calendly_url: string | null; - speciality: string | null; +function appointmentSnapshot( + appointment: PendingAppointmentCreated, +): ActiveProcessSnapshot { + return { + process_id: appointment.process_id, + appointment_id: appointment.id, + appointment_status: appointment.status, + scheduling_method: appointment.scheduling_method ?? null, + appointment_datetime: appointment.appointment_datetime ?? null, + }; +} + +function validAppointmentDate(value: string | null): Date | null { + try { + return value ? parseAppointmentIso(value) : null; + } catch { + return null; + } } -const isActiveProcessConflict = (error: any): boolean => - error?.response?.status === 409 && - error?.response?.data?.error?.code === "ACTIVE_PROCESS_EXISTS"; +function isPendingEmailRequest( + request: ActiveProcessSnapshot | null, +): request is ActiveProcessSnapshot & { + appointment_id: string; + appointment_datetime: string; +} { + return ( + request?.appointment_status === "PENDING" && + request.scheduling_method === "EMAIL" && + Boolean(request.appointment_id) && + Boolean(validAppointmentDate(request.appointment_datetime)) + ); +} -/** - * ProductPage - * - * Página de detalhes do produto. - * Rota: /catalog/:productType/:id - * - * Exibe: - * - Informações completas do produto (reutiliza ProductDetails) - * - Seção para agendar reunião com especialista (se houver) - * - Com calendly_url: link para Calendly + confirmação - * - Sem calendly_url: botão para enviar e-mail + confirmação - * - Sem especialista: seção oculta - * - * Lógica de duplas: - * - Verifica se existe agendamento SCHEDULED entre cliente + especialista + produto - * - Se existe: mostra mensagem "Você já possui um agendamento marcado" - * - Se não existe: mostra botões normalmente (Calendly ou Email) - */ +function creationErrorMessage(error: unknown): string { + const candidate = error as { + friendlyMessage?: string; + message?: string; + response?: { data?: { error?: { message?: string } } }; + } | null; + return ( + candidate?.friendlyMessage || + candidate?.response?.data?.error?.message || + candidate?.message || + "Não foi possível criar a solicitação. Tente novamente." + ); +} + +/** Orchestrates an owned request, using only the backend's Calendly capability. */ export default function ProductPage() { const { productType, id } = useParams(); const navigate = useNavigate(); const { user } = useAuth(); - const [product, setProduct] = useState(null); - const [specialist, setSpecialist] = useState(null); + const [specialist, setSpecialist] = useState( + null, + ); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [isCreatingPending, setIsCreatingPending] = useState(false); - const [lockedAppointment, setLockedAppointment] = - useState(null); + const [lockedRequest, setLockedRequest] = useState<{ + scopeKey: string; + snapshot: ActiveProcessSnapshot; + autoOpen: boolean; + } | null>(null); const [isStartProcessModalOpen, setIsStartProcessModalOpen] = useState(false); const [isDateTimeModalOpen, setIsDateTimeModalOpen] = useState(false); const [dateTimeError, setDateTimeError] = useState(null); - // Aviso de resultado da tentativa de criação do agendamento PENDING, antes - // de o popup do Calendly sequer abrir (conflito 409 / falha de rede). A - // partir do momento que o popup abre, quem governa o aviso é o hook - // (calendlySyncState / calendlySyncMessage). - const [creationNotice, setCreationNotice] = useState<{ - variant: "success" | "danger"; - message: string; - } | null>(null); + const [creationNotice, setCreationNotice] = useState(null); + const scopeKey = JSON.stringify([ + user?.id, + user?.role, + productType, + id, + product?.id, + specialist?.id, + ]); + const currentScopeRef = useRef(scopeKey); + currentScopeRef.current = scopeKey; + const mountedRef = useRef(false); + const creatingRef = useRef(null); + const requestProductType = productType?.toUpperCase() as + | "CAR" + | "BOAT" + | "AIRCRAFT" + | undefined; + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + }; + }, []); + + useEffect(() => { + creatingRef.current = null; + setIsCreatingPending(false); + setLockedRequest(null); + setIsDateTimeModalOpen(false); + setDateTimeError(null); + setCreationNotice(null); + }, [scopeKey]); const { isModalOpen: isCalendlyModalOpen, @@ -97,45 +154,38 @@ export default function ProductPage() { successRedirectMessage: "Solicitação de agendamento registrada com sucesso! Verifique seus processos.", onSynced: (syncStatus) => { - setLockedAppointment((prev) => - prev + setLockedRequest((previous) => + previous?.scopeKey === currentScopeRef.current && + previous.snapshot.appointment_id === syncStatus.appointment_id ? { - ...prev, - status: - syncStatus.status === "PENDING" ? prev.status : syncStatus.status, - appointment_datetime: - syncStatus.appointment_datetime ?? prev.appointment_datetime, - calendly_sync_status: syncStatus.calendly_sync_status, + ...previous, + snapshot: { + ...previous.snapshot, + appointment_status: syncStatus.status, + appointment_datetime: + syncStatus.appointment_datetime ?? + previous.snapshot.appointment_datetime, + }, } - : prev, + : previous, ); }, }); - // Hook para verificar agendamentos existentes - // APENAS dispara verificação após specialist ser carregado com sucesso const { existingAppointment, isLoading: isCheckingAppointment, error: checkAppointmentError, - } = useCheckAppointment( - user?.role === "CUSTOMER" && user?.id && specialist?.id ? user.id : undefined, - specialist?.id, - (productType?.toUpperCase() as "CAR" | "BOAT" | "AIRCRAFT") || undefined, - product?.id, - ); - - const currentAppointment = lockedAppointment ?? existingAppointment; + } = useCheckAppointment(specialist?.id, requestProductType, product?.id); + const localRequest = + lockedRequest?.scopeKey === scopeKey ? lockedRequest : null; + const currentRequest = + localRequest?.snapshot ?? + (existingAppointment?.exists ? existingAppointment : null); + const emailRequest = isPendingEmailRequest(currentRequest) + ? currentRequest + : null; - const redirectToProcesses = (message: string, delayMs: number = 900) => { - setTimeout(() => { - navigate("/customer/processes", { - state: { message }, - }); - }, delayMs); - }; - - // Mapear productType para categoria do catálogo const categoryMap: Record = { car: "cars", boat: "boats", @@ -143,17 +193,19 @@ export default function ProductPage() { }; useEffect(() => { + let active = true; async function loadProduct() { + setLoading(true); + setError(null); + setProduct(null); + setSpecialist(null); if (!productType || !id) { setError("Produto não encontrado"); setLoading(false); return; } - - setLoading(true); try { let rawProduct: RawCar | RawBoat | RawAircraft | null = null; - switch (productType) { case "car": rawProduct = await getCarById(id); @@ -167,32 +219,24 @@ export default function ProductPage() { default: throw new Error("Tipo de produto desconhecido"); } - - if (!rawProduct) { - throw new Error("Produto não encontrado"); - } - - // Obter descrição do produto (nome do campo varia por tipo) + if (!active) return; + if (!rawProduct) throw new Error("Produto não encontrado"); let descricao: string | undefined; - if ("descricao" in rawProduct) { + if ("descricao" in rawProduct) descricao = rawProduct.descricao as string | undefined; - } else if ("descricao_completa" in rawProduct) { + else if ("descricao_completa" in rawProduct) descricao = rawProduct.descricao_completa as string | undefined; - } - - // Converter para Product const formattedProduct: Product = { id: rawProduct.id, marca: rawProduct.marca, modelo: rawProduct.modelo, valor: rawProduct.valor, currency: rawProduct.currency, - descricao: descricao, + descricao, ano: rawProduct.ano, estado: rawProduct.estado, specialist_id: rawProduct.specialist_id, images: rawProduct.images, - // Campos específicos por tipo ...("cor" in rawProduct && { cor: rawProduct.cor }), ...("km" in rawProduct && { km: rawProduct.km }), ...("cambio" in rawProduct && { cambio: rawProduct.cambio }), @@ -216,278 +260,167 @@ export default function ProductPage() { tipo_aeronave: rawProduct.tipo_aeronave, }), }; - console.log(formattedProduct); - setProduct(formattedProduct); - - // Buscar dados do especialista se houver if (rawProduct.specialist_id) { try { - const specialistData = await getPublicSpecialistById( + const profile = await getPublicSpecialistById( rawProduct.specialist_id, ); - setSpecialist({ - id: specialistData.id, - name: specialistData.name, - surname: specialistData.surname, - email: specialistData.email, - calendly_url: specialistData.calendly_url, - speciality: specialistData.speciality, - }); - } catch (err) { - console.warn( - "Não foi possível carregar dados do especialista:", - err, - ); + if (active) setSpecialist(profile); + } catch (error) { + if (active) + console.warn( + "Não foi possível carregar dados do especialista:", + error, + ); } } - } catch (err) { - console.error("Erro ao carregar produto:", err); - setError("Erro ao carregar produto"); + } catch (error) { + if (active) { + console.error("Erro ao carregar produto:", error); + setError("Erro ao carregar produto"); + } } finally { - setLoading(false); + if (active) setLoading(false); } } - - loadProduct(); + void loadProduct(); + return () => { + active = false; + }; }, [productType, id]); - /** - * Cria agendamento PENDING e abre Calendly em modal - */ - const handleCalendlyClick = async () => { - if (!specialist?.calendly_url || !user || !product) return; - - // Garantir que a URL tenha protocolo https:// - let formattedUrl = specialist.calendly_url.trim(); - if ( - !formattedUrl.startsWith("http://") && - !formattedUrl.startsWith("https://") - ) { - formattedUrl = `https://${formattedUrl}`; - } - + const submitRequest = async ( + input: ProductPendingAppointmentInput, + calendlyUrl?: string, + ) => { + if (creatingRef.current) return; + const request = {}; + const submittedScope = scopeKey; + const isCurrent = () => + mountedRef.current && + currentScopeRef.current === submittedScope && + creatingRef.current === request; + creatingRef.current = request; setIsCreatingPending(true); + setDateTimeError(null); setCreationNotice(null); try { - const clientProcesses = await getProcessesByClient(user.id, 1, 100); - const activeProcess = clientProcesses.find( - (p) => - String(p.product_id) === String(product.id) && - p.product_type === productType?.toUpperCase() && - p.status !== "COMPLETED" && - p.status !== "REJECTED", - ); - if (activeProcess) { - const confirmed = window.confirm( - "Você já possui um processo de negociação ativo para este produto.\n\nDeseja abrir um novo processo independente? Isso não cancelará o processo existente.", - ); - if (!confirmed) { - setIsCreatingPending(false); - return; + // Preserve the existing Calendly preflight before opening its popup. + if (input.scheduling_method === "CALENDLY") { + const processes = await getProcessesByClient(input.client_id, 1, 100); + if (!isCurrent()) return; + if ( + processes.some( + (process) => + String(process.product_id) === input.product_id && + process.product_type === input.product_type && + process.status !== "COMPLETED" && + process.status !== "REJECTED", + ) + ) { + if ( + !window.confirm( + "Você já possui um processo de negociação ativo para este produto.\n\nDeseja abrir um novo processo independente? Isso não cancelará o processo existente.", + ) + ) + return; } } - - const pendingAppointment = await createPendingAppointment({ - client_id: user.id, - specialist_id: specialist.id, - product_type: - (productType?.toUpperCase() as "CAR" | "BOAT" | "AIRCRAFT") || "CAR", - product_id: product.id, - scheduling_method: "CALENDLY", - notes: "Cliente abriu agendamento via popup da plataforma", + const appointment = await createPendingAppointment(input); + if (!isCurrent()) return; + setLockedRequest({ + scopeKey: submittedScope, + snapshot: appointmentSnapshot(appointment), + autoOpen: input.scheduling_method === "EMAIL", }); - - setLockedAppointment(pendingAppointment); - openPopup(pendingAppointment.id, formattedUrl); - } catch (err: any) { - if (err.response?.status === 409) { - try { - if (user?.id && specialist?.id && product?.id && productType) { - const existing = await checkExistingAppointment( - user.id, - specialist.id, - productType.toUpperCase() as "CAR" | "BOAT" | "AIRCRAFT", - product.id, - ); - if (existing) { - setLockedAppointment(existing); - } - } - } catch (checkError) { - console.error("Erro ao recuperar agendamento existente:", checkError); - } - setCreationNotice({ - variant: "success", - message: "Você já possui uma solicitação de agendamento para este produto.", + setIsDateTimeModalOpen(false); + if (input.scheduling_method === "CALENDLY" && calendlyUrl) + openPopup(appointment.id, calendlyUrl); + } catch (error) { + if (!isCurrent()) return; + const existing = getActiveProcessSnapshot(error); + if (existing) { + setLockedRequest({ + scopeKey: submittedScope, + snapshot: existing, + autoOpen: false, }); - redirectToProcesses( - "Você já possui uma solicitação de agendamento para este produto.", - ); + setIsDateTimeModalOpen(false); + } else if (input.scheduling_method === "EMAIL") { + setDateTimeError(creationErrorMessage(error)); } else { - console.error("Erro ao criar agendamento pendente:", err); - setCreationNotice({ - variant: "danger", - message: "Erro ao criar solicitação de agendamento.", - }); + setCreationNotice(creationErrorMessage(error)); } } finally { - setIsCreatingPending(false); + if (isCurrent()) { + creatingRef.current = null; + setIsCreatingPending(false); + } } }; - const handleEmailClick = async () => { - if (!specialist?.email || !user || !product) return; - - setIsCreatingPending(true); - try { - // Criar agendamento PENDING - const pendingAppointment = await createPendingAppointment({ - client_id: user.id, - specialist_id: specialist.id, - product_type: - (productType?.toUpperCase() as "CAR" | "BOAT" | "AIRCRAFT") || "CAR", - product_id: product.id, - scheduling_method: "EMAIL", - notes: "Cliente entrou em contato por email", - }); - - setLockedAppointment(pendingAppointment); - - // Abrir email - const subject = encodeURIComponent( - `Interesse em ${product?.marca} ${product?.modelo}`, - ); - const body = encodeURIComponent( - `Olá ${specialist.name},\n\nTenho interesse no ${product?.marca} ${product?.modelo} e gostaria de agendar uma reunião.\n\nAtenciosamente.`, - ); - window.open( - `mailto:${specialist.email}?subject=${subject}&body=${body}`, - "_self", + const handleCalendlyClick = async () => { + if ( + !specialist?.calendly_scheduling_available || + user?.role !== "CUSTOMER" || + !product || + !requestProductType || + currentRequest || + isCheckingAppointment || + checkAppointmentError || + existingAppointment?.exists !== false + ) + return; + if (!specialist.calendly_url) { + setCreationNotice( + "Não foi possível abrir a agenda do especialista. Atualize a página e tente novamente.", ); - } catch (err: any) { - // Se já existe agendamento, apenas abrir o email - if (err.response?.status === 409) { - if (isActiveProcessConflict(err)) { - navigate("/customer/processes", { - state: { - message: - "Você já possui um processo ativo para este produto. Acompanhe o processo existente.", - }, - }); - return; - } - - try { - if (user?.id && specialist?.id && product?.id && productType) { - const existing = await checkExistingAppointment( - user.id, - specialist.id, - productType.toUpperCase() as "CAR" | "BOAT" | "AIRCRAFT", - product.id, - ); - if (existing) { - setLockedAppointment(existing); - } - } - } catch (checkError) { - console.error("Erro ao recuperar agendamento existente:", checkError); - } - - const subject = encodeURIComponent( - `Interesse em ${product?.marca} ${product?.modelo}`, - ); - const body = encodeURIComponent( - `Olá ${specialist.name},\n\nTenho interesse no ${product?.marca} ${product?.modelo} e gostaria de agendar uma reunião.\n\nAtenciosamente.`, - ); - window.open( - `mailto:${specialist.email}?subject=${subject}&body=${body}`, - "_self", - ); - } else { - console.error("Erro ao criar agendamento pendente:", err); - alert("Erro ao criar agendamento. Tente novamente."); - } - } finally { - setIsCreatingPending(false); + return; } - }; - - const handlePlatformScheduling = async (appointmentDatetime: string) => { - if (!specialist || !user || !product || !productType) return; - - setIsCreatingPending(true); - setDateTimeError(null); - try { - const scheduledAppointment = await createPlatformAppointment({ + await submitRequest( + { client_id: user.id, specialist_id: specialist.id, - product_type: productType.toUpperCase() as "CAR" | "BOAT" | "AIRCRAFT", + product_type: requestProductType, product_id: product.id, - appointment_datetime: appointmentDatetime, - notes: "Cliente escolheu o horário pela plataforma", - }); - - setLockedAppointment(scheduledAppointment); - setIsDateTimeModalOpen(false); - navigate("/customer/processes", { - state: { - message: "Reunião agendada. Você já pode acompanhar o processo.", - }, - }); - } catch (err: any) { - if (err.response?.status === 409) { - if (isActiveProcessConflict(err)) { - setIsDateTimeModalOpen(false); - navigate("/customer/processes", { - state: { - message: - "Você já possui um processo ativo para este produto. Acompanhe o processo existente.", - }, - }); - return; - } - - const existing = await checkExistingAppointment( - user.id, - specialist.id, - productType.toUpperCase() as "CAR" | "BOAT" | "AIRCRAFT", - product.id, - ); - - if (existing) { - setLockedAppointment(existing); - setIsDateTimeModalOpen(false); - navigate("/customer/processes", { - state: { - message: - "Você já possui uma solicitação para este produto. Acompanhe o processo existente.", - }, - }); - return; - } - } - - setDateTimeError( - err.friendlyMessage || - err.response?.data?.error?.message || - "Não foi possível confirmar esse horário. Escolha outro e tente novamente.", - ); - } finally { - setIsCreatingPending(false); - } + scheduling_method: "CALENDLY", + notes: "Cliente abriu agendamento via popup da plataforma", + }, + specialist.calendly_url.trim(), + ); }; - const handleBackToCatalog = () => { - const category = categoryMap[productType || ""] || "cars"; - navigate(`/catalog/${category}`); + const handleEmailScheduling = async (appointmentDatetime: string) => { + if ( + !specialist || + specialist.calendly_scheduling_available || + user?.role !== "CUSTOMER" || + !product || + !requestProductType || + currentRequest || + isCheckingAppointment || + checkAppointmentError || + existingAppointment?.exists !== false + ) + return; + await submitRequest({ + client_id: user.id, + specialist_id: specialist.id, + product_type: requestProductType, + product_id: product.id, + scheduling_method: "EMAIL", + appointment_datetime: appointmentDatetime, + notes: "Cliente propôs uma reunião por e-mail", + }); }; - if (loading) { - return ; - } + const handleBackToCatalog = () => + navigate(`/catalog/${categoryMap[productType || ""] || "cars"}`); - if (error || !product) { + if (loading) + return ; + if (error || !product) return (

@@ -499,29 +432,20 @@ export default function ProductPage() {

); - } return (
- - {/* Detalhes do produto */} - - {/* Seção de agendamento - só aparece se houver especialista */} {specialist && (

Agendar Reunião

- - {/* Informações do especialista */}
-

- Especialista responsável -

+

Especialista responsável

{specialist.name} {specialist.surname}

@@ -531,10 +455,23 @@ export default function ProductPage() {

)}
- - {/* Verifica se existe agendamento e mostra mensagem se houver */} + {user?.role === "CUSTOMER" && + (creationNotice || + (calendlySyncState !== "idle" && calendlySyncMessage)) && ( + + {creationNotice || calendlySyncMessage} + + )} {!user ? ( - /* Usuário não logado - mostrar botão para cadastro */

@@ -542,8 +479,8 @@ export default function ProductPage() { especialista, você precisa criar uma conta ou fazer login.

- -

Já tem uma conta?{" "}

- ) : user.role === "CONSULTANT" ? ( - /* Consultor - não agenda em nome próprio; inicia processo para um cliente */ + ) : user.role === "CONSULTANT" || user.role === "OFFICE" ? (

- Modo Consultor: Você não pode agendar uma reunião em seu próprio nome. Selecione qual cliente terá o processo criado para este produto. + + {user.role === "OFFICE" + ? "Modo Escritório:" + : "Modo Consultor:"} + {" "} + Você não pode agendar uma reunião em seu próprio nome. + Selecione qual cliente{" "} + {user.role === "OFFICE" ? "do escritório " : ""}terá o + processo criado para este produto.

- - -
- ) : user.role === "OFFICE" ? ( - /* Gerente de escritório — inicia processo para cliente da empresa */ -
- -

- Modo Escritório: Você não pode agendar uma reunião em seu próprio nome. Selecione qual cliente do escritório terá o processo criado para este produto. -

-
-
) : user.role !== "CUSTOMER" ? ( - /* SPECIALIST / ADMIN — apenas clientes podem agendar */

Apenas clientes podem agendar reuniões a partir do catálogo.

- ) : isCheckingAppointment ? ( - -

Verificando agendamentos...

-
- ) : checkAppointmentError ? ( - -

- Não foi possível validar seus agendamentos agora. Para evitar - duplicidade, atualize a página e tente novamente em instantes. -

-
- ) : currentAppointment ? ( + ) : emailRequest ? ( + + ) : currentRequest ? (
-

- {currentAppointment.status === "PENDING" - ? "Aguardando confirmação do especialista" - : "Agendamento já realizado"} -

-

- {currentAppointment.status === "PENDING" - ? "Você já demonstrou interesse neste produto. O especialista irá confirmar seu agendamento em breve." - : "Você já possui um agendamento marcado com este especialista para este produto."} - {currentAppointment.appointment_datetime && ( - <> -
- Data:{" "} - {new Date( - currentAppointment.appointment_datetime, - ).toLocaleDateString("pt-BR", { - weekday: "long", - year: "numeric", - month: "long", - day: "numeric", - hour: "2-digit", - minute: "2-digit", - })} - - )} -

+

+ {currentRequest.appointment_status === "PENDING" + ? "Aguardando confirmação do especialista" + : currentRequest.appointment_status === "SCHEDULED" + ? "Agendamento já realizado" + : "Você já possui um processo ativo para este produto"} +

+

+ {currentRequest.appointment_status === "PENDING" + ? "Você já demonstrou interesse neste produto. Acompanhe sua solicitação em Meus Processos." + : currentRequest.appointment_status === "SCHEDULED" + ? "Você já possui um agendamento marcado com este especialista para este produto." + : "Acompanhe o processo existente em Meus Processos."} + {validAppointmentDate( + currentRequest.appointment_datetime, + ) && ( + <> +
+ Data:{" "} + {validAppointmentDate( + currentRequest.appointment_datetime, + )?.toLocaleString("pt-BR", { + dateStyle: "long", + timeStyle: "short", + })} + + )} +

- {currentAppointment.status === "PENDING" && - currentAppointment.scheduling_method === "EMAIL" && ( - <> - undefined} - onChooseDateTime={() => undefined} - /> - - - )} + + Acompanhar processo +
- ) : specialist.calendly_url?.trim() ? ( - /* Com Calendly URL - Botão para acessar e criar PENDING */ + ) : checkAppointmentError ? ( + +

+ Não foi possível validar seus agendamentos agora. Para evitar + duplicidade, atualize a página e tente novamente em instantes. +

+
+ ) : isCheckingAppointment || !existingAppointment ? ( + +

Verificando agendamentos...

+
+ ) : specialist.calendly_scheduling_available ? (

- Dica: Clique no botão abaixo para agendar - uma reunião no popup. Assim que concluir, a plataforma tenta + Dica: Clique no botão abaixo para agendar uma + reunião no popup. Assim que concluir, a plataforma tenta sincronizar automaticamente seu agendamento.

- - {creationNotice ? ( - - {creationNotice.message} - - ) : ( - calendlySyncState !== "idle" && - calendlySyncMessage && ( - - {calendlySyncMessage} - - ) - )} - + + ; + } + render(); + const trigger = screen.getByRole("button", { name: "Propor horário" }); + trigger.focus(); + fireEvent.click(trigger); + fireEvent.change(screen.getByLabelText("Data e hora"), { target: { value: "2099-09-20T14:30" } }); + fireEvent.click(screen.getByRole("button", { name: "Cancelar" })); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + await waitFor(() => expect(document.activeElement).toBe(trigger)); + }); }); diff --git a/frontend/src/components/appointments/AppointmentDateTimeModal.tsx b/frontend/src/components/appointments/AppointmentDateTimeModal.tsx index 6911aea..9f59fac 100644 --- a/frontend/src/components/appointments/AppointmentDateTimeModal.tsx +++ b/frontend/src/components/appointments/AppointmentDateTimeModal.tsx @@ -1,7 +1,9 @@ -import { useEffect, useState, type FormEvent } from "react"; +import { useEffect, useId, useLayoutEffect, useRef, useState, type FormEvent, type RefObject } from "react"; import { browserTimeZone, + isoToLocalDateTimeInput, localDateTimeToIso, + parseAppointmentIso, } from "../../lib/appointment-datetime"; import { Alert } from "../ui/alert"; import Button from "../ui/button"; @@ -13,6 +15,8 @@ interface AppointmentDateTimeModalProps { description: string; submitLabel: string; definitiveWarning?: string; + initialValue?: string; + returnFocusRef?: RefObject; busy?: boolean; serverError?: string | null; onClearServerError?(): void; @@ -39,35 +43,69 @@ export default function AppointmentDateTimeModal({ description, submitLabel, definitiveWarning, + initialValue, + returnFocusRef, busy = false, serverError, onClearServerError, onOpenChange, onSubmit, }: AppointmentDateTimeModalProps) { - const [localDateTime, setLocalDateTime] = useState(""); + let initialLocalValue = ""; + try { + if (initialValue) initialLocalValue = isoToLocalDateTimeInput(initialValue); + } catch { + // A legacy malformed proposal must still allow the specialist to choose a time. + } + const [localDateTime, setLocalDateTime] = useState(initialLocalValue); const [validationError, setValidationError] = useState(null); + const [submitting, setSubmitting] = useState(false); + const submittingRef = useRef(false); + const focusTarget = useRef(null); + const focusCaptured = useRef(false); + const latestOpen = useRef(open); + const fieldId = useId(); + const errorId = `${fieldId}-error`; + const timeZoneId = `${fieldId}-timezone`; + const isBusy = busy || submitting; + const errorMessage = validationError || serverError; - useEffect(() => { - if (!open) { - setLocalDateTime(""); - setValidationError(null); - } + useLayoutEffect(() => { + latestOpen.current = open; }, [open]); + useEffect(() => { + setLocalDateTime(open ? initialLocalValue : ""); + setValidationError(null); + }, [open, initialValue, initialLocalValue]); + const handleOpenChange = (nextOpen: boolean) => { - if (!busy) onOpenChange(nextOpen); + if (!isBusy) onOpenChange(nextOpen); }; const handleSubmit = async (event: FormEvent) => { event.preventDefault(); + if (busy || submittingRef.current) return; + submittingRef.current = true; + setSubmitting(true); try { - const appointmentDatetime = localDateTimeToIso(localDateTime); + let appointmentDatetime: string; + if (initialValue && initialLocalValue && localDateTime === initialLocalValue) { + if (parseAppointmentIso(initialValue).getTime() <= Date.now()) { + throw new Error("Selecione uma data e hora futuras"); + } + appointmentDatetime = initialValue; + } else { + appointmentDatetime = localDateTimeToIso(localDateTime); + } setValidationError(null); await onSubmit(appointmentDatetime); } catch (error) { setValidationError(submissionErrorMessage(error)); + } finally { + submittingRef.current = false; + setSubmitting(false); } }; @@ -76,7 +114,22 @@ export default function AppointmentDateTimeModal({ { + if (!focusCaptured.current) { + focusTarget.current = returnFocusRef?.current || + (document.activeElement instanceof HTMLElement ? document.activeElement : null); + focusCaptured.current = true; + } + }} + onCloseAutoFocus={(event) => { + event.preventDefault(); + if (latestOpen.current) return; + const target = returnFocusRef?.current || focusTarget.current; + if (target?.isConnected) target.focus(); + focusCaptured.current = false; + focusTarget.current = null; + }} className="max-w-md" >
@@ -86,22 +139,24 @@ export default function AppointmentDateTimeModal({ {definitiveWarning} )} - {(validationError || serverError) && ( - {validationError || serverError} + {errorMessage && ( + {errorMessage} )}
{ setLocalDateTime(event.target.value); setValidationError(null); @@ -109,7 +164,7 @@ export default function AppointmentDateTimeModal({ }} className="w-full rounded-lg border border-border px-3 py-2 text-ink focus:border-brand-primary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 disabled:cursor-not-allowed disabled:opacity-60" /> -

+

Fuso horário: {browserTimeZone()}

@@ -118,12 +173,12 @@ export default function AppointmentDateTimeModal({ -
diff --git a/frontend/src/components/processes/ProcessCard.test.tsx b/frontend/src/components/processes/ProcessCard.test.tsx index 1538d42..85bf47b 100644 --- a/frontend/src/components/processes/ProcessCard.test.tsx +++ b/frontend/src/components/processes/ProcessCard.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom -import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { MemoryRouter } from "react-router-dom"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import ProcessCard from "./ProcessCard"; @@ -12,6 +12,7 @@ import { getProcessWithActiveContract, } from "../../services/processes.service"; import { rescheduleAppointment } from "../../services/appointments.service"; +import { isoToLocalDateTimeInput } from "../../lib/appointment-datetime"; vi.mock("../../services/processes.service", () => ({ confirmAppointment: vi.fn(), @@ -81,13 +82,13 @@ describe("ProcessCard appointment time actions", () => { it("lets only the specialist define a missing email appointment time", () => { const { unmount } = renderCard(); expect( - screen.getByRole("button", { name: "Definir data e hora" }), + screen.getByRole("button", { name: "Alterar e confirmar" }), ).toBeTruthy(); unmount(); renderCard(baseProcess, { isClientView: true }); expect( - screen.queryByRole("button", { name: "Definir data e hora" }), + screen.queryByRole("button", { name: "Alterar e confirmar" }), ).toBeNull(); }); @@ -98,7 +99,7 @@ describe("ProcessCard appointment time actions", () => { }); expect( - screen.queryByRole("button", { name: "Definir data e hora" }), + screen.queryByRole("button", { name: "Alterar e confirmar" }), ).toBeNull(); expect(screen.getByText("Aguardando sincronização do Calendly")).toBeTruthy(); }); @@ -110,7 +111,7 @@ describe("ProcessCard appointment time actions", () => { }); expect( - screen.getByRole("button", { name: "Definir data e hora" }), + screen.getByRole("button", { name: "Alterar e confirmar" }), ).toBeTruthy(); expect( screen.queryByText("Aguardando sincronização do Calendly"), @@ -122,7 +123,7 @@ describe("ProcessCard appointment time actions", () => { renderCard(baseProcess, { onStatusUpdated }); fireEvent.click( - screen.getByRole("button", { name: "Definir data e hora" }), + screen.getByRole("button", { name: "Alterar e confirmar" }), ); fireEvent.change(screen.getByLabelText("Data e hora"), { target: { value: "2099-09-20T14:30" }, @@ -196,7 +197,7 @@ describe("ProcessCard appointment time actions", () => { renderCard(baseProcess, { onStatusUpdated }); fireEvent.click( - screen.getByRole("button", { name: "Definir data e hora" }), + screen.getByRole("button", { name: "Alterar e confirmar" }), ); fireEvent.change(screen.getByLabelText("Data e hora"), { target: { value: "2099-09-20T14:30" }, @@ -242,4 +243,152 @@ describe("ProcessCard appointment time actions", () => { ).toBeTruthy(); expect(getMeetingByProcess).toHaveBeenCalledTimes(2); }); + + it("confirms the exact stored ISO without consuming rescheduling", async () => { + const appointment_datetime = "2099-09-20T14:30:45.123-03:00"; + const onStatusUpdated = vi.fn(); + renderCard({ ...baseProcess, appointment_datetime }, { onStatusUpdated }); + expect(screen.getByRole("button", { name: "Alterar e confirmar" })).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Confirmar horário" })); + await waitFor(() => expect(confirmAppointment).toHaveBeenCalledWith(baseProcess.id, appointment_datetime)); + expect(onStatusUpdated).toHaveBeenCalledOnce(); + expect(rescheduleAppointment).not.toHaveBeenCalled(); + expect(screen.queryByRole("dialog")).toBeNull(); + }); + + it("prefills change-and-confirm and calls the canonical endpoint", async () => { + const appointment_datetime = "2099-09-20T14:30:45.123-03:00"; + renderCard({ ...baseProcess, appointment_datetime }); + fireEvent.click(screen.getByRole("button", { name: "Alterar e confirmar" })); + expect((screen.getByLabelText("Data e hora") as HTMLInputElement).value).toBe(isoToLocalDateTimeInput(appointment_datetime)); + expect(screen.queryByText(/única alteração permitida/i)).toBeNull(); + fireEvent.change(screen.getByLabelText("Data e hora"), { target: { value: "2099-09-21T16:00" } }); + fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Confirmar horário" })); + await waitFor(() => expect(confirmAppointment).toHaveBeenCalledWith(baseProcess.id, new Date("2099-09-21T16:00").toISOString())); + expect(rescheduleAppointment).not.toHaveBeenCalled(); + }); + + it("opens change-and-confirm after a direct 409 and keeps conflict inline", async () => { + const appointment_datetime = "2099-09-20T17:30:00.000Z"; + vi.mocked(confirmAppointment).mockRejectedValue({ response: { status: 409, data: { error: { message: "Horário ocupado. Escolha outro horário." } } } }); + const onStatusUpdated = vi.fn(); + const alert = vi.spyOn(window, "alert").mockImplementation(() => {}); + renderCard({ ...baseProcess, appointment_datetime }, { onStatusUpdated }); + fireEvent.click(screen.getByRole("button", { name: "Confirmar horário" })); + const dialog = await screen.findByRole("dialog"); + expect(within(dialog).getByRole("alert").textContent).toContain("Horário ocupado"); + expect((screen.getByLabelText("Data e hora") as HTMLInputElement).value).toBe(isoToLocalDateTimeInput(appointment_datetime)); + fireEvent.click(within(dialog).getByRole("button", { name: "Confirmar horário" })); + await waitFor(() => expect(confirmAppointment).toHaveBeenCalledTimes(2)); + expect(screen.getByRole("dialog")).toBeTruthy(); + expect(onStatusUpdated).not.toHaveBeenCalled(); + expect(alert).not.toHaveBeenCalled(); + alert.mockRestore(); + }); + + it("keeps a non-conflict direct error inline without opening the modal", async () => { + vi.mocked(confirmAppointment).mockRejectedValue({ response: { status: 500, data: { error: { message: "Falha temporária." } } } }); + const alert = vi.spyOn(window, "alert").mockImplementation(() => {}); + renderCard({ ...baseProcess, appointment_datetime: "2099-09-20T17:30:00.000Z" }); + fireEvent.click(screen.getByRole("button", { name: "Confirmar horário" })); + expect((await screen.findByRole("alert")).textContent).toContain("Falha temporária"); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(alert).not.toHaveBeenCalled(); + alert.mockRestore(); + }); + + it("disables both confirmation actions and reject while a direct request is pending", async () => { + let resolve!: (value: Awaited>) => void; + vi.mocked(confirmAppointment).mockImplementation(() => new Promise((done) => { resolve = done; })); + renderCard({ ...baseProcess, appointment_datetime: "2099-09-20T17:30:00.000Z" }); + const confirm = screen.getByRole("button", { name: "Confirmar horário" }); + fireEvent.click(confirm); + fireEvent.click(confirm); + expect((confirm as HTMLButtonElement).disabled).toBe(true); + expect((screen.getByRole("button", { name: "Alterar e confirmar" }) as HTMLButtonElement).disabled).toBe(true); + expect((screen.getByRole("button", { name: "Recusar" }) as HTMLButtonElement).disabled).toBe(true); + expect(confirmAppointment).toHaveBeenCalledOnce(); + await act(async () => resolve({ processId: baseProcess.id, status: "SCHEDULING", appointment_status: "SCHEDULED" })); + }); + + it("keeps meeting and later reschedule actions in SCHEDULED plus SCHEDULING", async () => { + renderCard({ ...baseProcess, appointment_status: "SCHEDULED", appointment_datetime: "2099-09-20T17:30:00.000Z" }); + expect(await screen.findByRole("button", { name: "Iniciar Reunião" })).toBeTruthy(); + expect(screen.getByRole("button", { name: "Alterar horário" })).toBeTruthy(); + expect(screen.queryByRole("button", { name: "Confirmar horário" })).toBeNull(); + expect(screen.queryByRole("button", { name: "Alterar e confirmar" })).toBeNull(); + expect(screen.queryByText("Solicitação de agendamento")).toBeNull(); + }); + + it.each(["(11) 98765-4321", "+55 11 98765-4321"])("renders safe WhatsApp and preserves the original phone %s", (phone) => { + renderCard({ ...baseProcess, client: { ...baseProcess.client!, email: "cliente@example.com", phone } }); + const link = screen.getByRole("link", { name: /WhatsApp/i }); + expect(link.getAttribute("href")).toBe("https://wa.me/5511987654321"); + expect(link.getAttribute("target")).toBe("_blank"); + expect(link.getAttribute("rel")).toBe("noopener noreferrer"); + expect(screen.getByText(phone)).toBeTruthy(); + expect(screen.getByRole("button", { name: `Copiar telefone do cliente: ${phone}` })).toBeTruthy(); + }); + + it.each(["123", "ligar para ramal 42", null])("never generates WhatsApp for invalid/absent phone %s", (phone) => { + renderCard({ ...baseProcess, client: { ...baseProcess.client!, phone } }); + expect(screen.queryByRole("link", { name: /WhatsApp/i })).toBeNull(); + if (phone) expect(screen.getByText(phone)).toBeTruthy(); + else expect(screen.queryByRole("button", { name: /Copiar telefone/i })).toBeNull(); + }); + + it.each([ + { appointment_status: "CANCELLED" as const }, + { appointment_status: null }, + { appointment_status: undefined }, + { appointment_id: null }, + ])("does not offer confirmation outside an attached pending appointment: %j", (overrides) => { + renderCard({ ...baseProcess, appointment_datetime: "2099-09-20T17:30:00.000Z", ...overrides }); + expect(screen.queryByRole("button", { name: "Confirmar horário" })).toBeNull(); + expect(screen.queryByRole("button", { name: "Alterar e confirmar" })).toBeNull(); + expect(screen.queryByText("Solicitação de agendamento")).toBeNull(); + }); + + it.each(["Cancelar", "Fechar", "Escape"])("returns focus to the change-and-confirm trigger after %s", async (action) => { + renderCard({ ...baseProcess, appointment_datetime: "2099-09-20T17:30:00.000Z" }); + const trigger = screen.getByRole("button", { name: "Alterar e confirmar" }); + trigger.focus(); + fireEvent.click(trigger); + expect(await screen.findByRole("dialog")).toBeTruthy(); + if (action === "Escape") fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" }); + else fireEvent.click(screen.getByRole("button", { name: action })); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + await waitFor(() => expect(document.activeElement).toBe(trigger)); + }); + + it("returns focus to direct confirmation after dismissing its 409 recovery", async () => { + vi.mocked(confirmAppointment).mockRejectedValue({ response: { status: 409, data: { error: { message: "Escolha outro horário." } } } }); + renderCard({ ...baseProcess, appointment_datetime: "2099-09-20T17:30:00.000Z" }); + const trigger = screen.getByRole("button", { name: "Confirmar horário" }); + trigger.focus(); + fireEvent.click(trigger); + const dialog = await screen.findByRole("dialog"); + fireEvent.click(within(dialog).getByRole("button", { name: "Cancelar" })); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + await waitFor(() => expect(document.activeElement).toBe(trigger)); + }); + + it("keeps modal and card controls busy during changed confirmation", async () => { + let resolve!: (value: Awaited>) => void; + vi.mocked(confirmAppointment).mockImplementation(() => new Promise((done) => { resolve = done; })); + renderCard({ ...baseProcess, appointment_datetime: "2099-09-20T17:30:00.000Z" }); + fireEvent.click(screen.getByRole("button", { name: "Alterar e confirmar" })); + const dialog = screen.getByRole("dialog"); + const submit = within(dialog).getByRole("button", { name: "Confirmar horário" }) as HTMLButtonElement; + fireEvent.click(submit); + expect(submit.disabled).toBe(true); + expect((screen.getByLabelText("Data e hora") as HTMLInputElement).disabled).toBe(true); + expect((within(dialog).getByRole("button", { name: "Cancelar" }) as HTMLButtonElement).disabled).toBe(true); + expect((within(dialog).getByRole("button", { name: "Fechar" }) as HTMLButtonElement).disabled).toBe(true); + fireEvent.keyDown(dialog, { key: "Escape" }); + expect(screen.getByRole("dialog")).toBeTruthy(); + await act(async () => resolve({ processId: baseProcess.id, status: "SCHEDULING", appointment_status: "SCHEDULED" })); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + expect(rescheduleAppointment).not.toHaveBeenCalled(); + }); }); diff --git a/frontend/src/components/processes/ProcessCard.tsx b/frontend/src/components/processes/ProcessCard.tsx index 224ddca..7a2f109 100644 --- a/frontend/src/components/processes/ProcessCard.tsx +++ b/frontend/src/components/processes/ProcessCard.tsx @@ -15,7 +15,7 @@ import { Mail, Phone, } from "lucide-react"; -import { useState, useEffect } from "react"; +import { useState, useEffect, useRef } from "react"; import { useNavigate } from "react-router-dom"; import type { Process } from "../../services/processes.service"; import type { Product, SpecialityType } from "../../types/types"; @@ -23,7 +23,7 @@ import React from "react"; import UpdateProcessStatusModal from "./UpdateProcessStatusModal"; import CopyableContact from "./CopyableContact"; import AppointmentDateTimeModal from "../appointments/AppointmentDateTimeModal"; -import { applyPhoneMask } from "../../utils/mask"; +import { buildWhatsAppHref } from "../../lib/whatsapp"; import { getContextualStatusMessage } from "../../utils/processStatusMessages"; import { getProcessCompletionReason, @@ -119,6 +119,8 @@ export default function ProcessCard({ null, ); const [isRescheduling, setIsRescheduling] = useState(false); + const confirmationInFlight = useRef(false); + const dateTimeTriggerRef = useRef(null); // Verifica se é um processo de consultoria (sem produto atribuído) const isConsultancy = !process.product_type || !process.product_id; @@ -130,6 +132,7 @@ export default function ProcessCard({ const counterpartLabel = isClientView ? "especialista" : "cliente"; const counterpartEmail = counterpart?.email?.trim() || null; const counterpartPhone = counterpart?.phone?.trim() || null; + const whatsAppHref = counterpartPhone ? buildWhatsAppHref(counterpartPhone) : null; const isAppointmentConfirmed = process.appointment_status === "SCHEDULED" || process.appointment_status === "COMPLETED"; @@ -250,7 +253,9 @@ export default function ProcessCard({ // Handle confirm appointment const handleConfirmAppointment = async (appointmentDatetime: string) => { - if (isConfirming) return; + if (confirmationInFlight.current || isCancelling || + process.appointment_status !== "PENDING" || !process.appointment_id) return; + confirmationInFlight.current = true; try { setIsConfirming(true); @@ -259,18 +264,17 @@ export default function ProcessCard({ setDateTimeAction(null); onStatusUpdated?.(); } catch (error) { - console.error("Error confirming appointment:", error); const message = getActionErrorMessage( error, "Erro ao confirmar agendamento. Tente novamente.", ); - if (dateTimeAction === "confirm") { - setDateTimeActionError(message); - } else { - alert(message); + setDateTimeActionError(message); + if ((error as { response?: { status?: number } })?.response?.status === 409) { + setDateTimeAction("confirm"); } } finally { setIsConfirming(false); + confirmationInFlight.current = false; } }; @@ -422,11 +426,22 @@ export default function ProcessCard({ {counterpartPhone && ( } - label={applyPhoneMask(counterpartPhone)} + label={counterpartPhone} value={counterpartPhone} description={`telefone do ${counterpartLabel}`} /> )} + {whatsAppHref && ( + + + WhatsApp do {counterpartLabel} + + )}
)} @@ -501,7 +516,7 @@ export default function ProcessCard({ {/* Appointment Confirmation Buttons - SCHEDULING Status (before appointment confirmation) */} - {process.status === "SCHEDULING" && !isAppointmentConfirmed && ( + {process.status === "SCHEDULING" && process.appointment_status === "PENDING" && process.appointment_id && (

@@ -509,10 +524,13 @@ export default function ProcessCard({ ? "Aguardando confirmação do especialista" : "Solicitação de agendamento"}

+ {dateTimeActionError && dateTimeAction === null && ( +

{dateTimeActionError}

+ )} {!isClientView ? ( // Specialist view - Confirm or Reject buttons -
+
+ )} + + }} + disabled={isConfirming || isCancelling} + className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-white border border-green-600 text-green-700 rounded-lg font-medium hover:bg-green-50 transition disabled:opacity-50" + > + + Alterar e confirmar + + ) : (

Aguardando sincronização do Calendly @@ -599,7 +620,8 @@ export default function ProcessCard({ {canSpecialistReschedule && ( ; + }, useCalendlyEventListener: vi.fn(), - PopupModal: ({ url }: { url: string }) => Calendly popup, })); -const client = { - id: "client-1", - name: "Cliente", - surname: "Teste", - email: "cliente@example.com", -}; -const publicProfile: PublicSpecialistProfile = { - id: "specialist-1", - name: "Ana", - surname: "Silva", - email: "ana@example.com", - speciality: "CAR", - calendly_url: "https://calendly.com/ana", - calendly_scheduling_available: true, -}; - -function renderModal(mode: "CONSULTANT" | "OFFICE") { - render( - - - - } - /> - Processos do consultor

} - /> - Processos do escritório
} - /> - - , - ); +const client: Client = { id: "customer-1", name: "Cliente", surname: "Teste", email: "cliente@example.com", cpf: "12345678900", rg: "12345678", role: "CUSTOMER" }; +const specialist: PublicSpecialistProfile = { id: "specialist-1", name: "Ana", surname: "Silva", email: "ana@example.com", speciality: "CAR", calendly_url: "https://calendly.com/ana/reuniao", calendly_scheduling_available: false }; +const secondClient: Client = { ...client, id: "customer-2", name: "Outro", email: "outro@example.com" }; +function Location() { return

{useLocation().pathname}

; } +function scopeContent(props: { specialistId?: string; productType?: "CAR" | "BOAT" | "AIRCRAFT"; productId?: string; mode?: "CONSULTANT" | "OFFICE" } = {}, visible = true) { + return {visible && }; +} + +function renderModal(mode: "CONSULTANT" | "OFFICE" = "CONSULTANT") { + return render( + } /> + Processos do consultor

} /> + Processos do escritório

} /> +
); } -describe("StartProcessForClientModal public specialist display", () => { +async function selectAndCreate() { + fireEvent.click(await screen.findByRole("button", { name: /Cliente Teste/i })); + fireEvent.click(screen.getByRole("button", { name: "Criar processo" })); +} + +describe("StartProcessForClientModal capability", () => { beforeEach(() => { - vi.mocked(getClients).mockResolvedValue([client] as never); - vi.mocked(officeService.listClients).mockResolvedValue([client] as never); - vi.mocked(getPublicSpecialistById).mockResolvedValue(publicProfile); - vi.mocked(getUserById).mockResolvedValue(publicProfile as never); - const process = { - id: "process-1", - status: "SCHEDULING", - appointment_id: "appointment-1", - }; - vi.mocked(createConsultantProcess).mockResolvedValue(process); - vi.mocked(officeService.createProcess).mockResolvedValue(process); - }); - afterEach(() => { - cleanup(); - vi.clearAllMocks(); - }); - - it.each(["CONSULTANT", "OFFICE"] as const)( - "loads the public specialist profile in %s mode without private user access", - async (mode) => { - renderModal(mode); - await screen.findByRole("button", { name: /Cliente Teste/ }); - await waitFor(() => - expect(getPublicSpecialistById).toHaveBeenCalledWith("specialist-1"), - ); - expect(getUserById).not.toHaveBeenCalled(); - fireEvent.click(screen.getByRole("button", { name: /Cliente Teste/ })); - fireEvent.click(screen.getByRole("button", { name: "Criar processo" })); - const createProcess = - mode === "OFFICE" - ? officeService.createProcess - : createConsultantProcess; - await waitFor(() => - expect(createProcess).toHaveBeenCalledWith({ - client_id: "client-1", - specialist_id: "specialist-1", - product_type: "CAR", - product_id: "car-1", - }), - ); - expect( - ( - await screen.findByRole("link", { name: "Calendly popup" }) - ).getAttribute("href"), - ).toBe(publicProfile.calendly_url); - }, - ); - - it("preserves process creation when the public profile has no Calendly URL", async () => { - vi.mocked(getPublicSpecialistById).mockResolvedValue({ - ...publicProfile, - calendly_url: null, - calendly_scheduling_available: false, - }); - renderModal("CONSULTANT"); - fireEvent.click( - await screen.findByRole("button", { name: /Cliente Teste/ }), - ); - fireEvent.click(screen.getByRole("button", { name: "Criar processo" })); + popupClosers.length = 0; + vi.mocked(getClients).mockResolvedValue([client]); + vi.mocked(officeService.listClients).mockResolvedValue([{ id: client.id, name: client.name, surname: client.surname, email: client.email, cpf: client.cpf, civil_state: null, consultant_id: null, consultant: null, created_at: "2026-01-01T00:00:00.000Z" }]); + vi.mocked(getPublicSpecialistById).mockResolvedValue(specialist); + vi.mocked(createConsultantProcess).mockResolvedValue({ id: "process-1", appointment_id: "appointment-1", status: "SCHEDULING" }); + vi.mocked(officeService.createProcess).mockResolvedValue({ id: "process-1", appointment_id: "appointment-1" }); + vi.mocked(registerCalendlyScheduledEvent).mockResolvedValue({} as never); + vi.mocked(getCalendlySyncStatus).mockResolvedValue({} as never); + }); + afterEach(() => { cleanup(); vi.resetAllMocks(); }); + + it.each(["CONSULTANT", "OFFICE"] as const)("ignores a stale URL when capability is false in %s mode", async (mode) => { + renderModal(mode); + await selectAndCreate(); + expect(await screen.findByText(mode === "OFFICE" ? "Processos do escritório" : "Processos do consultor")).toBeTruthy(); + expect(screen.queryByRole("link", { name: "Agendar no Calendly" })).toBeNull(); + expect(getPublicSpecialistById).toHaveBeenCalledWith(specialist.id); + expect(getUserById).not.toHaveBeenCalled(); + }); + + it.each(["CONSULTANT", "OFFICE"] as const)("opens Calendly only for capability true in %s mode", async (mode) => { + vi.mocked(getPublicSpecialistById).mockResolvedValue({ ...specialist, calendly_scheduling_available: true }); + renderModal(mode); + await selectAndCreate(); + expect((await screen.findByRole("link", { name: "Agendar no Calendly" })).getAttribute("href")).toBe(specialist.calendly_url); + expect(mode === "OFFICE" ? officeService.createProcess : createConsultantProcess).toHaveBeenCalledWith({ client_id: client.id, specialist_id: specialist.id, product_type: "CAR", product_id: "car-1" }); + expect(getUserById).not.toHaveBeenCalled(); + }); + + it("preserves process creation without a Calendly URL when capability is false", async () => { + vi.mocked(getPublicSpecialistById).mockResolvedValue({ ...specialist, calendly_url: null }); + renderModal(); + await selectAndCreate(); expect(await screen.findByText("Processos do consultor")).toBeTruthy(); expect(getUserById).not.toHaveBeenCalled(); }); + + it("waits for the public capability before allowing creation", async () => { + let resolve!: (value: PublicSpecialistProfile) => void; + vi.mocked(getPublicSpecialistById).mockImplementation(() => new Promise((done) => { resolve = done; })); + renderModal(); + fireEvent.click(await screen.findByRole("button", { name: /Cliente Teste/i })); + const create = screen.getByRole("button", { name: "Criar processo" }) as HTMLButtonElement; + expect(create.disabled).toBe(true); + fireEvent.click(create); + expect(createConsultantProcess).not.toHaveBeenCalled(); + await act(async () => resolve(specialist)); + await waitFor(() => expect(create.disabled).toBe(false)); + }); + + it("shows a load error and prevents treating unavailable capability as false", async () => { + vi.mocked(getPublicSpecialistById).mockRejectedValue(new Error("offline")); + renderModal(); + fireEvent.click(await screen.findByRole("button", { name: /Cliente Teste/i })); + expect((await screen.findByRole("alert")).textContent).toContain("especialista"); + expect((screen.getByRole("button", { name: "Criar processo" }) as HTMLButtonElement).disabled).toBe(true); + expect(createConsultantProcess).not.toHaveBeenCalled(); + }); + + it("does not fall back when capability is true but its URL is absent", async () => { + vi.mocked(getPublicSpecialistById).mockResolvedValue({ ...specialist, calendly_scheduling_available: true, calendly_url: null }); + renderModal(); + await selectAndCreate(); + expect((await screen.findByRole("alert")).textContent).toContain("Calendly"); + expect(createConsultantProcess).not.toHaveBeenCalled(); + expect(screen.queryByText("Processos do consultor")).toBeNull(); + }); + + it("resets capability and ignores an old specialist response after switching specialistId", async () => { + let resolveOld!: (value: PublicSpecialistProfile) => void; + vi.mocked(getPublicSpecialistById).mockImplementationOnce(() => new Promise((done) => { resolveOld = done; })).mockResolvedValueOnce({ ...specialist, id: "specialist-2", calendly_url: null }); + const view = render(); + fireEvent.click(await screen.findByRole("button", { name: /Cliente Teste/i })); + view.rerender(); + fireEvent.click(await screen.findByRole("button", { name: /Cliente Teste/i })); + await waitFor(() => expect((screen.getByRole("button", { name: "Criar processo" }) as HTMLButtonElement).disabled).toBe(false)); + await act(async () => resolveOld({ ...specialist, calendly_scheduling_available: true })); + fireEvent.click(screen.getByRole("button", { name: "Criar processo" })); + await waitFor(() => expect(createConsultantProcess).toHaveBeenCalledWith(expect.objectContaining({ specialist_id: "specialist-2" }))); + expect(screen.queryByRole("link", { name: "Agendar no Calendly" })).toBeNull(); + }); + + it.each(["resolve", "reject"] as const)("ignores obsolete creation %s after changing specialist scope", async (outcome) => { + let resolve!: (value: Awaited>) => void; + let reject!: (error: Error) => void; + vi.mocked(createConsultantProcess).mockImplementationOnce(() => new Promise((done, fail) => { resolve = done; reject = fail; })); + vi.mocked(getPublicSpecialistById).mockResolvedValueOnce({ ...specialist, calendly_scheduling_available: true }).mockResolvedValueOnce({ ...specialist, id: "specialist-2", calendly_url: null }); + const content = (specialistId: string) => + + + ; + const view = render(content(specialist.id)); + await selectAndCreate(); + expect(createConsultantProcess).toHaveBeenCalledOnce(); + view.rerender(content("specialist-2")); + await waitFor(() => expect(getPublicSpecialistById).toHaveBeenCalledWith("specialist-2")); + await act(async () => { + if (outcome === "resolve") resolve({ id: "old-process", appointment_id: "old-appointment", status: "SCHEDULING" }); + else reject(new Error("old creation failed")); + }); + expect(screen.queryByRole("link", { name: "Agendar no Calendly" })).toBeNull(); + expect(screen.queryByText("old creation failed")).toBeNull(); + expect(screen.getByTestId("location").textContent).toBe("/start"); + fireEvent.click(await screen.findByRole("button", { name: /Cliente Teste/i })); + expect((screen.getByRole("button", { name: "Criar processo" }) as HTMLButtonElement).disabled).toBe(false); + }); + + it.each([{ productType: "BOAT" as const }, { productId: "car-2" }, { mode: "OFFICE" as const }])("invalidates in-flight creation for scope change %j", async (props) => { + let resolve!: (value: Awaited>) => void; + vi.mocked(createConsultantProcess).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); + const view = render(scopeContent()); + await selectAndCreate(); + view.rerender(scopeContent(props)); + await act(async () => resolve({ id: "old-process", appointment_id: "old-appointment", status: "SCHEDULING" })); + expect(screen.getByTestId("location").textContent).toBe("/start"); + expect(screen.queryByRole("link", { name: "Agendar no Calendly" })).toBeNull(); + }); + + it.each(["resolve", "reject"] as const)("does not let the old %s/finally release the new A→B→A request", async (outcome) => { + let resolveOld!: (value: Awaited>) => void; + let rejectOld!: (error: Error) => void; + let resolveCurrent!: (value: Awaited>) => void; + vi.mocked(getPublicSpecialistById).mockImplementation(async (id) => ({ ...specialist, id, calendly_scheduling_available: true })); + vi.mocked(createConsultantProcess) + .mockImplementationOnce(() => new Promise((done, fail) => { resolveOld = done; rejectOld = fail; })) + .mockImplementationOnce(() => new Promise((done) => { resolveCurrent = done; })); + const view = render(scopeContent()); + await selectAndCreate(); + view.rerender(scopeContent({ specialistId: "specialist-2" })); + await waitFor(() => expect(getPublicSpecialistById).toHaveBeenCalledWith("specialist-2")); + view.rerender(scopeContent()); + fireEvent.click(await screen.findByRole("button", { name: /Cliente Teste/i })); + fireEvent.click(screen.getByRole("button", { name: "Criar processo" })); + await waitFor(() => expect(createConsultantProcess).toHaveBeenCalledTimes(2)); + await act(async () => { + if (outcome === "resolve") resolveOld({ id: "old-process", appointment_id: "old-appointment", status: "SCHEDULING" }); + else rejectOld(new Error("old creation failed")); + }); + expect((screen.getByRole("button", { name: "Criando..." }) as HTMLButtonElement).disabled).toBe(true); + expect(screen.queryByRole("alert")).toBeNull(); + expect(screen.queryByRole("link", { name: "Agendar no Calendly" })).toBeNull(); + await act(async () => resolveCurrent({ id: "current-process", appointment_id: "current-appointment", status: "SCHEDULING" })); + expect(await screen.findByRole("link", { name: "Agendar no Calendly" })).toBeTruthy(); + }); + + it("does not navigate after the modal unmounts during creation", async () => { + let resolve!: (value: Awaited>) => void; + vi.mocked(createConsultantProcess).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); + const view = render(scopeContent()); + await selectAndCreate(); + view.rerender(scopeContent({}, false)); + await act(async () => resolve({ id: "old-process", appointment_id: "old-appointment", status: "SCHEDULING" })); + expect(screen.getByTestId("location").textContent).toBe("/start"); + }); + + it("ignores the old client list after switching mode and clears the selection", async () => { + let resolve!: (value: Client[]) => void; + vi.mocked(getClients).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); + vi.mocked(officeService.listClients).mockResolvedValue([{ id: secondClient.id, name: secondClient.name, surname: secondClient.surname, email: secondClient.email, cpf: secondClient.cpf, civil_state: null, consultant_id: null, consultant: null, created_at: "2026-01-01T00:00:00.000Z" }]); + const view = render(scopeContent()); + view.rerender(scopeContent({ mode: "OFFICE" })); + expect(await screen.findByRole("button", { name: /Outro Teste/i })).toBeTruthy(); + await act(async () => resolve([client])); + expect(screen.getByRole("button", { name: /Outro Teste/i })).toBeTruthy(); + expect(screen.queryByRole("button", { name: /Cliente Teste/i })).toBeNull(); + expect((screen.getByRole("button", { name: "Criar processo" }) as HTMLButtonElement).disabled).toBe(true); + }); + + it("keeps the popup prefill tied to the submitted client while creation is busy", async () => { + let resolve!: (value: Awaited>) => void; + vi.mocked(getClients).mockResolvedValue([client, secondClient]); + vi.mocked(getPublicSpecialistById).mockResolvedValue({ ...specialist, calendly_scheduling_available: true }); + vi.mocked(createConsultantProcess).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); + renderModal(); + await selectAndCreate(); + const other = screen.getByRole("button", { name: /Outro Teste/i }) as HTMLButtonElement; + expect(other.disabled).toBe(true); + fireEvent.click(other); + await act(async () => resolve({ id: "process-1", appointment_id: "appointment-1", status: "SCHEDULING" })); + const popup = await screen.findByRole("link", { name: "Agendar no Calendly" }); + expect(popup.getAttribute("data-client-name")).toBe("Cliente Teste"); + expect(popup.getAttribute("data-client-email")).toBe(client.email); + expect(createConsultantProcess).toHaveBeenCalledWith(expect.objectContaining({ client_id: client.id })); + }); + + it("ignores Calendly sync completion after its scope changes", async () => { + let resolve!: (value: Awaited>) => void; + vi.mocked(getPublicSpecialistById).mockImplementation(async (id) => ({ ...specialist, id, calendly_scheduling_available: true })); + vi.mocked(registerCalendlyScheduledEvent).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); + const view = render(scopeContent()); + await selectAndCreate(); + await screen.findByRole("link", { name: "Agendar no Calendly" }); + const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0].onEventScheduled!; + let sync!: Promise; + act(() => { sync = Promise.resolve(listener({ data: { event: "calendly.event_scheduled", payload: { event: { uri: "event-uri" }, invitee: { uri: "invitee-uri" } } } } as Parameters[0])); }); + view.rerender(scopeContent({ specialistId: "specialist-2" })); + await act(async () => { resolve({} as never); await sync; }); + expect(getCalendlySyncStatus).not.toHaveBeenCalled(); + expect(screen.getByTestId("location").textContent).toBe("/start"); + }); + + it("keeps the selected client when only label or callback props change", async () => { + const view = render(scopeContent()); + fireEvent.click(await screen.findByRole("button", { name: /Cliente Teste/i })); + fireEvent.change(screen.getByPlaceholderText("Buscar por nome ou e-mail..."), { target: { value: "Cliente" } }); + view.rerender( {}} />); + expect((screen.getByRole("button", { name: "Criar processo" }) as HTMLButtonElement).disabled).toBe(false); + expect((screen.getByPlaceholderText("Buscar por nome ou e-mail...") as HTMLInputElement).value).toBe("Cliente"); + expect(getClients).toHaveBeenCalledOnce(); + expect(getPublicSpecialistById).toHaveBeenCalledOnce(); + }); + + it("ignores callbacks belonging to an obsolete Calendly popup before any HTTP write", async () => { + vi.mocked(getPublicSpecialistById).mockImplementation(async (id) => ({ ...specialist, id, calendly_scheduling_available: true })); + const view = render(scopeContent()); + await selectAndCreate(); + await screen.findByRole("link", { name: "Agendar no Calendly" }); + const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0].onEventScheduled!; + const close = popupClosers.at(-1)!; + view.rerender(scopeContent({ specialistId: "specialist-2" })); + await act(async () => { + close(); + await listener({ data: { event: "calendly.event_scheduled", payload: { event: { uri: "event-uri" }, invitee: { uri: "invitee-uri" } } } } as Parameters[0]); + }); + expect(registerCalendlyScheduledEvent).not.toHaveBeenCalled(); + expect(getCalendlySyncStatus).not.toHaveBeenCalled(); + expect(screen.getByTestId("location").textContent).toBe("/start"); + }); + + it("keeps the current popup close flow and releases its busy state", async () => { + vi.mocked(getPublicSpecialistById).mockResolvedValue({ ...specialist, calendly_scheduling_available: true }); + const onBusyChange = vi.fn(); + render(); + await selectAndCreate(); + expect(await screen.findByRole("link", { name: "Agendar no Calendly" })).toBeTruthy(); + expect(onBusyChange).toHaveBeenLastCalledWith(true); + fireEvent.click(screen.getByRole("button", { name: "Fechar Calendly" })); + expect(onBusyChange).toHaveBeenLastCalledWith(false); + expect(screen.getByTestId("location").textContent).toBe("/consultant/processes"); + }); }); diff --git a/frontend/src/components/processes/StartProcessForClientModal.tsx b/frontend/src/components/processes/StartProcessForClientModal.tsx index 84c91fe..55d8f07 100644 --- a/frontend/src/components/processes/StartProcessForClientModal.tsx +++ b/frontend/src/components/processes/StartProcessForClientModal.tsx @@ -1,9 +1,9 @@ -import { useEffect, useMemo, useRef, useState } from "react"; +import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useNavigate } from "react-router-dom"; import { PopupModal, useCalendlyEventListener } from "react-calendly"; import { getClients, createConsultantProcess, type Client } from "../../services/consultant.service"; import { officeService } from "../../services/office"; -import { getPublicSpecialistById } from "../../services/specialists.service"; +import { getPublicSpecialistById, type PublicSpecialistProfile } from "../../services/specialists.service"; import { registerCalendlyScheduledEvent, getCalendlySyncStatus, @@ -40,15 +40,23 @@ interface Props { productLabel?: string; mode?: keyof typeof MODES; onClose: () => void; + onBusyChange?(busy: boolean): void; } -export default function StartProcessForClientModal({ +export default function StartProcessForClientModal(props: Props) { + const mode = props.mode ?? "CONSULTANT"; + const scope = JSON.stringify([mode, props.specialistId, props.productType, props.productId]); + return ; +} + +function StartProcessForClientModalInner({ productType, productId, specialistId, productLabel, mode = "CONSULTANT", onClose, + onBusyChange, }: Props) { const config = MODES[mode]; const navigate = useNavigate(); @@ -61,32 +69,70 @@ export default function StartProcessForClientModal({ const searchRef = useRef(null); // Calendly - const [specialistCalendlyUrl, setSpecialistCalendlyUrl] = useState< - string | null - >(null); - const [pendingAppointmentId, setPendingAppointmentId] = useState< - string | null - >(null); + const [specialistProfile, setSpecialistProfile] = useState(null); + const [isLoadingSpecialist, setIsLoadingSpecialist] = useState(true); + const [specialistError, setSpecialistError] = useState(null); + const submittingRef = useRef(false); + const mountedRef = useRef(false); + const operationGeneration = useRef(0); + const busyCallbackRef = useRef(onBusyChange); + const [pendingOperation, setPendingOperation] = useState<{ + appointmentId: string; + generation: number; + client: Client; + } | null>(null); const [calendlyUrl, setCalendlyUrl] = useState(null); const [isCalendlyOpen, setIsCalendlyOpen] = useState(false); const [calendlyMessage, setCalendlyMessage] = useState(null); + useLayoutEffect(() => { + busyCallbackRef.current = onBusyChange; + }, [onBusyChange]); + + useLayoutEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + operationGeneration.current += 1; + busyCallbackRef.current?.(false); + }; + }, []); + + const isCurrentOperation = (generation: number) => + mountedRef.current && operationGeneration.current === generation; + + const setBusy = (busy: boolean) => { + setIsSubmitting(busy); + busyCallbackRef.current?.(busy); + }; + useEffect(() => { + let active = true; + setClients([]); + setSelectedClient(null); + setIsLoadingClients(true); config .listClients() - .then((list) => setClients(list as Client[])) - .catch(() => setClients([])) - .finally(() => setIsLoadingClients(false)); + .then((list) => { if (active) setClients(list as Client[]); }) + .catch(() => { if (active) setClients([]); }) + .finally(() => { if (active) setIsLoadingClients(false); }); searchRef.current?.focus(); // MODES é constante de módulo, então `config` só muda se `mode` mudar — // não recarrega a lista a cada render. + return () => { active = false; }; }, [config]); // Carrega o link do Calendly do especialista para permitir agendar a reunião useEffect(() => { + let active = true; + setSpecialistProfile(null); + setSpecialistError(null); + setIsLoadingSpecialist(true); getPublicSpecialistById(specialistId) - .then((u) => setSpecialistCalendlyUrl(u.calendly_url)) - .catch(() => setSpecialistCalendlyUrl(null)); + .then((profile) => { if (active) setSpecialistProfile(profile); }) + .catch(() => { if (active) setSpecialistError("Não foi possível carregar o especialista. Tente novamente."); }) + .finally(() => { if (active) setIsLoadingSpecialist(false); }); + return () => { active = false; }; }, [specialistId]); const filtered = useMemo(() => { @@ -100,7 +146,8 @@ export default function StartProcessForClientModal({ // Sincroniza o horário escolhido no Calendly com o agendamento criado useCalendlyEventListener({ onEventScheduled: async (event) => { - if (!pendingAppointmentId) return; + const pending = pendingOperation; + if (!pending || !isCurrentOperation(pending.generation)) return; const payload = (event as any)?.data?.payload; const eventUri = payload?.event?.uri; @@ -108,47 +155,70 @@ export default function StartProcessForClientModal({ try { if (eventUri && inviteeUri) { - await registerCalendlyScheduledEvent(pendingAppointmentId, { + await registerCalendlyScheduledEvent(pending.appointmentId, { event_uri: eventUri, invitee_uri: inviteeUri, client_event: "calendly.event_scheduled", client_observed_at: new Date().toISOString(), }); + if (!isCurrentOperation(pending.generation)) return; // Best-effort: garante que o status foi consultado antes de seguir - await getCalendlySyncStatus(pendingAppointmentId).catch(() => null); + await getCalendlySyncStatus(pending.appointmentId).catch(() => null); + if (!isCurrentOperation(pending.generation)) return; } } catch (err) { - console.error("Erro ao sincronizar evento do Calendly:", err); + if (isCurrentOperation(pending.generation)) { + console.error("Erro ao sincronizar evento do Calendly:", err); + } } finally { - setIsCalendlyOpen(false); - navigate(config.redirectTo); + if (isCurrentOperation(pending.generation)) { + operationGeneration.current += 1; + setIsCalendlyOpen(false); + setPendingOperation(null); + submittingRef.current = false; + setBusy(false); + navigate(config.redirectTo); + } } }, }); const handleSubmit = async () => { + if (submittingRef.current || isLoadingSpecialist || specialistError || + !specialistProfile || specialistProfile.id !== specialistId) return; if (!selectedClient) { setError("Selecione um cliente."); return; } setError(null); - setIsSubmitting(true); + const specialistCalendlyUrl = specialistProfile.calendly_url?.trim(); + if (specialistProfile.calendly_scheduling_available && !specialistCalendlyUrl) { + setError("O link do Calendly não está disponível. Tente novamente."); + return; + } + submittingRef.current = true; + const generation = ++operationGeneration.current; + const submittedClient = selectedClient; + let awaitingCalendly = false; + setBusy(true); try { const process = await config.createProcess({ - client_id: selectedClient.id, + client_id: submittedClient.id, specialist_id: specialistId, product_type: productType, product_id: productId, }); + if (!isCurrentOperation(generation)) return; // Se o especialista tem Calendly, abre o popup para marcar o horário. // Sem Calendly, segue o fluxo antigo (agendamento definido depois). - if (specialistCalendlyUrl && process.appointment_id) { + if (specialistProfile.calendly_scheduling_available && specialistCalendlyUrl && process.appointment_id) { let url = specialistCalendlyUrl.trim(); if (!url.startsWith("http://") && !url.startsWith("https://")) { url = `https://${url}`; } - setPendingAppointmentId(process.appointment_id); + awaitingCalendly = true; + setPendingOperation({ appointmentId: process.appointment_id, generation, client: submittedClient }); setCalendlyUrl(url); setIsCalendlyOpen(true); setCalendlyMessage( @@ -158,8 +228,14 @@ export default function StartProcessForClientModal({ navigate(config.redirectTo); } } catch (err) { - setError((err as Error).message || "Erro ao criar processo. Tente novamente."); - setIsSubmitting(false); + if (isCurrentOperation(generation)) { + setError((err as Error).message || "Erro ao criar processo. Tente novamente."); + } + } finally { + if (isCurrentOperation(generation) && !awaitingCalendly) { + submittingRef.current = false; + setBusy(false); + } } }; @@ -208,6 +284,7 @@ export default function StartProcessForClientModal({
- {error &&

{error}

} + {specialistError &&

{specialistError}

} + {error &&

{error}

} {calendlyMessage && (

{calendlyMessage}

)}
- @@ -247,15 +329,20 @@ export default function StartProcessForClientModal({ url={calendlyUrl} open={isCalendlyOpen} onModalClose={() => { + if (!pendingOperation || !isCurrentOperation(pendingOperation.generation)) return; + operationGeneration.current += 1; setIsCalendlyOpen(false); + setPendingOperation(null); + submittingRef.current = false; + setBusy(false); navigate(config.redirectTo); }} rootElement={document.getElementById("root") ?? document.body} prefill={{ - name: selectedClient - ? `${selectedClient.name} ${selectedClient.surname}`.trim() + name: pendingOperation + ? `${pendingOperation.client.name} ${pendingOperation.client.surname}`.trim() : undefined, - email: selectedClient?.email, + email: pendingOperation?.client.email, }} /> )} diff --git a/frontend/src/components/ui/dialog.tsx b/frontend/src/components/ui/dialog.tsx index c394dfe..fc64f4f 100644 --- a/frontend/src/components/ui/dialog.tsx +++ b/frontend/src/components/ui/dialog.tsx @@ -1,4 +1,4 @@ -import type { ReactNode } from "react"; +import type { ComponentPropsWithoutRef, ReactNode } from "react"; import * as DialogPrimitive from "@radix-ui/react-dialog"; import { AnimatePresence, motion, useReducedMotion } from "framer-motion"; import { X } from "lucide-react"; @@ -13,6 +13,8 @@ export function DialogContent({ className, hideTitle, dismissible = true, + onOpenAutoFocus, + onCloseAutoFocus, }: { open: boolean; title: ReactNode; @@ -20,6 +22,8 @@ export function DialogContent({ className?: string; hideTitle?: boolean; dismissible?: boolean; + onOpenAutoFocus?: ComponentPropsWithoutRef["onOpenAutoFocus"]; + onCloseAutoFocus?: ComponentPropsWithoutRef["onCloseAutoFocus"]; }) { const shouldReduceMotion = useReducedMotion(); const duration = shouldReduceMotion ? 0 : 0.15; @@ -41,6 +45,8 @@ export function DialogContent({ asChild forceMount aria-describedby={undefined} + onOpenAutoFocus={onOpenAutoFocus} + onCloseAutoFocus={onCloseAutoFocus} onEscapeKeyDown={(event) => { if (!dismissible) event.preventDefault(); }} diff --git a/frontend/src/pages/catalog/ProductPage.test.tsx b/frontend/src/pages/catalog/ProductPage.test.tsx index 505a600..61d2e57 100644 --- a/frontend/src/pages/catalog/ProductPage.test.tsx +++ b/frontend/src/pages/catalog/ProductPage.test.tsx @@ -10,7 +10,9 @@ import { } from "@testing-library/react"; import { MemoryRouter, Route, Routes, useNavigate } from "react-router-dom"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import userEvent from "@testing-library/user-event"; import ProductPage from "./ProductPage"; +import { createConsultantProcess, getClients } from "../../services/consultant.service"; import { getCarById } from "../../services/cars.service"; import { getUserById } from "../../services/users.service"; import { @@ -72,13 +74,11 @@ vi.mock("../../hooks/useCalendlyScheduling", () => ({ closePopup: vi.fn(), }), })); -vi.mock("react-calendly", () => ({ PopupModal: () => null })); +vi.mock("react-calendly", () => ({ PopupModal: () => null, useCalendlyEventListener: vi.fn() })); vi.mock("../../components/product/ProductDetails", () => ({ default: () =>
Detalhes do produto
, })); -vi.mock("../../components/processes/StartProcessForClientModal", () => ({ - default: () => null, -})); +vi.mock("../../services/consultant.service", () => ({ getClients: vi.fn(), createConsultantProcess: vi.fn() })); const product = { id: "car-1", @@ -139,6 +139,7 @@ function page() { } /> Meus processos
} /> + Processos delegados
} /> ); @@ -186,9 +187,43 @@ describe("ProductPage scheduling", () => { vi.mocked(getPublicSpecialistById).mockResolvedValue(specialist); vi.mocked(checkExistingAppointment).mockResolvedValue({ exists: false }); vi.mocked(createPendingAppointment).mockResolvedValue(appointment); + vi.mocked(getClients).mockResolvedValue([{ id: "delegated-client", name: "Cliente", surname: "Delegado", email: "cliente@example.com", cpf: "12345678900", rg: "12345678", role: "CUSTOMER" }]); vi.spyOn(window, "open").mockImplementation(() => null); }); + it.each(["Fechar", "Escape", "outside"])("keeps the delegated process dialog open during POST when attempting %s", async (action) => { + authState.user = { ...authState.user, role: "CONSULTANT" }; + let resolve!: (value: Awaited>) => void; + vi.mocked(createConsultantProcess).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); + render(page()); + fireEvent.click(await screen.findByRole("button", { name: "Iniciar processo para cliente" })); + fireEvent.click(await screen.findByRole("button", { name: /Cliente Delegado/i })); + fireEvent.click(screen.getByRole("button", { name: "Criar processo" })); + const dialog = screen.getByRole("dialog"); + if (action === "Fechar") { + const close = screen.getByRole("button", { name: "Fechar" }) as HTMLButtonElement; + expect(close.disabled).toBe(true); + fireEvent.click(close); + } else if (action === "Escape") { + fireEvent.keyDown(dialog, { key: "Escape" }); + } else { + await userEvent.setup({ pointerEventsCheck: 0 }).click(document.body); + } + expect(screen.getByRole("dialog").getAttribute("data-state")).toBe("open"); + await act(async () => resolve({ id: "delegated-process", appointment_id: "delegated-appointment", status: "SCHEDULING" })); + expect(createConsultantProcess).toHaveBeenCalledOnce(); + expect(await screen.findByText("Processos delegados")).toBeTruthy(); + }); + + it("allows an idle delegated dialog to close outside", async () => { + authState.user = { ...authState.user, role: "CONSULTANT" }; + render(page()); + fireEvent.click(await screen.findByRole("button", { name: "Iniciar processo para cliente" })); + await screen.findByRole("button", { name: /Cliente Delegado/i }); + await userEvent.setup({ pointerEventsCheck: 0 }).click(document.body); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + }); + afterEach(() => { cleanup(); vi.restoreAllMocks(); diff --git a/frontend/src/pages/catalog/ProductPage.tsx b/frontend/src/pages/catalog/ProductPage.tsx index 964ac7e..24b47b1 100644 --- a/frontend/src/pages/catalog/ProductPage.tsx +++ b/frontend/src/pages/catalog/ProductPage.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { ArrowLeft, CheckCircle, ExternalLink, Loader2 } from "lucide-react"; import { PopupModal } from "react-calendly"; @@ -106,6 +106,15 @@ export default function ProductPage() { autoOpen: boolean; } | null>(null); const [isStartProcessModalOpen, setIsStartProcessModalOpen] = useState(false); + const [isStartProcessBusy, setIsStartProcessBusy] = useState(false); + const startProcessBusyRef = useRef(false); + const handleStartProcessBusyChange = useCallback((busy: boolean) => { + startProcessBusyRef.current = busy; + setIsStartProcessBusy(busy); + }, []); + const handleStartProcessOpenChange = (open: boolean) => { + if (!startProcessBusyRef.current) setIsStartProcessModalOpen(open); + }; const [isDateTimeModalOpen, setIsDateTimeModalOpen] = useState(false); const [dateTimeError, setDateTimeError] = useState(null); const [creationNotice, setCreationNotice] = useState(null); @@ -666,12 +675,13 @@ export default function ProductPage() { {specialist && productType && id && ( setIsStartProcessModalOpen(false)} + onClose={() => handleStartProcessOpenChange(false)} + onBusyChange={handleStartProcessBusyChange} /> diff --git a/frontend/src/pages/customer/ConsultoriaPage.test.tsx b/frontend/src/pages/customer/ConsultoriaPage.test.tsx new file mode 100644 index 0000000..f737215 --- /dev/null +++ b/frontend/src/pages/customer/ConsultoriaPage.test.tsx @@ -0,0 +1,59 @@ +// @vitest-environment jsdom + +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import ConsultoriaPage from "./ConsultoriaPage"; +import { AuthContext, type AuthContextProps } from "../../contexts/AuthContext"; +import { getSpecialistsGroupedByCategory, type PublicSpecialistProfile } from "../../services/specialists.service"; +import { createConsultancyAppointment } from "../../services/appointments.service"; + +const { openPopup } = vi.hoisted(() => ({ openPopup: vi.fn() })); +vi.mock("../../services/specialists.service", () => ({ getSpecialistsGroupedByCategory: vi.fn() })); +vi.mock("../../services/appointments.service", () => ({ createConsultancyAppointment: vi.fn() })); +vi.mock("../../hooks/useCalendlyScheduling", () => ({ useCalendlyScheduling: () => ({ isModalOpen: false, modalUrl: null, syncState: "idle", syncMessage: null, openPopup, closePopup: vi.fn() }) })); + +const specialist: PublicSpecialistProfile = { id: "specialist-1", name: "Ana", surname: "Silva", email: "ana@example.com", speciality: "CAR", calendly_url: "https://calendly.com/ana/reuniao", calendly_scheduling_available: false }; +function mockSpecialist(value: PublicSpecialistProfile) { + vi.mocked(getSpecialistsGroupedByCategory).mockResolvedValue({ CAR: [value], BOAT: [], AIRCRAFT: [] }); +} +function renderPage() { + const context = { user: { id: "customer-1", name: "Cliente", surname: "Teste", email: "cliente@example.com", role: "CUSTOMER" } } as AuthContextProps; + return render( + } /> + Meus processos

} /> +
); +} + +describe("ConsultoriaPage capability", () => { + beforeEach(() => { + mockSpecialist(specialist); + vi.mocked(createConsultancyAppointment).mockResolvedValue({ id: "appointment-1" } as never); + }); + afterEach(() => { cleanup(); vi.resetAllMocks(); }); + + it("creates EMAIL consultancy without product or date even with a stale URL", async () => { + renderPage(); + fireEvent.click(await screen.findByRole("button", { name: "Solicitar Reunião" })); + expect(await screen.findByText("Meus processos")).toBeTruthy(); + expect(createConsultancyAppointment).toHaveBeenCalledWith({ client_id: "customer-1", specialist_id: specialist.id, scheduling_method: "EMAIL", notes: "Consultoria solicitada pelo cliente" }); + expect(openPopup).not.toHaveBeenCalled(); + }); + + it("preserves connected Calendly consultancy", async () => { + mockSpecialist({ ...specialist, calendly_scheduling_available: true }); + renderPage(); + fireEvent.click(await screen.findByRole("button", { name: "Solicitar Reunião" })); + await waitFor(() => expect(openPopup).toHaveBeenCalledWith("appointment-1", specialist.calendly_url)); + expect(createConsultancyAppointment).toHaveBeenCalledWith(expect.objectContaining({ scheduling_method: "CALENDLY" })); + }); + + it("does not create EMAIL fallback for a capability true response missing its URL", async () => { + mockSpecialist({ ...specialist, calendly_scheduling_available: true, calendly_url: null }); + renderPage(); + fireEvent.click(await screen.findByRole("button", { name: "Solicitar Reunião" })); + expect((await screen.findByRole("alert")).textContent).toContain("Calendly"); + expect(createConsultancyAppointment).not.toHaveBeenCalled(); + expect(openPopup).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/pages/customer/ConsultoriaPage.tsx b/frontend/src/pages/customer/ConsultoriaPage.tsx index 1ded032..f7d4373 100644 --- a/frontend/src/pages/customer/ConsultoriaPage.tsx +++ b/frontend/src/pages/customer/ConsultoriaPage.tsx @@ -4,7 +4,7 @@ import { Car, Ship, Plane, Calendar, UserCircle2, Loader2 } from "lucide-react"; import { PopupModal } from "react-calendly"; import { getSpecialistsGroupedByCategory, - type Specialist, + type PublicSpecialistProfile, type GroupedSpecialists, } from "../../services/specialists.service"; import { createConsultancyAppointment } from "../../services/appointments.service"; @@ -24,7 +24,7 @@ interface SpecialistGroup { type: SpecialityType; label: string; icon: React.ReactNode; - specialists: Specialist[]; + specialists: PublicSpecialistProfile[]; } const specialityConfig: Record< @@ -110,24 +110,26 @@ export default function ConsultoriaPage() { setIsTypeModalOpen(false); }; - const handleRequestMeeting = async (specialist: Specialist) => { + const handleRequestMeeting = async (specialist: PublicSpecialistProfile) => { if (!user || requestingSpecialistId) return; setRequestingSpecialistId(specialist.id); setErrorMessage(""); try { + const hasCalendly = specialist.calendly_scheduling_available; + const rawCalendlyUrl = specialist.calendly_url?.trim() || ""; + if (hasCalendly && !rawCalendlyUrl) { + throw new Error("O link do Calendly não está disponível. Tente novamente."); + } const pendingAppointment = await createConsultancyAppointment({ client_id: user.id, specialist_id: specialist.id, - scheduling_method: specialist.calendly_url?.trim() - ? "CALENDLY" - : "EMAIL", + scheduling_method: hasCalendly ? "CALENDLY" : "EMAIL", notes: `Consultoria solicitada pelo cliente`, }); - const rawCalendlyUrl = specialist.calendly_url?.trim(); - if (!rawCalendlyUrl) { + if (!hasCalendly) { navigate("/customer/processes", { state: { message: @@ -276,8 +278,8 @@ export default function ConsultoriaPage() { } interface SpecialistCardProps { - specialist: Specialist; - onRequestMeeting: (specialist: Specialist) => Promise; + specialist: PublicSpecialistProfile; + onRequestMeeting: (specialist: PublicSpecialistProfile) => Promise; isRequesting: boolean; } diff --git a/frontend/src/pages/profile/ProfilePage.test.tsx b/frontend/src/pages/profile/ProfilePage.test.tsx new file mode 100644 index 0000000..d38a413 --- /dev/null +++ b/frontend/src/pages/profile/ProfilePage.test.tsx @@ -0,0 +1,57 @@ +// @vitest-environment jsdom + +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import ProfilePage from "./ProfilePage"; +import { useAuth } from "../../store/authStateManager"; +import { getUserById, updateUser, type UserProfile } from "../../services/users.service"; +import { getCalendlyOAuthStatus } from "../../services/appointments.service"; +import { getMyAdvisor } from "../../services/advisor.service"; +import type { UserProps } from "../../types/types"; + +vi.mock("../../services/users.service", () => ({ getUserById: vi.fn(), updateUser: vi.fn() })); +vi.mock("../../services/appointments.service", () => ({ getCalendlyOAuthStatus: vi.fn(), getCalendlyAuthorizeUrl: vi.fn(), disconnectCalendlyOAuth: vi.fn() })); +vi.mock("../../services/advisor.service", () => ({ getMyAdvisor: vi.fn(), inviteAdvisor: vi.fn(), removeAdvisor: vi.fn() })); + +const profile: UserProfile = { id: "user-1", name: "Ana", surname: "Silva", email: "ana@example.com", role: "SPECIALIST", cpf: "12345678900", rg: "12345678", phone: "11987654321", civil_state: null, speciality: "CAR", calendly_url: "https://calendly.com/ana/reuniao", created_at: "2026-01-01T00:00:00.000Z" }; +function renderPage(role: UserProps["role"] = "SPECIALIST") { + useAuth.setState({ user: { id: profile.id, name: profile.name, surname: profile.surname, email: profile.email, cpf: profile.cpf, rg: profile.rg, role } }); + return render(); +} + +describe("ProfilePage Calendly payload", () => { + beforeEach(() => { + vi.mocked(getUserById).mockResolvedValue(profile); + vi.mocked(updateUser).mockResolvedValue(profile); + vi.mocked(getCalendlyOAuthStatus).mockResolvedValue({ connected: false, calendly_user_uri: null, expires_at: null, is_active: false }); + vi.mocked(getMyAdvisor).mockResolvedValue(null); + }); + afterEach(() => { cleanup(); vi.resetAllMocks(); useAuth.setState({ user: null }); }); + + it.each(["", " "])("sends null when a specialist clears Calendly with %j", async (value) => { + renderPage(); + const input = await screen.findByPlaceholderText("https://calendly.com/seu-usuario"); + fireEvent.change(input, { target: { value } }); + fireEvent.click(screen.getByRole("button", { name: "Salvar Alterações" })); + await waitFor(() => expect(updateUser).toHaveBeenCalledWith(profile.id, expect.objectContaining({ calendly_url: null }))); + }); + + it("sends the trimmed specialist URL", async () => { + renderPage(); + const input = await screen.findByPlaceholderText("https://calendly.com/seu-usuario"); + fireEvent.change(input, { target: { value: "https://calendly.com/ana/novo" } }); + fireEvent.click(screen.getByRole("button", { name: "Salvar Alterações" })); + await waitFor(() => expect(updateUser).toHaveBeenCalledWith(profile.id, expect.objectContaining({ calendly_url: "https://calendly.com/ana/novo" }))); + }); + + it.each(["CUSTOMER", "CONSULTANT", "OFFICE", "ADMIN"] as const)("never sends calendly_url for %s even if the loaded profile has a URL", async (role) => { + renderPage(role); + const save = await screen.findByRole("button", { name: "Salvar Alterações" }); + expect(screen.queryByPlaceholderText("https://calendly.com/seu-usuario")).toBeNull(); + fireEvent.click(save); + await waitFor(() => expect(updateUser).toHaveBeenCalledOnce()); + expect(Object.hasOwn(vi.mocked(updateUser).mock.calls[0][1], "calendly_url")).toBe(false); + expect(getUserById).toHaveBeenCalledWith(profile.id); + }); +}); diff --git a/frontend/src/pages/profile/ProfilePage.tsx b/frontend/src/pages/profile/ProfilePage.tsx index ea03cd9..31dfb2a 100644 --- a/frontend/src/pages/profile/ProfilePage.tsx +++ b/frontend/src/pages/profile/ProfilePage.tsx @@ -264,7 +264,7 @@ export default function CustomerProfilePage() { // Só envia calendly_url se for especialista if (user.role === "SPECIALIST") { const trimmedUrl = formData.calendly_url?.trim(); - dataToUpdate.calendly_url = trimmedUrl || undefined; + dataToUpdate.calendly_url = trimmedUrl || null; } await updateUser(user.id, dataToUpdate); diff --git a/frontend/src/services/specialists.service.ts b/frontend/src/services/specialists.service.ts index 8e4d929..fdc8e68 100644 --- a/frontend/src/services/specialists.service.ts +++ b/frontend/src/services/specialists.service.ts @@ -22,9 +22,9 @@ export type Specialist = { // Tipo para especialistas agrupados por categoria export type GroupedSpecialists = { - CAR: Specialist[]; - BOAT: Specialist[]; - AIRCRAFT: Specialist[]; + CAR: PublicSpecialistProfile[]; + BOAT: PublicSpecialistProfile[]; + AIRCRAFT: PublicSpecialistProfile[]; }; // Projeção pública de contato comercial; não contém documentos ou dados OAuth. diff --git a/frontend/src/services/users.service.ts b/frontend/src/services/users.service.ts index 11d6302..b8798d1 100644 --- a/frontend/src/services/users.service.ts +++ b/frontend/src/services/users.service.ts @@ -21,7 +21,7 @@ export interface UpdateUserData { cpf?: string; rg?: string; phone?: string; - calendly_url?: string; + calendly_url?: string | null; } export interface ApiResponse { From a062e98fd7946ce0a903e25ca1fa1e4ad916dd7f Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 10:35:25 -0300 Subject: [PATCH 14/60] fix: keep delegated Calendly popup inside dialog scope --- .../StartProcessForClientModal.test.tsx | 28 +- .../processes/StartProcessForClientModal.tsx | 24 +- frontend/src/components/ui/dialog.tsx | 86 +++++-- .../ProductPage.calendly.integration.test.tsx | 243 ++++++++++++++++++ frontend/src/pages/catalog/ProductPage.tsx | 7 + 5 files changed, 348 insertions(+), 40 deletions(-) create mode 100644 frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx diff --git a/frontend/src/components/processes/StartProcessForClientModal.test.tsx b/frontend/src/components/processes/StartProcessForClientModal.test.tsx index 2030ed0..546db81 100644 --- a/frontend/src/components/processes/StartProcessForClientModal.test.tsx +++ b/frontend/src/components/processes/StartProcessForClientModal.test.tsx @@ -30,13 +30,13 @@ const client: Client = { id: "customer-1", name: "Cliente", surname: "Teste", em const specialist: PublicSpecialistProfile = { id: "specialist-1", name: "Ana", surname: "Silva", email: "ana@example.com", speciality: "CAR", calendly_url: "https://calendly.com/ana/reuniao", calendly_scheduling_available: false }; const secondClient: Client = { ...client, id: "customer-2", name: "Outro", email: "outro@example.com" }; function Location() { return

{useLocation().pathname}

; } -function scopeContent(props: { specialistId?: string; productType?: "CAR" | "BOAT" | "AIRCRAFT"; productId?: string; mode?: "CONSULTANT" | "OFFICE" } = {}, visible = true) { - return {visible && }; +function scopeContent(props: { specialistId?: string; productType?: "CAR" | "BOAT" | "AIRCRAFT"; productId?: string; mode?: "CONSULTANT" | "OFFICE"; onCalendlyOpenChange?(open: boolean): void } = {}, visible = true) { + return {visible && }; } function renderModal(mode: "CONSULTANT" | "OFFICE" = "CONSULTANT") { return render( - } /> + } /> Processos do consultor

} /> Processos do escritório

} />
); @@ -120,9 +120,9 @@ describe("StartProcessForClientModal capability", () => { it("resets capability and ignores an old specialist response after switching specialistId", async () => { let resolveOld!: (value: PublicSpecialistProfile) => void; vi.mocked(getPublicSpecialistById).mockImplementationOnce(() => new Promise((done) => { resolveOld = done; })).mockResolvedValueOnce({ ...specialist, id: "specialist-2", calendly_url: null }); - const view = render(); + const view = render(); fireEvent.click(await screen.findByRole("button", { name: /Cliente Teste/i })); - view.rerender(); + view.rerender(); fireEvent.click(await screen.findByRole("button", { name: /Cliente Teste/i })); await waitFor(() => expect((screen.getByRole("button", { name: "Criar processo" }) as HTMLButtonElement).disabled).toBe(false)); await act(async () => resolveOld({ ...specialist, calendly_scheduling_available: true })); @@ -138,7 +138,7 @@ describe("StartProcessForClientModal capability", () => { vi.mocked(getPublicSpecialistById).mockResolvedValueOnce({ ...specialist, calendly_scheduling_available: true }).mockResolvedValueOnce({ ...specialist, id: "specialist-2", calendly_url: null }); const content = (specialistId: string) => - + ; const view = render(content(specialist.id)); await selectAndCreate(); @@ -254,7 +254,7 @@ describe("StartProcessForClientModal capability", () => { const view = render(scopeContent()); fireEvent.click(await screen.findByRole("button", { name: /Cliente Teste/i })); fireEvent.change(screen.getByPlaceholderText("Buscar por nome ou e-mail..."), { target: { value: "Cliente" } }); - view.rerender( {}} />); + view.rerender( {}} />); expect((screen.getByRole("button", { name: "Criar processo" }) as HTMLButtonElement).disabled).toBe(false); expect((screen.getByPlaceholderText("Buscar por nome ou e-mail...") as HTMLInputElement).value).toBe("Cliente"); expect(getClients).toHaveBeenCalledOnce(); @@ -263,12 +263,16 @@ describe("StartProcessForClientModal capability", () => { it("ignores callbacks belonging to an obsolete Calendly popup before any HTTP write", async () => { vi.mocked(getPublicSpecialistById).mockImplementation(async (id) => ({ ...specialist, id, calendly_scheduling_available: true })); - const view = render(scopeContent()); + const onCalendlyOpenChange = vi.fn(); + const view = render(scopeContent({ onCalendlyOpenChange })); await selectAndCreate(); await screen.findByRole("link", { name: "Agendar no Calendly" }); const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0].onEventScheduled!; const close = popupClosers.at(-1)!; - view.rerender(scopeContent({ specialistId: "specialist-2" })); + expect(onCalendlyOpenChange).toHaveBeenLastCalledWith(true); + view.rerender(scopeContent({ specialistId: "specialist-2", onCalendlyOpenChange })); + expect(onCalendlyOpenChange).toHaveBeenLastCalledWith(false); + onCalendlyOpenChange.mockClear(); await act(async () => { close(); await listener({ data: { event: "calendly.event_scheduled", payload: { event: { uri: "event-uri" }, invitee: { uri: "invitee-uri" } } } } as Parameters[0]); @@ -276,17 +280,21 @@ describe("StartProcessForClientModal capability", () => { expect(registerCalendlyScheduledEvent).not.toHaveBeenCalled(); expect(getCalendlySyncStatus).not.toHaveBeenCalled(); expect(screen.getByTestId("location").textContent).toBe("/start"); + expect(onCalendlyOpenChange).not.toHaveBeenCalled(); }); it("keeps the current popup close flow and releases its busy state", async () => { vi.mocked(getPublicSpecialistById).mockResolvedValue({ ...specialist, calendly_scheduling_available: true }); const onBusyChange = vi.fn(); - render(); + const onCalendlyOpenChange = vi.fn(); + render(); await selectAndCreate(); expect(await screen.findByRole("link", { name: "Agendar no Calendly" })).toBeTruthy(); expect(onBusyChange).toHaveBeenLastCalledWith(true); + expect(onCalendlyOpenChange).toHaveBeenLastCalledWith(true); fireEvent.click(screen.getByRole("button", { name: "Fechar Calendly" })); expect(onBusyChange).toHaveBeenLastCalledWith(false); + expect(onCalendlyOpenChange).toHaveBeenLastCalledWith(false); expect(screen.getByTestId("location").textContent).toBe("/consultant/processes"); }); }); diff --git a/frontend/src/components/processes/StartProcessForClientModal.tsx b/frontend/src/components/processes/StartProcessForClientModal.tsx index 55d8f07..9167eca 100644 --- a/frontend/src/components/processes/StartProcessForClientModal.tsx +++ b/frontend/src/components/processes/StartProcessForClientModal.tsx @@ -41,6 +41,8 @@ interface Props { mode?: keyof typeof MODES; onClose: () => void; onBusyChange?(busy: boolean): void; + calendlyRootElement: HTMLElement | null; + onCalendlyOpenChange?(open: boolean): void; } export default function StartProcessForClientModal(props: Props) { @@ -57,6 +59,8 @@ function StartProcessForClientModalInner({ mode = "CONSULTANT", onClose, onBusyChange, + calendlyRootElement, + onCalendlyOpenChange, }: Props) { const config = MODES[mode]; const navigate = useNavigate(); @@ -76,6 +80,7 @@ function StartProcessForClientModalInner({ const mountedRef = useRef(false); const operationGeneration = useRef(0); const busyCallbackRef = useRef(onBusyChange); + const calendlyOpenCallbackRef = useRef(onCalendlyOpenChange); const [pendingOperation, setPendingOperation] = useState<{ appointmentId: string; generation: number; @@ -87,13 +92,15 @@ function StartProcessForClientModalInner({ useLayoutEffect(() => { busyCallbackRef.current = onBusyChange; - }, [onBusyChange]); + calendlyOpenCallbackRef.current = onCalendlyOpenChange; + }, [onBusyChange, onCalendlyOpenChange]); useLayoutEffect(() => { mountedRef.current = true; return () => { mountedRef.current = false; operationGeneration.current += 1; + calendlyOpenCallbackRef.current?.(false); busyCallbackRef.current?.(false); }; }, []); @@ -106,6 +113,11 @@ function StartProcessForClientModalInner({ busyCallbackRef.current?.(busy); }; + const setCalendlyOpen = (open: boolean) => { + setIsCalendlyOpen(open); + calendlyOpenCallbackRef.current?.(open); + }; + useEffect(() => { let active = true; setClients([]); @@ -173,7 +185,7 @@ function StartProcessForClientModalInner({ } finally { if (isCurrentOperation(pending.generation)) { operationGeneration.current += 1; - setIsCalendlyOpen(false); + setCalendlyOpen(false); setPendingOperation(null); submittingRef.current = false; setBusy(false); @@ -220,7 +232,7 @@ function StartProcessForClientModalInner({ awaitingCalendly = true; setPendingOperation({ appointmentId: process.appointment_id, generation, client: submittedClient }); setCalendlyUrl(url); - setIsCalendlyOpen(true); + setCalendlyOpen(true); setCalendlyMessage( "Conclua o agendamento no Calendly para marcar o horário da reunião.", ); @@ -324,20 +336,20 @@ function StartProcessForClientModalInner({ - {calendlyUrl && isCalendlyOpen && ( + {calendlyRootElement && calendlyUrl && isCalendlyOpen && ( { if (!pendingOperation || !isCurrentOperation(pendingOperation.generation)) return; operationGeneration.current += 1; - setIsCalendlyOpen(false); + setCalendlyOpen(false); setPendingOperation(null); submittingRef.current = false; setBusy(false); navigate(config.redirectTo); }} - rootElement={document.getElementById("root") ?? document.body} + rootElement={calendlyRootElement} prefill={{ name: pendingOperation ? `${pendingOperation.client.name} ${pendingOperation.client.surname}`.trim() diff --git a/frontend/src/components/ui/dialog.tsx b/frontend/src/components/ui/dialog.tsx index fc64f4f..440b125 100644 --- a/frontend/src/components/ui/dialog.tsx +++ b/frontend/src/components/ui/dialog.tsx @@ -1,4 +1,4 @@ -import type { ComponentPropsWithoutRef, ReactNode } from "react"; +import { useCallback, useLayoutEffect, useRef, type ComponentPropsWithoutRef, type ReactNode } from "react"; import * as DialogPrimitive from "@radix-ui/react-dialog"; import { AnimatePresence, motion, useReducedMotion } from "framer-motion"; import { X } from "lucide-react"; @@ -15,6 +15,9 @@ export function DialogContent({ dismissible = true, onOpenAutoFocus, onCloseAutoFocus, + onPortalContainerChange, + portalActive = false, + portalLabel, }: { open: boolean; title: ReactNode; @@ -24,9 +27,55 @@ export function DialogContent({ dismissible?: boolean; onOpenAutoFocus?: ComponentPropsWithoutRef["onOpenAutoFocus"]; onCloseAutoFocus?: ComponentPropsWithoutRef["onCloseAutoFocus"]; + onPortalContainerChange?(element: HTMLDivElement | null): void; + portalActive?: boolean; + portalLabel?: string; }) { const shouldReduceMotion = useReducedMotion(); const duration = shouldReduceMotion ? 0 : 0.15; + const portalRef = useRef(null); + const setPortalContainer = useCallback((element: HTMLDivElement | null) => { + portalRef.current = element; + onPortalContainerChange?.(element); + }, [onPortalContainerChange]); + + useLayoutEffect(() => { + const portal = portalRef.current; + if (open && portalActive && portal && !portal.contains(document.activeElement)) { + portal.focus({ preventScroll: true }); + } + }, [open, portalActive]); + + const panel = ( + + ); return ( @@ -54,30 +103,19 @@ export function DialogContent({ if (!dismissible) event.preventDefault(); }} > - -
- - {title} - - - - + {onPortalContainerChange ? ( + // Keep viewport portals inside the focus scope without inheriting the panel's transform or overflow. +
+ {panel} +
- {children} - + ) : panel} )} diff --git a/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx b/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx new file mode 100644 index 0000000..7bb0ae5 --- /dev/null +++ b/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx @@ -0,0 +1,243 @@ +// @vitest-environment jsdom + +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { StrictMode } from "react"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import ProductPage from "./ProductPage"; +import { getCarById } from "../../services/cars.service"; +import { createConsultantProcess, getClients } from "../../services/consultant.service"; +import { officeService } from "../../services/office"; +import { getPublicSpecialistById, type PublicSpecialistProfile } from "../../services/specialists.service"; +import { checkExistingAppointment, getCalendlySyncStatus, registerCalendlyScheduledEvent } from "../../services/appointments.service"; + +const { authState } = vi.hoisted(() => ({ + authState: { user: { id: "consultant-1", role: "CONSULTANT", name: "Consultor", surname: "Teste", email: "consultor@example.com" } }, +})); + +vi.mock("../../services/cars.service", () => ({ getCarById: vi.fn() })); +vi.mock("../../services/boats.service", () => ({ getBoatById: vi.fn() })); +vi.mock("../../services/aircrafts.service", () => ({ getAircraftById: vi.fn() })); +vi.mock("../../services/specialists.service", () => ({ getPublicSpecialistById: vi.fn() })); +vi.mock("../../services/consultant.service", () => ({ getClients: vi.fn(), createConsultantProcess: vi.fn() })); +vi.mock("../../services/office", () => ({ officeService: { listClients: vi.fn(), createProcess: vi.fn() } })); +vi.mock("../../services/appointments.service", async (importOriginal) => ({ + ...(await importOriginal()), + checkExistingAppointment: vi.fn(), + getCalendlySyncStatus: vi.fn(), + registerCalendlyScheduledEvent: vi.fn(), +})); +vi.mock("../../store/authStateManager", () => ({ + useAuth: (selector?: (state: typeof authState) => unknown) => selector ? selector(authState) : authState, +})); + +const specialist: PublicSpecialistProfile = { + id: "specialist-1", name: "Ana", surname: "Silva", email: "ana@example.com", speciality: "CAR", + calendly_url: "https://calendly.com/ana/reuniao", calendly_scheduling_available: true, +}; +const client = { id: "customer-1", name: "Cliente", surname: "Delegado", email: "cliente@example.com", cpf: "12345678900", rg: "12345678", role: "CUSTOMER" as const }; + +function pageContent() { + return + + } /> + Processos do consultor} /> + Processos do escritório} /> + + ; +} + +function page(strict = false) { + const root = document.createElement("div"); + root.id = "root"; + document.body.append(root); + return render(strict ? {pageContent()} : pageContent(), { container: root }); +} + +async function openCalendly(preserveEnabledFocus = false) { + const user = userEvent.setup(); + await user.click(await screen.findByRole("button", { name: "Iniciar processo para cliente" })); + await user.click(await screen.findByRole("button", { name: /Cliente Delegado/ })); + if (preserveEnabledFocus) { + act(() => screen.getByPlaceholderText("Buscar por nome ou e-mail...").focus()); + fireEvent.click(screen.getByRole("button", { name: "Criar processo" })); + } else { + await user.click(screen.getByRole("button", { name: "Criar processo" })); + } + const iframe = await screen.findByTitle("Calendly Scheduling Page"); + return { user, iframe }; +} + +describe("delegated Calendly with the real Radix dialog and PopupModal", () => { + beforeEach(() => { + authState.user = { ...authState.user, role: "CONSULTANT" }; + vi.mocked(getCarById).mockResolvedValue({ + id: "car-1", marca: "Marca", modelo: "Modelo", valor: 100_000, currency: "BRL", estado: "novo", ano: 2026, + specialist_id: specialist.id, identificador: "ABC-1", created_at: "2026-01-01T00:00:00.000Z", updated_at: "2026-01-01T00:00:00.000Z", + }); + vi.mocked(getPublicSpecialistById).mockResolvedValue(specialist); + vi.mocked(checkExistingAppointment).mockResolvedValue({ exists: false }); + vi.mocked(getClients).mockResolvedValue([client]); + vi.mocked(officeService.listClients).mockResolvedValue([{ ...client, civil_state: null, consultant_id: null, consultant: null, created_at: "2026-01-01T00:00:00.000Z" }]); + vi.mocked(createConsultantProcess).mockResolvedValue({ id: "process-1", appointment_id: "appointment-1", status: "SCHEDULING" }); + vi.mocked(officeService.createProcess).mockResolvedValue({ id: "process-1", appointment_id: "appointment-1" }); + vi.mocked(registerCalendlyScheduledEvent).mockResolvedValue({} as never); + vi.mocked(getCalendlySyncStatus).mockResolvedValue({} as never); + }); + + afterEach(() => { + cleanup(); + document.getElementById("root")?.remove(); + vi.resetAllMocks(); + }); + + it.each(["CONSULTANT", "OFFICE"])("keeps the real %s popup accessible inside the host focus scope", async (role) => { + authState.user.role = role; + page(); + const { iframe } = await openCalendly(); + expect(iframe.closest('[aria-hidden="true"]') === null).toBe(true); + expect(screen.getByRole("dialog").contains(iframe)).toBe(true); + expect(screen.getByRole("button", { name: "Close modal" })).toBeTruthy(); + expect(new URL(iframe.src).searchParams.get("name")).toBe("Cliente Delegado"); + expect(new URL(iframe.src).searchParams.get("email")).toBe(client.email); + }); + + it.each(["CONSULTANT", "OFFICE"])("allows focus to enter the real %s Calendly iframe and close control", async (role) => { + authState.user.role = role; + page(); + const { iframe } = await openCalendly(true); + act(() => iframe.focus()); + expect(document.activeElement).toBe(iframe); + const close = iframe.closest(".calendly-overlay")!.querySelector(".calendly-popup-close")!; + act(() => close.focus()); + expect(document.activeElement).toBe(close); + }); + + it.each(["CONSULTANT", "OFFICE"])("isolates %s keyboard focus in the active popup without unmounting the form", async (role) => { + authState.user.role = role; + page(); + const { user, iframe } = await openCalendly(); + const slot = iframe.closest(".calendly-overlay")!.parentElement!; + const search = screen.getByPlaceholderText("Buscar por nome ou e-mail..."); + const panel = search.closest("[inert]"); + expect(panel !== null).toBe(true); + expect(panel?.getAttribute("aria-hidden")).toBe("true"); + expect(panel?.hidden).toBe(true); + expect(slot.tabIndex).toBe(-1); + expect(document.activeElement).toBe(slot); + expect(screen.queryByRole("textbox")).toBeNull(); + await user.tab(); + expect(slot.contains(document.activeElement)).toBe(true); + await user.tab(); + expect(slot.contains(document.activeElement)).toBe(true); + let ancestor = slot.parentElement; + while (ancestor && ancestor !== document.body) { + expect(["", "none"]).toContain(ancestor.style.transform); + expect(["", "none"]).toContain(ancestor.style.translate); + expect(["", "visible"]).toContain(ancestor.style.overflow); + ancestor = ancestor.parentElement; + } + }); + + it.each(["CONSULTANT", "OFFICE"])("allows the real %s popup close button to redirect and release the host lock", async (role) => { + authState.user.role = role; + page(); + const { user, iframe } = await openCalendly(); + expect(getComputedStyle(iframe).pointerEvents).toBe("auto"); + const close = iframe.closest(".calendly-overlay")!.querySelector(".calendly-popup-close")!; + await user.click(close); + expect(await screen.findByRole("heading", { name: role === "OFFICE" ? "Processos do escritório" : "Processos do consultor" })).toBeTruthy(); + await waitFor(() => expect(document.body.style.pointerEvents).not.toBe("none")); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(screen.queryByTitle("Calendly Scheduling Page")).toBeNull(); + }); + + it.each(["Fechar", "Escape", "outside"])("keeps the real host nondismissible during POST for %s", async (action) => { + let resolve!: (value: Awaited>) => void; + vi.mocked(createConsultantProcess).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); + page(); + const user = userEvent.setup(); + await user.click(await screen.findByRole("button", { name: "Iniciar processo para cliente" })); + await user.click(await screen.findByRole("button", { name: /Cliente Delegado/ })); + await user.click(screen.getByRole("button", { name: "Criar processo" })); + if (action === "Fechar") { + const close = screen.getByRole("button", { name: "Fechar" }); + expect(close.disabled).toBe(true); + await user.click(close); + } else if (action === "Escape") { + await user.keyboard("{Escape}"); + } else { + await userEvent.setup({ pointerEventsCheck: 0 }).click(document.body); + } + expect(screen.getByRole("dialog").getAttribute("data-state")).toBe("open"); + expect(screen.queryByTitle("Calendly Scheduling Page")).toBeNull(); + await act(async () => resolve({ id: "process-1", appointment_id: "appointment-1", status: "SCHEDULING" })); + const iframe = await screen.findByTitle("Calendly Scheduling Page"); + await user.click(iframe.closest(".calendly-overlay")!.querySelector(".calendly-popup-close")!); + expect(await screen.findByRole("heading", { name: "Processos do consultor" })).toBeTruthy(); + }); + + it("closes the idle host when clicked outside its panel", async () => { + page(); + const user = userEvent.setup(); + await user.click(await screen.findByRole("button", { name: "Iniciar processo para cliente" })); + await screen.findByRole("button", { name: /Cliente Delegado/ }); + await userEvent.setup({ pointerEventsCheck: 0 }).click(document.body); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + }); + + it.each(["CONSULTANT", "OFFICE"])("synchronizes a real Calendly event before redirecting in %s mode", async (role) => { + authState.user.role = role; + page(); + await openCalendly(); + fireEvent(window, new MessageEvent("message", { + origin: "https://calendly.com", + data: { event: "calendly.event_scheduled", payload: { event: { uri: "event-uri" }, invitee: { uri: "invitee-uri" } } }, + })); + expect(await screen.findByRole("heading", { name: role === "OFFICE" ? "Processos do escritório" : "Processos do consultor" })).toBeTruthy(); + expect(registerCalendlyScheduledEvent).toHaveBeenCalledWith("appointment-1", expect.objectContaining({ event_uri: "event-uri", invitee_uri: "invitee-uri" })); + expect(getCalendlySyncStatus).toHaveBeenCalledWith("appointment-1"); + await waitFor(() => expect(document.body.style.pointerEvents).not.toBe("none")); + }); + + it("ignores synchronization completion after the real popup is closed", async () => { + let resolve!: (value: Awaited>) => void; + vi.mocked(registerCalendlyScheduledEvent).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); + page(); + const { user, iframe } = await openCalendly(); + fireEvent(window, new MessageEvent("message", { + origin: "https://calendly.com", + data: { event: "calendly.event_scheduled", payload: { event: { uri: "event-uri" }, invitee: { uri: "invitee-uri" } } }, + })); + await waitFor(() => expect(registerCalendlyScheduledEvent).toHaveBeenCalledOnce()); + await user.click(iframe.closest(".calendly-overlay")!.querySelector(".calendly-popup-close")!); + expect(await screen.findByRole("heading", { name: "Processos do consultor" })).toBeTruthy(); + await act(async () => resolve({} as never)); + expect(getCalendlySyncStatus).not.toHaveBeenCalled(); + expect(screen.queryByTitle("Calendly Scheduling Page")).toBeNull(); + }); + + it("keeps popup focus across rerenders in StrictMode without refocusing its slot", async () => { + const view = page(true); + const { user, iframe } = await openCalendly(); + const slot = iframe.closest(".calendly-overlay")!.parentElement!; + expect(document.activeElement).toBe(slot); + const refocus = vi.spyOn(slot, "focus"); + act(() => iframe.focus()); + view.rerender({pageContent()}); + expect(document.activeElement).toBe(iframe); + expect(refocus).not.toHaveBeenCalled(); + const close = screen.getByRole("button", { name: "Close modal" }); + act(() => close.focus()); + view.rerender({pageContent()}); + expect(document.activeElement).toBe(close); + expect(refocus).not.toHaveBeenCalled(); + await user.click(close); + expect(await screen.findByRole("heading", { name: "Processos do consultor" })).toBeTruthy(); + await waitFor(() => expect(document.body.style.pointerEvents).not.toBe("none")); + expect(slot.isConnected).toBe(false); + expect(refocus).not.toHaveBeenCalled(); + refocus.mockRestore(); + }); +}); diff --git a/frontend/src/pages/catalog/ProductPage.tsx b/frontend/src/pages/catalog/ProductPage.tsx index 24b47b1..e221dcf 100644 --- a/frontend/src/pages/catalog/ProductPage.tsx +++ b/frontend/src/pages/catalog/ProductPage.tsx @@ -107,6 +107,8 @@ export default function ProductPage() { } | null>(null); const [isStartProcessModalOpen, setIsStartProcessModalOpen] = useState(false); const [isStartProcessBusy, setIsStartProcessBusy] = useState(false); + const [startProcessPortalElement, setStartProcessPortalElement] = useState(null); + const [isStartProcessCalendlyOpen, setIsStartProcessCalendlyOpen] = useState(false); const startProcessBusyRef = useRef(false); const handleStartProcessBusyChange = useCallback((busy: boolean) => { startProcessBusyRef.current = busy; @@ -682,6 +684,9 @@ export default function ProductPage() { title="Iniciar processo para cliente" hideTitle dismissible={!isStartProcessBusy} + onPortalContainerChange={setStartProcessPortalElement} + portalActive={isStartProcessCalendlyOpen} + portalLabel="Agendar reunião no Calendly" > handleStartProcessOpenChange(false)} onBusyChange={handleStartProcessBusyChange} + calendlyRootElement={startProcessPortalElement} + onCalendlyOpenChange={setIsStartProcessCalendlyOpen} /> From 94e4f92406e1c8103603ea143dc7c6f5b3f937eb Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 11:00:49 -0300 Subject: [PATCH 15/60] test: cover no-Calendly email scheduling end to end --- backend/package.json | 3 +- backend/prisma/seed-email-scheduling-e2e.ts | 394 ++++++++++ backend/test/email-scheduling.e2e-spec.ts | 799 ++++++++++++++++++++ backend/test/jest-e2e.json | 3 + docs/docs/agendamento-sem-calendly.md | 374 ++------- 5 files changed, 1265 insertions(+), 308 deletions(-) create mode 100644 backend/prisma/seed-email-scheduling-e2e.ts create mode 100644 backend/test/email-scheduling.e2e-spec.ts diff --git a/backend/package.json b/backend/package.json index f7aa54d..a30abdf 100644 --- a/backend/package.json +++ b/backend/package.json @@ -18,7 +18,8 @@ "test:cov": "jest --coverage", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", "test:e2e": "jest --config ./test/jest-e2e.json", - "seed": "ts-node prisma/seed.ts" + "seed": "ts-node prisma/seed.ts", + "seed:email-scheduling-e2e": "ts-node prisma/seed-email-scheduling-e2e.ts" }, "dependencies": { "@aws-sdk/client-s3": "^3.911.0", diff --git a/backend/prisma/seed-email-scheduling-e2e.ts b/backend/prisma/seed-email-scheduling-e2e.ts new file mode 100644 index 0000000..f7b1737 --- /dev/null +++ b/backend/prisma/seed-email-scheduling-e2e.ts @@ -0,0 +1,394 @@ +/** + * Local-only fixtures for the no-Calendly scheduling gate. No .env fallback, + * truncation, user deletion or product deletion. Generated workflow IDs are + * resolved from an allowlist and validated before transactional cleanup. + */ +import type { Prisma, PrismaClient } from '@prisma/client'; +import * as bcrypt from 'bcrypt'; + +type Actor = 'customer' | 'specialist' | 'outsider'; +type Namespace = 'browser' | 'http'; + +export interface EmailSchedulingE2EConfig { + databaseUrl: string; + namespace: Namespace; + credentials: Record; +} + +export function emailSchedulingFixtures(namespace: Namespace) { + const prefix = + namespace === 'browser' + ? 'c848f474-6492-4ac1-8a7d' + : '8c26e2a3-fd13-447a-9b6c'; + const rgPrefix = namespace === 'browser' ? '990801' : '990802'; + const users = [ + { + actor: 'customer' as const, + id: `${prefix}-000000000001`, + name: 'E2E Cliente', + surname: `Email ${namespace}`, + rg: `${rgPrefix}00001`, + phone: '11987654321', + role: 'CUSTOMER' as const, + speciality: null, + }, + { + actor: 'specialist' as const, + id: `${prefix}-000000000002`, + name: 'E2E Especialista', + surname: `Email ${namespace}`, + rg: `${rgPrefix}00002`, + phone: '11976543210', + role: 'SPECIALIST' as const, + speciality: 'CAR' as const, + }, + { + actor: 'outsider' as const, + id: `${prefix}-000000000003`, + name: 'E2E Nao Atribuido', + surname: `Email ${namespace}`, + rg: `${rgPrefix}00003`, + phone: '21998765432', + role: 'SPECIALIST' as const, + speciality: 'CAR' as const, + }, + ]; + return { + namespace, + users, + cars: [ + { + id: `${prefix}-000000000101`, + specialist_id: users[1].id, + marca: 'E2E Email', + modelo: 'Produto A', + identificador: `email-scheduling-${namespace}-a`, + }, + { + id: `${prefix}-000000000102`, + specialist_id: users[1].id, + marca: 'E2E Email', + modelo: 'Produto B', + identificador: `email-scheduling-${namespace}-b`, + }, + ], + }; +} + +type Fixtures = ReturnType; + +export function readEmailSchedulingE2EConfig( + env: NodeJS.ProcessEnv, + namespace: Namespace = 'browser', +): EmailSchedulingE2EConfig { + const databaseUrl = env.EMAIL_SCHEDULING_E2E_DATABASE_URL?.trim(); + try { + const url = new URL(databaseUrl ?? ''); + if ( + !['postgresql:', 'postgres:'].includes(url.protocol) || + !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) || + !/(?:^|_)email_scheduling_e2e$/.test(url.pathname.slice(1)) + ) + throw new Error('invalid'); + } catch { + throw new Error( + 'EMAIL_SCHEDULING_E2E_DATABASE_URL must name a dedicated *_email_scheduling_e2e PostgreSQL database on loopback', + ); + } + + const credentials = {} as EmailSchedulingE2EConfig['credentials']; + for (const actor of ['customer', 'specialist', 'outsider'] as const) { + const emailKey = `EMAIL_SCHEDULING_E2E_${actor.toUpperCase()}_EMAIL`; + const passwordKey = `EMAIL_SCHEDULING_E2E_${actor.toUpperCase()}_PASSWORD`; + const email = env[emailKey]?.trim().toLowerCase(); + const password = env[passwordKey]; + if (!email || !/^[^\s@]+@[a-z0-9.-]+\.test$/.test(email)) { + throw new Error(`${emailKey} must be a reserved .test email address`); + } + if (!password || password.length < 6 || !password.trim()) { + throw new Error(`${passwordKey} must contain at least 6 characters`); + } + const [local, domain] = email.split('@'); + credentials[actor] = { + email: namespace === 'http' ? `${local}+http@${domain}` : email, + password, + }; + } + if ( + new Set(Object.values(credentials).map(({ email }) => email)).size !== 3 + ) { + throw new Error('E2E emails must be distinct'); + } + return { databaseUrl: databaseUrl!, namespace, credentials }; +} + +async function assertBaseOwnership( + tx: Prisma.TransactionClient, + fixture: Fixtures, + config?: EmailSchedulingE2EConfig, +) { + for (const expected of fixture.users) { + const user = await tx.user.findUnique({ + where: { id: expected.id }, + select: { + name: true, + surname: true, + rg: true, + role: true, + email: true, + address_id: true, + consultant_id: true, + company_id: true, + calendly_url: true, + calendly_user_uri: true, + calendly_organization_uri: true, + calendly_connection: { select: { user_id: true } }, + }, + }); + if (!user) continue; + if ( + user.name !== expected.name || + user.surname !== expected.surname || + user.rg !== expected.rg || + user.role !== expected.role || + (config && user.email !== config.credentials[expected.actor].email) || + user.address_id || + user.consultant_id || + user.company_id || + user.calendly_url || + user.calendly_user_uri || + user.calendly_organization_uri || + user.calendly_connection + ) { + throw new Error( + 'Refusing to reset a fixture user with unexpected ownership or relationships', + ); + } + } + for (const expected of fixture.cars) { + const car = await tx.car.findUnique({ + where: { id: expected.id }, + select: { + identificador: true, + specialist_id: true, + marca: true, + modelo: true, + }, + }); + if ( + car && + (car.identificador !== expected.identificador || + car.specialist_id !== expected.specialist_id || + car.marca !== expected.marca || + car.modelo !== expected.modelo) + ) { + throw new Error( + 'Refusing to reset a fixture product with unexpected ownership', + ); + } + } +} + +async function cleanupInTransaction( + tx: Prisma.TransactionClient, + fixture: Fixtures, +) { + await assertBaseOwnership(tx, fixture); + const userIds = fixture.users.map(({ id }) => id); + const carIds = fixture.cars.map(({ id }) => id); + const appointments = await tx.appointment.findMany({ + where: { + OR: [ + { client_id: { in: userIds } }, + { specialist_id: { in: userIds } }, + { product_id: { in: carIds } }, + ], + }, + include: { process: { select: { id: true } } }, + }); + const appointmentIds = appointments.map(({ id }) => id); + const processes = await tx.process.findMany({ + where: { + OR: [ + { client_id: { in: userIds } }, + { specialist_id: { in: userIds } }, + { car_id: { in: carIds } }, + { product_id: { in: carIds } }, + { appointment_id: { in: appointmentIds } }, + ], + }, + include: { + appointment: { select: { id: true } }, + ProcessStatusHistory: true, + meeting_session: { select: { id: true } }, + _count: { + select: { + contracts: true, + proposals: true, + products: true, + rejections: true, + }, + }, + }, + }); + // All candidates are checked before the first delete. Unexpected cross-links + // abort the whole reset, even when only one side matches a deterministic ID. + for (const appointment of appointments) { + const process = processes.find(({ id }) => id === appointment.process?.id); + if ( + appointment.client_id !== fixture.users[0].id || + appointment.specialist_id !== fixture.users[1].id || + appointment.product_type !== 'CAR' || + !appointment.product_id || + !carIds.includes(appointment.product_id) || + appointment.scheduling_method !== 'EMAIL' || + !['PENDING', 'SCHEDULED'].includes(appointment.status) || + appointment.calendly_event_uri || + appointment.calendly_invitee_uri || + !process || + process.appointment_id !== appointment.id + ) { + throw new Error( + 'Refusing cleanup: unexpected appointment ownership, method or link', + ); + } + } + for (const process of processes) { + const appointment = appointments.find( + ({ id }) => id === process.appointment_id, + ); + if ( + process.client_id !== fixture.users[0].id || + process.specialist_id !== fixture.users[1].id || + process.product_type !== 'CAR' || + !process.car_id || + !carIds.includes(process.car_id) || + process.boat_id || + process.aircraft_id || + (process.product_id && process.product_id !== process.car_id) || + process.status !== 'SCHEDULING' || + !appointment || + appointment.product_id !== process.car_id || + process.meeting_session || + process.active_contract_id || + process.accepted_proposal_id || + Object.values(process._count).some((count) => count !== 0) || + process.ProcessStatusHistory.some( + (history) => + history.status !== 'SCHEDULING' || + history.reason !== null || + (history.changed_by !== null && + !userIds.includes(history.changed_by)), + ) + ) { + throw new Error( + 'Refusing cleanup: unexpected process ownership or downstream data', + ); + } + } + const processIds = processes.map(({ id }) => id); + await tx.processStatusHistory.deleteMany({ + where: { processId: { in: processIds } }, + }); + await tx.process.deleteMany({ where: { id: { in: processIds } } }); + await tx.appointment.deleteMany({ where: { id: { in: appointmentIds } } }); + await tx.refreshToken.deleteMany({ where: { user_id: { in: userIds } } }); +} + +export async function cleanupEmailSchedulingFixtures( + prisma: PrismaClient, + fixture: Fixtures, +) { + await prisma.$transaction((tx) => cleanupInTransaction(tx, fixture), { + isolationLevel: 'Serializable', + }); +} + +export async function seedEmailSchedulingFixtures( + prisma: PrismaClient, + config: EmailSchedulingE2EConfig, + fixture: Fixtures, +) { + if (config.namespace !== fixture.namespace) + throw new Error('Fixture namespace mismatch'); + const hashes: Record = { + customer: await bcrypt.hash(config.credentials.customer.password, 10), + specialist: await bcrypt.hash(config.credentials.specialist.password, 10), + outsider: await bcrypt.hash(config.credentials.outsider.password, 10), + }; + await prisma.$transaction( + async (tx) => { + await assertBaseOwnership(tx, fixture, config); + await cleanupInTransaction(tx, fixture); + for (const user of fixture.users) { + const { actor, ...fields } = user; + const data = { + ...fields, + email: config.credentials[actor].email, + password_hash: hashes[actor], + is_active: true, + deactivated_at: null, + deactivated_by: null, + calendly_url: null, + calendly_user_uri: null, + calendly_organization_uri: null, + }; + await tx.user.upsert({ + where: { id: user.id }, + create: data, + update: data, + }); + } + for (const [index, car] of fixture.cars.entries()) { + const data = { + ...car, + is_active: true, + deactivated_at: null, + valor: 100000 + index * 10000, + currency: 'BRL' as const, + estado: 'SP', + ano: 2026, + descricao: + 'Produto sintético para o fluxo de reunião por e-mail E2E.', + }; + await tx.car.upsert({ + where: { id: car.id }, + create: data, + update: data, + }); + } + }, + { timeout: 15_000, isolationLevel: 'Serializable' }, + ); +} + +async function main() { + // Validate before importing or constructing Prisma. Never echo the URL, + // credential values, Prisma error metadata or fixture contacts to logs. + const config = readEmailSchedulingE2EConfig(process.env); + const { PrismaClient } = await import('@prisma/client'); + const prisma = new PrismaClient({ + datasources: { db: { url: config.databaseUrl } }, + }); + try { + await seedEmailSchedulingFixtures( + prisma, + config, + emailSchedulingFixtures('browser'), + ); + console.log( + 'Email scheduling E2E fixtures ready: 3 users, 2 products (browser namespace).', + ); + } finally { + await prisma.$disconnect(); + } +} + +if (require.main === module) { + main().catch(() => { + console.error( + 'Email scheduling E2E seed failed. Check local database, required test variables and fixture ownership; no credentials logged.', + ); + process.exitCode = 1; + }); +} diff --git a/backend/test/email-scheduling.e2e-spec.ts b/backend/test/email-scheduling.e2e-spec.ts new file mode 100644 index 0000000..92e5283 --- /dev/null +++ b/backend/test/email-scheduling.e2e-spec.ts @@ -0,0 +1,799 @@ +import type { INestApplication } from '@nestjs/common'; +import type { PrismaClient } from '@prisma/client'; +import cookieParser from 'cookie-parser'; +import request from 'supertest'; +import { + cleanupEmailSchedulingFixtures, + emailSchedulingFixtures, + readEmailSchedulingE2EConfig, + seedEmailSchedulingFixtures, +} from '../prisma/seed-email-scheduling-e2e'; + +const fixture = emailSchedulingFixtures('http'); +const proposedIso = '2099-10-20T17:30:00.000Z'; +const changedIso = '2099-10-21T19:00:00.000Z'; +const secondIso = '2099-10-23T17:30:00.000Z'; +const checkKeys = [ + 'exists', + 'appointment_id', + 'process_id', + 'appointment_status', + 'scheduling_method', + 'appointment_datetime', +]; + +// A dedicated URL opts in to the real PostgreSQL gate. Ordinary e2e discovery +// never falls back to a developer's DATABASE_URL or the application's .env. +const describeHttp = process.env.EMAIL_SCHEDULING_E2E_DATABASE_URL + ? describe + : describe.skip; + +describe('email scheduling fixture safety', () => { + const validEnv = { + EMAIL_SCHEDULING_E2E_DATABASE_URL: + 'postgresql://test:test@127.0.0.1:5432/email_scheduling_e2e', + EMAIL_SCHEDULING_E2E_CUSTOMER_EMAIL: 'customer@example.test', + EMAIL_SCHEDULING_E2E_CUSTOMER_PASSWORD: 'customer-test-password', + EMAIL_SCHEDULING_E2E_SPECIALIST_EMAIL: 'specialist@example.test', + EMAIL_SCHEDULING_E2E_SPECIALIST_PASSWORD: 'specialist-test-password', + EMAIL_SCHEDULING_E2E_OUTSIDER_EMAIL: 'outsider@example.test', + EMAIL_SCHEDULING_E2E_OUTSIDER_PASSWORD: 'outsider-test-password', + }; + + it('uses separate deterministic base IDs for browser seed and HTTP fixtures', () => { + const browser = emailSchedulingFixtures('browser'); + const baseIds = (items: typeof fixture) => [ + ...items.users.map(({ id }) => id), + ...items.cars.map(({ id }) => id), + ]; + expect(new Set([...baseIds(browser), ...baseIds(fixture)]).size).toBe(10); + expect(emailSchedulingFixtures('http')).toEqual(fixture); + }); + + it.each([ + undefined, + 'not-a-url', + 'postgresql://test:test@production.example.test:5432/database', + 'mysql://test:test@localhost:3306/database', + 'postgresql://test:test@localhost:5432/bmfluxdb', + ])('rejects a missing, malformed or nonlocal database URL', (databaseUrl) => { + expect(() => + readEmailSchedulingE2EConfig({ + ...validEnv, + EMAIL_SCHEDULING_E2E_DATABASE_URL: databaseUrl, + }), + ).toThrow(/EMAIL_SCHEDULING_E2E_DATABASE_URL/); + }); + + it('requires environment credentials and only reserved .test recipients', () => { + expect(() => + readEmailSchedulingE2EConfig({ + ...validEnv, + EMAIL_SCHEDULING_E2E_CUSTOMER_PASSWORD: undefined, + }), + ).toThrow(/EMAIL_SCHEDULING_E2E_CUSTOMER_PASSWORD/); + expect(() => + readEmailSchedulingE2EConfig({ + ...validEnv, + EMAIL_SCHEDULING_E2E_CUSTOMER_EMAIL: 'customer@example.com', + }), + ).toThrow(/EMAIL_SCHEDULING_E2E_CUSTOMER_EMAIL/); + expect(() => + readEmailSchedulingE2EConfig({ + ...validEnv, + EMAIL_SCHEDULING_E2E_OUTSIDER_EMAIL: + validEnv.EMAIL_SCHEDULING_E2E_CUSTOMER_EMAIL, + }), + ).toThrow(/distinct/i); + }); + + it('normalizes addresses and derives a separate HTTP login namespace', () => { + const config = readEmailSchedulingE2EConfig( + { + ...validEnv, + EMAIL_SCHEDULING_E2E_CUSTOMER_EMAIL: ' CUSTOMER@EXAMPLE.TEST ', + }, + 'http', + ); + expect(config.credentials.customer.email).toBe( + 'customer+http@example.test', + ); + expect(config.namespace).toBe('http'); + }); +}); + +describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { + let app: INestApplication | undefined; + let prisma: PrismaClient | undefined; + let config: ReturnType; + let fixtureReady = false; + let customerToken: string; + let specialistToken: string; + let outsiderToken: string; + const oldDatabaseUrl = process.env.DATABASE_URL; + const oldNotificationsEnabled = process.env.NOTIFICATIONS_ENABLED; + + beforeAll(async () => { + config = readEmailSchedulingE2EConfig(process.env, 'http'); + for (const name of [ + 'JWT_SECRET_ACCESS', + 'JWT_SECRET_REFRESH', + 'JWT_SECRET_REFERRAL', + 'JWT_SECRET_ADVISOR', + ]) { + if (!process.env[name]?.trim()) throw new Error(`Missing ${name}`); + } + process.env.DATABASE_URL = config.databaseUrl; + process.env.NOTIFICATIONS_ENABLED = 'false'; + const { PrismaClient } = + require('@prisma/client') as typeof import('@prisma/client'); + prisma = new PrismaClient({ + datasources: { db: { url: config.databaseUrl } }, + }); + await prisma.$connect(); + await seedEmailSchedulingFixtures(prisma, config, fixture); + fixtureReady = true; + await seedEmailSchedulingFixtures(prisma, config, fixture); + expect( + await prisma.user.count({ + where: { id: { in: fixture.users.map(({ id }) => id) } }, + }), + ).toBe(3); + expect( + await prisma.car.count({ + where: { id: { in: fixture.cars.map(({ id }) => id) } }, + }), + ).toBe(2); + + // Load the real application only after validating the isolated database. + // External delivery and unrelated background jobs are outside this gate. + const { AppModule } = + require('../src/app.module') as typeof import('../src/app.module'); + const { Test } = + require('@nestjs/testing') as typeof import('@nestjs/testing'); + const { ClassSerializerInterceptor, ValidationPipe } = + require('@nestjs/common') as typeof import('@nestjs/common'); + const { Reflector } = + require('@nestjs/core') as typeof import('@nestjs/core'); + const { PrismaService } = + require('../src/prisma/prisma.service') as typeof import('../src/prisma/prisma.service'); + const { S3Service } = + require('../src/aws/s3.service') as typeof import('../src/aws/s3.service'); + const { SesService } = + require('../src/aws/ses.service') as typeof import('../src/aws/ses.service'); + const { DocuSignClient } = + require('../src/providers/docusign/docusign.client') as typeof import('../src/providers/docusign/docusign.client'); + const { NotificationService } = + require('../src/features/notifications/notification.service') as typeof import('../src/features/notifications/notification.service'); + const { RateLimitGuard } = + require('../src/shared/guards/rate-limit.guard') as typeof import('../src/shared/guards/rate-limit.guard'); + const { ProductImportJobsService } = + require('../src/features/product-import-jobs/product-import-jobs.service') as typeof import('../src/features/product-import-jobs/product-import-jobs.service'); + const { ConsultantInviteJobsService } = + require('../src/features/office/consultant-invite-jobs.service') as typeof import('../src/features/office/consultant-invite-jobs.service'); + const { ClientInviteJobsService } = + require('../src/features/consultant/client-invite-jobs.service') as typeof import('../src/features/consultant/client-invite-jobs.service'); + const { MeetingReminderService } = + require('../src/features/meetings/meeting-reminder.service') as typeof import('../src/features/meetings/meeting-reminder.service'); + const { localizedValidationExceptionFactory } = + require('../src/shared/validation/localized-validation-exception') as typeof import('../src/shared/validation/localized-validation-exception'); + const module = await Test.createTestingModule({ + imports: [AppModule], + }) + .overrideProvider(PrismaService) + .useValue(prisma) + .overrideProvider(S3Service) + .useValue({}) + .overrideProvider(SesService) + .useValue({}) + .overrideProvider(DocuSignClient) + .useValue({}) + .overrideProvider(NotificationService) + .useValue({ sendAppointmentConfirmedEmail: async () => undefined }) + .overrideProvider(ProductImportJobsService) + .useValue({}) + .overrideProvider(ConsultantInviteJobsService) + .useValue({}) + .overrideProvider(ClientInviteJobsService) + .useValue({}) + .overrideProvider(MeetingReminderService) + .useValue({}) + // RateLimitGuard owns an interval with no destruction hook. Its login + // throttling is outside this gate; authentication itself is never stubbed. + .overrideGuard(RateLimitGuard) + .useValue({ canActivate: () => true }) + .compile(); + app = module.createNestApplication(); + app.use(cookieParser()); + app.setGlobalPrefix('api'); + app.useGlobalPipes( + new ValidationPipe({ + whitelist: true, + forbidNonWhitelisted: true, + transform: true, + exceptionFactory: localizedValidationExceptionFactory, + }), + ); + app.useGlobalInterceptors( + new ClassSerializerInterceptor(app.get(Reflector)), + ); + app.useLogger(false); + await app.init(); + + [customerToken, specialistToken, outsiderToken] = await Promise.all([ + login('customer'), + login('specialist'), + login('outsider'), + ]); + }, 30_000); + + afterAll(async () => { + try { + await app?.close(); + if (prisma && fixtureReady) { + await cleanupEmailSchedulingFixtures(prisma, fixture); + expect( + await prisma.appointment.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(0); + expect( + await prisma.process.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(0); + } + } finally { + await prisma?.$disconnect(); + if (oldDatabaseUrl === undefined) delete process.env.DATABASE_URL; + else process.env.DATABASE_URL = oldDatabaseUrl; + if (oldNotificationsEnabled === undefined) + delete process.env.NOTIFICATIONS_ENABLED; + else process.env.NOTIFICATIONS_ENABLED = oldNotificationsEnabled; + } + }); + + async function login(actor: 'customer' | 'specialist' | 'outsider') { + const response = await request(app!.getHttpServer()) + .post('/api/auth/login') + .send(config.credentials[actor]) + .expect(201); + expect(response.body.success).toBe(true); + expect(typeof response.body.data.access_token).toBe('string'); + expect(response.body.data.access_token.length > 0).toBe(true); + expect(response.body.data.user.id).toBe( + fixture.users.find((user) => user.actor === actor)!.id, + ); + expect( + Object.prototype.hasOwnProperty.call( + response.body.data.user, + 'password_hash', + ), + ).toBe(false); + const cookies = response.headers['set-cookie'] as unknown as + | string[] + | undefined; + expect( + Array.isArray(cookies) && + cookies.some((cookie) => cookie.startsWith('refreshToken=')), + ).toBe(true); + return response.body.data.access_token as string; + } + + function checkQuery(productId: string) { + return { + specialist_id: fixture.users[1].id, + product_type: 'CAR', + product_id: productId, + }; + } + + function pendingBody(productId: string, datetime = proposedIso) { + return { + client_id: fixture.users[0].id, + ...checkQuery(productId), + scheduling_method: 'EMAIL', + appointment_datetime: datetime, + }; + } + + function assertNoPrivateFields(value: unknown) { + const forbidden = new Set([ + 'cpf', + 'rg', + 'password_hash', + 'civil_state', + 'bank', + 'agency', + 'checking_account', + 'calendly_connection', + 'calendly_user_uri', + 'calendly_organization_uri', + 'access_token', + 'refresh_token', + ]); + const visit = (item: unknown) => { + if (!item || typeof item !== 'object') return; + for (const [key, child] of Object.entries(item)) { + expect(forbidden.has(key)).toBe(false); + visit(child); + } + }; + visit(value); + } + + function assertNoContacts(value: unknown) { + assertNoPrivateFields(value); + const serialized = JSON.stringify(value); + for (const actor of ['customer', 'specialist', 'outsider'] as const) { + expect(serialized.includes(config.credentials[actor].email)).toBe(false); + } + for (const user of fixture.users) { + expect(serialized.includes(user.phone)).toBe(false); + } + } + + async function assertStoredState( + productId: string, + processId: string, + appointmentId: string, + status: 'PENDING' | 'SCHEDULED', + datetime: string, + ) { + const appointments = await prisma!.appointment.findMany({ + where: { + client_id: fixture.users[0].id, + specialist_id: fixture.users[1].id, + product_id: productId, + }, + }); + const processes = await prisma!.process.findMany({ + where: { + client_id: fixture.users[0].id, + specialist_id: fixture.users[1].id, + car_id: productId, + }, + include: { ProcessStatusHistory: true }, + }); + expect(appointments).toHaveLength(1); + expect(processes).toHaveLength(1); + expect(appointments[0]).toMatchObject({ + id: appointmentId, + status, + scheduling_method: 'EMAIL', + appointment_datetime: new Date(datetime), + specialist_rescheduled_at: null, + specialist_rescheduled_from: null, + confirmed_by_id: status === 'SCHEDULED' ? fixture.users[1].id : null, + }); + expect(appointments[0].confirmed_at === null).toBe(status === 'PENDING'); + expect(processes[0]).toMatchObject({ + id: processId, + appointment_id: appointmentId, + status: 'SCHEDULING', + }); + expect(processes[0].ProcessStatusHistory).toHaveLength(1); + expect(processes[0].ProcessStatusHistory[0].status).toBe('SCHEDULING'); + return processes[0]; + } + + it('serves only the public business profile and blocks private profile IDOR', async () => { + const profile = await request(app!.getHttpServer()) + .get(`/api/specialists/${fixture.users[1].id}/public-profile`) + .expect(200); + expect(Object.keys(profile.body).sort()).toEqual( + [ + 'id', + 'name', + 'surname', + 'email', + 'speciality', + 'calendly_url', + 'calendly_scheduling_available', + ].sort(), + ); + expect(profile.body).toMatchObject({ + id: fixture.users[1].id, + email: config.credentials.specialist.email, + calendly_url: null, + calendly_scheduling_available: false, + }); + assertNoPrivateFields(profile.body); + expect(profile.body).not.toHaveProperty('phone'); + await request(app!.getHttpServer()) + .get(`/api/users/${fixture.users[0].id}`) + .expect(401); + const unchangedProfile = { + id: true, + name: true, + surname: true, + phone: true, + calendly_url: true, + updated_at: true, + } as const; + const before = await prisma!.user.findUniqueOrThrow({ + where: { id: fixture.users[0].id }, + select: unchangedProfile, + }); + for (const token of [specialistToken, outsiderToken]) { + const deniedGet = await request(app!.getHttpServer()) + .get(`/api/users/${fixture.users[0].id}`) + .auth(token, { type: 'bearer' }) + .expect(403); + assertNoContacts(deniedGet.body); + const deniedPatch = await request(app!.getHttpServer()) + .patch(`/api/users/${fixture.users[0].id}`) + .auth(token, { type: 'bearer' }) + .send({ name: 'IDOR should never be written' }) + .expect(403); + assertNoContacts(deniedPatch.body); + } + expect( + await prisma!.user.findUniqueOrThrow({ + where: { id: before.id }, + select: unchangedProfile, + }), + ).toEqual(before); + await request(app!.getHttpServer()) + .get(`/api/users/${fixture.users[0].id}`) + .auth(customerToken, { type: 'bearer' }) + .expect(200); + }); + + it('derives own-check identity from JWT and rejects query identity/other roles', async () => { + const own = await request(app!.getHttpServer()) + .get('/api/appointments/check') + .auth(customerToken, { type: 'bearer' }) + .query(checkQuery(fixture.cars[0].id)) + .expect(200); + expect(own.body.data).toEqual({ exists: false }); + assertNoContacts(own.body); + await request(app!.getHttpServer()) + .get('/api/appointments/check') + .query(checkQuery(fixture.cars[0].id)) + .expect(401); + await request(app!.getHttpServer()) + .get('/api/appointments/check') + .auth(customerToken, { type: 'bearer' }) + .query({ + ...checkQuery(fixture.cars[0].id), + client_id: fixture.users[2].id, + }) + .expect(400); + for (const token of [specialistToken, outsiderToken]) { + const denied = await request(app!.getHttpServer()) + .get('/api/appointments/check') + .auth(token, { type: 'bearer' }) + .query(checkQuery(fixture.cars[0].id)) + .expect(403); + assertNoContacts(denied.body); + } + }); + + it('rejects invalid creation, identity substitution and PLATFORM bypass without writes', async () => { + const body = pendingBody(fixture.cars[0].id); + const { appointment_datetime: _date, ...withoutDate } = body; + for (const invalid of [ + withoutDate, + { ...body, appointment_datetime: '2000-01-01T00:00:00.000Z' }, + { ...body, appointment_datetime: '2099-10-20T17:30' }, + ]) { + await request(app!.getHttpServer()) + .post('/api/appointments/pending') + .auth(customerToken, { type: 'bearer' }) + .send(invalid) + .expect(400); + } + for (const [token, requestBody] of [ + [customerToken, { ...body, client_id: fixture.users[2].id }], + [outsiderToken, body], + ] as const) { + const denied = await request(app!.getHttpServer()) + .post('/api/appointments/pending') + .auth(token, { type: 'bearer' }) + .send(requestBody) + .expect(403); + assertNoContacts(denied.body); + } + const { scheduling_method: _method, ...directBody } = body; + await request(app!.getHttpServer()) + .post('/api/appointments') + .auth(customerToken, { type: 'bearer' }) + .send(directBody) + .expect(403); + const calendly = await request(app!.getHttpServer()) + .post('/api/appointments/pending') + .auth(customerToken, { type: 'bearer' }) + .send({ ...withoutDate, scheduling_method: 'CALENDLY' }) + .expect(409); + expect(calendly.body.error.code).toBe('CALENDLY_UNAVAILABLE'); + assertNoContacts(calendly.body); + expect( + await prisma!.appointment.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(0); + expect( + await prisma!.process.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(0); + }); + + it('creates two dated proposals, projects assigned contacts, and confirms changed/unchanged times', async () => { + const created = [] as { + appointmentId: string; + processId: string; + productId: string; + }[]; + for (const car of fixture.cars) { + const response = await request(app!.getHttpServer()) + .post('/api/appointments/pending') + .auth(customerToken, { type: 'bearer' }) + .send(pendingBody(car.id)) + .expect(201); + expect(response.body.data).toMatchObject({ + id: expect.any(String), + process_id: expect.any(String), + status: 'PENDING', + scheduling_method: 'EMAIL', + appointment_datetime: proposedIso, + client: { id: fixture.users[0].id }, + specialist: { id: fixture.users[1].id }, + product: { id: car.id }, + }); + assertNoPrivateFields(response.body); + created.push({ + appointmentId: response.body.data.id, + processId: response.body.data.process_id, + productId: car.id, + }); + await assertStoredState( + car.id, + response.body.data.process_id, + response.body.data.id, + 'PENDING', + proposedIso, + ); + const own = await request(app!.getHttpServer()) + .get('/api/appointments/check') + .auth(customerToken, { type: 'bearer' }) + .query(checkQuery(car.id)) + .expect(200); + expect(Object.keys(own.body.data).sort()).toEqual([...checkKeys].sort()); + expect(own.body.data).toEqual({ + exists: true, + appointment_id: response.body.data.id, + process_id: response.body.data.process_id, + appointment_status: 'PENDING', + scheduling_method: 'EMAIL', + appointment_datetime: proposedIso, + }); + assertNoContacts(own.body); + const duplicate = await request(app!.getHttpServer()) + .post('/api/appointments/pending') + .auth(customerToken, { type: 'bearer' }) + .send(pendingBody(car.id)) + .expect(409); + expect(duplicate.body.error.code).toBe('ACTIVE_PROCESS_EXISTS'); + const { exists: _exists, ...snapshot } = own.body.data; + expect(duplicate.body.error.details).toEqual({ + existing_request: snapshot, + }); + assertNoContacts(duplicate.body); + await assertStoredState( + car.id, + response.body.data.process_id, + response.body.data.id, + 'PENDING', + proposedIso, + ); + } + + for (const { processId } of created) { + const detail = await request(app!.getHttpServer()) + .get(`/api/processes/${processId}`) + .auth(specialistToken, { type: 'bearer' }) + .expect(200); + expect(detail.body.data.client).toEqual({ + id: fixture.users[0].id, + name: fixture.users[0].name, + email: config.credentials.customer.email, + phone: fixture.users[0].phone, + }); + assertNoPrivateFields(detail.body); + const customer = await request(app!.getHttpServer()) + .get(`/api/processes/${processId}`) + .auth(customerToken, { type: 'bearer' }) + .expect(200); + expect(customer.body.data.client).not.toHaveProperty('email'); + expect(customer.body.data.client.phone).toBeNull(); + expect(customer.body.data.specialist.phone).toBeNull(); + assertNoContacts(customer.body); + const outsider = await request(app!.getHttpServer()) + .get(`/api/processes/${processId}`) + .auth(outsiderToken, { type: 'bearer' }) + .expect(403); + assertNoContacts(outsider.body); + for (const token of [customerToken, outsiderToken]) { + await request(app!.getHttpServer()) + .post(`/api/processes/${processId}/confirm-appointment`) + .auth(token, { type: 'bearer' }) + .send({ appointment_datetime: changedIso }) + .expect(403); + } + } + const privateAppointment = await request(app!.getHttpServer()) + .get(`/api/appointments/${created[0].appointmentId}`) + .auth(outsiderToken, { type: 'bearer' }) + .expect(403); + assertNoContacts(privateAppointment.body); + const assignedList = await request(app!.getHttpServer()) + .get(`/api/processes/specialist/${fixture.users[1].id}`) + .auth(specialistToken, { type: 'bearer' }) + .expect(200); + expect(assignedList.body.data).toHaveLength(2); + for (const process of assignedList.body.data) { + expect(process.client.email).toBe(config.credentials.customer.email); + expect(process.client.phone).toBe(fixture.users[0].phone); + } + const forbiddenList = await request(app!.getHttpServer()) + .get(`/api/processes/specialist/${fixture.users[1].id}`) + .auth(outsiderToken, { type: 'bearer' }) + .expect(403); + assertNoContacts(forbiddenList.body); + const emptyList = await request(app!.getHttpServer()) + .get(`/api/processes/specialist/${fixture.users[2].id}`) + .auth(outsiderToken, { type: 'bearer' }) + .expect(200); + expect(emptyList.body.data).toEqual([]); + assertNoContacts(emptyList.body); + + const confirm = (processId: string, datetime: string) => + request(app!.getHttpServer()) + .post(`/api/processes/${processId}/confirm-appointment`) + .auth(specialistToken, { type: 'bearer' }) + .send({ appointment_datetime: datetime }); + const first = await confirm(created[0].processId, changedIso).expect(201); + expect(first.body.data).toEqual({ + processId: created[0].processId, + status: 'SCHEDULING', + appointment_status: 'SCHEDULED', + appointment_datetime: changedIso, + }); + assertNoContacts(first.body); + const firstStored = await assertStoredState( + created[0].productId, + created[0].processId, + created[0].appointmentId, + 'SCHEDULED', + changedIso, + ); + expect(firstStored.notes).toContain(`proposta: ${proposedIso}`); + expect(firstStored.notes).toContain(`horário confirmado: ${changedIso}`); + + // A confirmed commitment conflicts; a still-pending EMAIL proposal did not. + const conflict = await confirm(created[1].processId, changedIso).expect( + 409, + ); + assertNoContacts(conflict.body); + expect(Object.keys(conflict.body.error.details)).toEqual([ + 'suggested_times', + ]); + for (const item of created) { + expect(JSON.stringify(conflict.body).includes(item.appointmentId)).toBe( + false, + ); + expect(JSON.stringify(conflict.body).includes(item.processId)).toBe( + false, + ); + } + await assertStoredState( + created[1].productId, + created[1].processId, + created[1].appointmentId, + 'PENDING', + proposedIso, + ); + + // The second product confirms its original suggestion without changing it. + const second = await confirm(created[1].processId, proposedIso).expect(201); + expect(second.body.data.appointment_datetime).toBe(proposedIso); + await assertStoredState( + created[1].productId, + created[1].processId, + created[1].appointmentId, + 'SCHEDULED', + proposedIso, + ); + const beforeRepeat = await prisma!.process.findUniqueOrThrow({ + where: { id: created[0].processId }, + }); + await confirm(created[0].processId, changedIso).expect(201); + expect( + await prisma!.process.findUniqueOrThrow({ + where: { id: created[0].processId }, + }), + ).toEqual(beforeRepeat); + await confirm(created[0].processId, secondIso).expect(400); + + for (const item of created) { + const confirmed = await request(app!.getHttpServer()) + .get(`/api/processes/${item.processId}`) + .auth(specialistToken, { type: 'bearer' }) + .expect(200); + expect(confirmed.body.data.status).toBe('SCHEDULING'); + expect(confirmed.body.data.appointment_status).toBe('SCHEDULED'); + expect(confirmed.body.data.client.email).toBe( + config.credentials.customer.email, + ); + expect(confirmed.body.data.client.phone).toBe(fixture.users[0].phone); + const own = await request(app!.getHttpServer()) + .get('/api/appointments/check') + .auth(customerToken, { type: 'bearer' }) + .query(checkQuery(item.productId)) + .expect(200); + expect(Object.keys(own.body.data).sort()).toEqual([...checkKeys].sort()); + expect(own.body.data.appointment_status).toBe('SCHEDULED'); + assertNoContacts(own.body); + } + expect( + await prisma!.appointment.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(2); + expect( + await prisma!.process.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(2); + }, 30_000); + + it('aborts cleanup before deleting anything when a fixture has a foreign participant', async () => { + const sentinel = { + id: '8c26e2a3-fd13-447a-9b6c-000000000901', + client_id: fixture.users[0].id, + specialist_id: fixture.users[2].id, + product_id: fixture.cars[0].id, + product_type: 'CAR' as const, + scheduling_method: 'EMAIL' as const, + }; + const before = { + appointments: await prisma!.appointment.count({ + where: { client_id: fixture.users[0].id }, + }), + processes: await prisma!.process.count({ + where: { client_id: fixture.users[0].id }, + }), + }; + // Fixed test-owned ID; create fails on collision and never deletes a row + // that existed before this test. The invalid participant is intentional. + await prisma!.appointment.create({ + data: { + ...sentinel, + status: 'PENDING', + appointment_datetime: new Date(secondIso), + }, + }); + try { + await expect( + cleanupEmailSchedulingFixtures(prisma!, fixture), + ).rejects.toThrow(/Refusing cleanup/); + expect( + await prisma!.appointment.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(before.appointments + 1); + expect( + await prisma!.process.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(before.processes); + expect(await prisma!.appointment.count({ where: sentinel })).toBe(1); + } finally { + // Only the exact row created above may be removed; no cascade or broad + // fixture reset is used to recover from the deliberate integrity failure. + await prisma!.appointment.deleteMany({ where: sentinel }); + } + }); +}); diff --git a/backend/test/jest-e2e.json b/backend/test/jest-e2e.json index e9d912f..50f8efa 100644 --- a/backend/test/jest-e2e.json +++ b/backend/test/jest-e2e.json @@ -3,6 +3,9 @@ "rootDir": ".", "testEnvironment": "node", "testRegex": ".e2e-spec.ts$", + "moduleNameMapper": { + "^src/(.*)$": "/../src/$1" + }, "transform": { "^.+\\.(t|j)s$": "ts-jest" } diff --git a/docs/docs/agendamento-sem-calendly.md b/docs/docs/agendamento-sem-calendly.md index 1536650..70b32d9 100644 --- a/docs/docs/agendamento-sem-calendly.md +++ b/docs/docs/agendamento-sem-calendly.md @@ -3,344 +3,104 @@ sidebar_position: 6 title: Agendamento sem Calendly --- -# Agendamento sem Calendly — especificação de design +# Agendamento sem Calendly por e-mail -**Data:** 14 de setembro de 2026 -**Status:** aprovado para planejamento -**Escopo:** cadastro de produtos e início de negociação quando o especialista não possui Calendly conectado +Sem Calendly ativo, o cliente usa **Solicitar reunião**, propõe uma data e hora futura e registra um pedido pendente. O especialista atribuído pode confirmar a sugestão ou **Alterar e confirmar**. A confirmação reserva o horário; o processo continua em `SCHEDULING` para permitir a reunião. -## 1. Objetivo +Conectar Calendly é opcional e não bloqueia cadastro, edição ou publicação de produtos. A capacidade `calendly_scheduling_available` vem do backend: exige uma URL HTTPS do domínio Calendly e uma conexão OAuth ativa. Uma URL residual, sozinha, não ativa esse caminho. -Permitir que especialistas operem normalmente sem uma conta Calendly e oferecer ao cliente duas formas simples de iniciar uma negociação: +## Fluxo do cliente -1. entrar em contato livremente por e-mail e combinar o horário fora da plataforma; ou -2. escolher uma data e hora diretamente na plataforma. +1. Entre como cliente, abra o produto e escolha **Solicitar reunião**. +2. Informe a data e hora futura no modal. A interface mostra o fuso local; a API recebe e armazena um instante UTC em ISO 8601. +3. Após a criação, a página mostra o sucesso e tenta abrir o aplicativo padrão de e-mail com destinatário, assunto e corpo sugeridos. O pedido já está salvo como `PENDING/EMAIL`, com o horário proposto, junto ao processo `SCHEDULING`. +4. Use os fallbacks **Abrir aplicativo de e-mail**, **Abrir no Gmail**, **Copiar e-mail** ou **Acompanhar processo**. Eles continuam disponíveis após recarregar ou revisitar o produto enquanto o próprio pedido está pendente. -O Calendly continua disponível como conveniência, mas deixa de ser requisito para cadastrar produtos ou receber solicitações. +A abertura automática ocorre no máximo uma vez por pedido recém-criado. Reload, revisita e recuperação de duplicidade restauram o painel sem repetir essa tentativa. Falha do navegador, ausência de aplicativo padrão ou indisponibilidade do clipboard não desfazem o pedido; o endereço permanece visível e selecionável. -## 2. Estado atual e problemas encontrados +O assunto e o corpo são editáveis no compositor externo. A plataforma não captura nem persiste essas edições e não comprova que um e-mail foi enviado. Um `mailto:` ou link Gmail válido demonstra apenas que a composição foi preparada. Uma falha na criação não abre o compositor. -O sistema já possui boa parte da infraestrutura necessária: +## Fluxo do especialista -- `Appointment` registra data, participantes e estado do agendamento; -- `Process` representa o processo comercial e nasce em `SCHEDULING`; -- o backend já valida conflitos de horário e consegue criar `Appointment` e `Process` atomicamente; -- a página de produto já possui um fallback que cria uma solicitação pendente e abre um `mailto:`; -- a área de processos já possui a sala de reunião interna e ações para iniciar e entrar em uma reunião; -- existe um modal global dispensável que incentiva o especialista a conectar o Calendly. +No processo pendente por e-mail, o especialista atribuído vê a proposta, o e-mail do cliente e seu telefone, quando preenchido. Um número brasileiro normalizável também produz um atalho WhatsApp. Telefone ausente não produz ação; telefone inválido permanece como texto, sem link incorreto. -Entretanto, o comportamento atual não atende integralmente ao objetivo: +- **Confirmar horário** envia o instante proposto ao endpoint canônico do processo. +- **Alterar e confirmar** abre o seletor com a proposta existente e envia o horário escolhido. Sem edição efetiva, o instante ISO original é preservado. -- `ProductFormPage` substitui o formulário por um bloqueio quando o especialista não tem Calendly; -- o modal global afirma que a negociação fica bloqueada sem Calendly; -- o cliente sem Calendly só recebe a opção de e-mail; -- não existe interface ativa para o cliente escolher uma data e hora na plataforma; -- no fluxo de e-mail, a confirmação do especialista não exige o horário combinado; -- não existe controle explícito da única alteração de horário permitida ao especialista; -- o endpoint direto de agendamento precisa garantir que o usuário autenticado seja o próprio cliente informado. +Ambas as ações resultam em `Appointment=SCHEDULED` e `Process=SCHEDULING`. A primeira definição ou alteração antes da confirmação não consome a remarcação posterior: `specialist_rescheduled_at` e `specialist_rescheduled_from` continuam nulos. As notas preservam a proposta e o horário confirmado. O cliente passa a ver o horário efetivo, e os controles da reunião continuam disponíveis no processo. -## 3. Decisões de produto +Pedidos `PENDING/EMAIL` são propostas e não ocupam a agenda. A confirmação valida o conflito novamente sob trava de agenda. Se houver `409`, o especialista pode escolher outro horário no modal, que conserva a mensagem do erro. Dupla submissão do mesmo horário confirmado não cria registros ou histórico adicionais. -- Conectar o Calendly é opcional. -- A ausência ou indisponibilidade do Calendly nunca bloqueia criação, edição ou publicação de produtos. -- Um especialista com Calendly mantém o fluxo atual de agendamento. -- Um cliente que escolhe um produto de especialista sem Calendly pode optar por e-mail ou agendamento interno. -- Um horário escolhido pelo cliente na plataforma é confirmado imediatamente. -- No fluxo por e-mail, somente o especialista registra o horário acordado. -- Registrar o primeiro horário após a conversa por e-mail não conta como alteração. -- Depois que um horário está confirmado, o especialista pode alterá-lo uma única vez. -- A alteração feita pelo especialista é definitiva e não depende de aprovação do cliente. -- O MVP não restringe tecnicamente o início da sala a uma janela exata ao redor do horário; o horário é exibido e o especialista inicia a sala quando chega o momento. +A remarcação de um compromisso já confirmado continua sendo uma ação separada, permitida uma vez ao especialista responsável. Ela preenche os dois campos de auditoria. A reunião e o avanço comercial seguem o fluxo existente. -## 4. Abordagem escolhida +## Contratos e privacidade -A implementação evoluirá o fluxo atual, reutilizando `Appointment`, `Process`, as validações de agenda e a sala interna. +| Operação | Contrato | +|---|---| +| `POST /api/appointments/pending` | Cliente autenticado cria para si, com `scheduling_method=EMAIL`, produto/especialista e `appointment_datetime` futura. Retorna o appointment e o `process_id` criados atomicamente. | +| `GET /api/appointments/check` | Somente `CUSTOMER`; aceita `specialist_id`, `product_type` e `product_id`. A identidade vem do JWT; enviar `client_id` na query é inválido. | +| `POST /api/processes/:id/confirm-appointment` | Somente o especialista atribuído; aceita o horário sugerido ou outro futuro, confirma sob lock e mantém `SCHEDULING`. | +| `GET /api/specialists/:id/public-profile` | ID, nome comercial, especialidade, e-mail comercial, URL Calendly e booleano de capacidade. Não inclui documentos, telefone pessoal ou dados OAuth. | +| `GET/PATCH /api/users/:id` | Perfil privado: somente o próprio usuário ou `ADMIN`. Apenas especialista pode definir uma URL Calendly; `null` remove a URL. | -Não será criado um calendário completo de disponibilidade. Essa alternativa exigiria regras de jornada, recorrência, bloqueios e fuso horário que não são necessárias para o primeiro lançamento. +A consulta do próprio pedido retorna somente `{ exists: false }` ou `{ exists: true, appointment_id, process_id, appointment_status, scheduling_method, appointment_datetime }`, sem nomes ou contatos. Um pedido ativo duplicado responde `409/ACTIVE_PROCESS_EXISTS` com `error.details.existing_request` nesse mesmo formato mínimo, sem o discriminante `exists`. Outros conflitos não expõem IDs ou contatos do compromisso concorrente. -Também não haverá uma etapa de aprovação da sugestão do cliente: no agendamento interno, a seleção já cria um horário confirmado. +Os contatos do cliente aparecem na lista e no detalhe somente para o especialista atribuído ao pedido `PENDING/EMAIL` em `SCHEDULING` e continuam disponíveis para ele após a confirmação. Outros especialistas não podem listar ou abrir esse processo. As projeções de cliente não recebem os contatos privados nesse estado. O e-mail comercial do especialista é intencionalmente público para permitir a composição da mensagem. -## 5. Modelo de dados +O backend recusa a criação direta `SCHEDULED/PLATFORM` por `POST /api/appointments` nesse cenário. O caminho com Calendly ativo continua usando `CALENDLY` e não aceita horário enviado pelo cliente. A consultoria sem produto conserva o pedido `PENDING/EMAIL` sem data e exige sua definição na confirmação. Registros legados sem proposta continuam legíveis. `pending_expires_at` é metadado: não existe expiração automática nesta entrega. -### 5.1 Origem do agendamento +## Validação local repetível -Adicionar ao Prisma: +Use PostgreSQL local e o banco dedicado `bmfluxdb_email_scheduling_e2e`, com as migrations existentes aplicadas. A URL deve ser explícita, usar loopback (`localhost`, `127.0.0.1` ou `::1`) e nome de banco terminado em `email_scheduling_e2e`. O seed não carrega `.env` nem usa `DATABASE_URL` como fallback. -```prisma -enum AppointmentSchedulingMethod { - CALENDLY - EMAIL - PLATFORM -} -``` - -Adicionar a `Appointment`: - -```prisma -scheduling_method AppointmentSchedulingMethod? -specialist_rescheduled_at DateTime? -specialist_rescheduled_from DateTime? -``` - -`scheduling_method` será opcional para permitir uma migração aditiva sem classificar incorretamente registros históricos. Todos os novos agendamentos devem preenchê-lo explicitamente. - -`specialist_rescheduled_at` funciona como a trava da única alteração. `specialist_rescheduled_from` preserva o horário anterior para auditoria. - -Não é necessário um contador: campo vazio significa que a alteração ainda está disponível; campo preenchido significa que ela já foi consumida. - -### 5.2 Estados - -| Método | Criação | Quando passa a `SCHEDULED` | Processo | -|---|---|---|---| -| `CALENDLY` | `PENDING` | após sincronização/confirmação atual | permanece com o comportamento existente | -| `EMAIL` | `PENDING`, sem horário | quando o especialista registra o horário acordado | permanece em `SCHEDULING` até a reunião | -| `PLATFORM` | `SCHEDULED`, com horário | na própria criação | nasce em `SCHEDULING` | - -Confirmar um horário não significa concluir a reunião nem iniciar a negociação financeira. O processo continua em `SCHEDULING` enquanto a conversa ainda não aconteceu. - -## 6. Fluxos - -### 6.1 Especialista sem Calendly - -1. O especialista entra na área autenticada. -2. A plataforma consulta o estado da conexão Calendly. -3. Se não houver conexão ativa, exibe um modal informativo. -4. O especialista pode escolher `Conectar agora` ou `Continuar sem Calendly`. -5. Ao dispensar o modal, continua usando todas as funcionalidades, inclusive cadastro de produtos. -6. O modal não volta durante a mesma sessão do navegador. - -Falha na consulta do Calendly não bloqueia nenhuma tela. O formulário de produto deve ser renderizado independentemente do resultado dessa consulta. - -### 6.2 Cliente escolhe contato por e-mail - -1. Na página do produto, o cliente seleciona `Enviar e-mail`. -2. A plataforma cria `Appointment(PENDING, EMAIL)` e o `Process(SCHEDULING)` associado na mesma transação. -3. A plataforma abre um `mailto:` com destinatário, assunto e texto sugeridos, todos editáveis no cliente de e-mail. -4. A página redireciona para `Meus Processos` e informa que o horário será definido após o contato. -5. O especialista combina o horário com o cliente fora da plataforma. -6. No card do processo, o especialista escolhe `Definir data e hora`. -7. O backend valida e grava o horário, muda o agendamento para `SCHEDULED` e mantém o processo em `SCHEDULING`. -8. O cliente recebe uma notificação e passa a ver o horário no processo. - -Se o navegador não conseguir abrir o cliente de e-mail, a solicitação continua criada. A interface deve exibir o endereço do especialista com uma ação de copiar. - -### 6.3 Cliente escolhe data e hora na plataforma +Configure as variáveis na sessão local, sem salvar ou publicar credenciais: -1. Na página do produto, o cliente seleciona `Escolher data e hora`. -2. Um modal simples exibe um campo `datetime-local`, o fuso local do navegador e o botão `Confirmar agendamento`. -3. O frontend converte o valor local para ISO 8601 UTC. -4. O backend valida o usuário, o produto, o horário futuro, conflito de agenda e processo ativo duplicado. -5. A transação cria `Appointment(SCHEDULED, PLATFORM)` e `Process(SCHEDULING)`. -6. O cliente é redirecionado para `Meus Processos` com o horário confirmado. -7. O especialista é notificado sobre o novo agendamento. +- `EMAIL_SCHEDULING_E2E_DATABASE_URL`; +- `EMAIL_SCHEDULING_E2E_CUSTOMER_EMAIL` e `EMAIL_SCHEDULING_E2E_CUSTOMER_PASSWORD`; +- `EMAIL_SCHEDULING_E2E_SPECIALIST_EMAIL` e `EMAIL_SCHEDULING_E2E_SPECIALIST_PASSWORD`; +- `EMAIL_SCHEDULING_E2E_OUTSIDER_EMAIL` e `EMAIL_SCHEDULING_E2E_OUTSIDER_PASSWORD`; +- `JWT_SECRET_ACCESS`, `JWT_SECRET_REFRESH`, `JWT_SECRET_REFERRAL` e `JWT_SECRET_ADVISOR` para o HTTP E2E; `JWT_SECRET_PASSWORD_RESET` pode ser dedicado ou usar o fallback existente. -O cliente não escolhe a duração no MVP. Será usada a mesma janela de conflito de uma hora já adotada pelo backend. +Os três e-mails devem ser distintos e terminar em `.test`, domínio reservado para testes. As senhas exigem pelo menos seis caracteres e são armazenadas com bcrypt (custo 10). O seed não imprime URL, e-mails, senhas ou hashes. -### 6.4 Alteração única pelo especialista - -1. Um agendamento `SCHEDULED` com horário e `specialist_rescheduled_at` vazio exibe `Alterar horário` somente ao especialista responsável. -2. O especialista escolhe um novo horário futuro. -3. A interface avisa que essa será a única alteração e pede confirmação explícita. -4. O backend trava a agenda do especialista, revalida conflito excluindo o próprio agendamento e atualiza atomicamente: - - `specialist_rescheduled_from` com o horário vigente; - - `appointment_datetime` com o novo horário; - - `specialist_rescheduled_at` com o instante da operação. -5. O novo horário passa a valer imediatamente. -6. O cliente é notificado e a ação desaparece para o especialista. - -Uma segunda tentativa retorna `409 Conflict` com mensagem de que a alteração definitiva já foi utilizada. - -### 6.5 Reunião interna - -1. Enquanto o processo está em `SCHEDULING` e o agendamento está `SCHEDULED`, ambos veem o horário confirmado. -2. Ao chegar o momento, o especialista usa `Iniciar reunião`. -3. O cliente passa a ver `Entrar na reunião` assim que a sessão existir. -4. O encerramento da conversa segue o fluxo atual de avanço para negociação. - -## 7. Backend e contratos HTTP - -### 7.1 Criação direta - -Manter `POST /appointments` como operação de agendamento interno e endurecer suas regras: - -- aceitar somente usuário autenticado com papel `CUSTOMER`; -- exigir `req.user.id === client_id`; -- exigir `appointment_datetime` para esse fluxo; -- definir `scheduling_method = PLATFORM` no servidor; -- criar agendamento e processo na mesma transação; -- manter o processo em `SCHEDULING`. - -O cliente não poderá enviar outro `scheduling_method` nesse endpoint. - -### 7.2 Solicitação por e-mail - -`POST /appointments/pending` passa a aceitar `scheduling_method` apenas com os valores `EMAIL` ou `CALENDLY`. As chamadas da página de produto devem enviar o valor de forma explícita. - -Para reduzir risco de compatibilidade, chamadas antigas sem o campo continuam sendo tratadas como `CALENDLY` no serviço, mas o banco não aplica um default retroativo. - -### 7.3 Definição inicial pelo especialista - -Evoluir `POST /processes/:id/confirm-appointment` para aceitar: - -```json -{ - "appointment_datetime": "2026-09-20T17:00:00.000Z" -} +```sh +rtk docker compose up -d db +rtk docker compose exec -T db pg_isready -U user -d bmfluxdb +# Crie o banco dedicado antes de aplicar as migrations. +rtk env DATABASE_URL="$EMAIL_SCHEDULING_E2E_DATABASE_URL" DIRECT_URL="$EMAIL_SCHEDULING_E2E_DATABASE_URL" npm --prefix backend exec -- prisma migrate deploy +rtk npm --prefix backend run seed:email-scheduling-e2e +rtk node -e 'if (!process.env.EMAIL_SCHEDULING_E2E_DATABASE_URL) process.exit(1)' +rtk npm --prefix backend run test:e2e -- --runInBand --runTestsByPath test/email-scheduling.e2e-spec.ts --json --outputFile=/tmp/email-scheduling-http-e2e.json +rtk node -e 'const r=require("/tmp/email-scheduling-http-e2e.json");if(!r.success||r.numPendingTests!==0)process.exit(1)' ``` -Para `EMAIL`, a data é obrigatória. A operação: +O seed cria ou atualiza três usuários sintéticos e dois carros ativos atribuídos ao especialista sem Calendly. Os IDs-base são fixos: -- exige que o solicitante seja o especialista do processo; -- exige processo em `SCHEDULING` e agendamento em `PENDING`; -- valida data futura e conflito sob a trava já existente; -- muda o agendamento para `SCHEDULED`; -- não preenche os campos de reagendamento; -- não avança o processo para `NEGOTIATION`. +| Fixture | UUID no namespace de navegador | +|---|---| +| Cliente | `c848f474-6492-4ac1-8a7d-000000000001` | +| Especialista atribuído | `c848f474-6492-4ac1-8a7d-000000000002` | +| Especialista não atribuído | `c848f474-6492-4ac1-8a7d-000000000003` | +| Produto A | `c848f474-6492-4ac1-8a7d-000000000101` | +| Produto B | `c848f474-6492-4ac1-8a7d-000000000102` | -### 7.4 Reagendamento definitivo +O HTTP E2E usa outro prefixo, `8c26e2a3-fd13-447a-9b6c`, e deriva aliases `local+http@dominio.test` dos e-mails da sessão. Assim ele não limpa pedidos feitos com o seed de navegador. Ele inicializa o `AppModule` real, autentica as três identidades pelo login e usa guards, validação, serializer e prefixo reais. Somente fronteiras externas (SES/S3/DocuSign), recuperação de jobs e o timer de rate limit são neutralizados; autenticação, autorização, transações e persistência não são simuladas. Sem a URL explícita, o grupo HTTP é pulado; o gate dedicado exige zero testes pulados. -Adicionar `PATCH /appointments/:id/reschedule`: - -```json -{ - "appointment_datetime": "2026-09-21T19:00:00.000Z" -} -``` +O teste cobre criação pendente, identidade derivada do JWT, IDOR de GET/PATCH, bypass direto, contato autorizado na lista/detalhe, duplicidade, conflito sem PII, confirmação alterada e inalterada, idempotência e estados/cardinalidade no banco. O seed também é executado duas vezes pelo teste para comprovar a idempotência dos IDs-base. -Regras: +A limpeza resolve os IDs gerados de appointments/processes apenas a partir dos usuários/produtos determinísticos e valida ambos os participantes, método e vínculos antes de excluir qualquer registro. Histórico, processo e appointment são apagados nessa ordem dentro de uma transação; tokens são limitados aos usuários da fixture. Contrato, proposta, reunião, `Product` ou vínculo inesperado interrompem o reset integralmente. Usuários e carros são atualizados por ID; nunca são truncados ou apagados. Rodar novamente o seed reinicia somente os pedidos desse namespace. -- somente o especialista responsável; -- agendamento em `SCHEDULED`; -- horário atual existente; -- `specialist_rescheduled_at` ainda vazio; -- novo horário futuro e diferente do atual; -- ausência de conflito com outro agendamento do especialista; -- atualização atômica e protegida contra duas alterações concorrentes. +## Checklist de navegador e gates -## 8. Frontend +Inicie backend e frontend do source atual, apontando ambos para o banco dedicado. No backend, use `NOTIFICATIONS_ENABLED=false` para evitar entrega de notificações; no frontend, `VITE_API_BASE_URL=http://localhost:3000/api`. Use contextos independentes para cliente, especialista atribuído e usuário não atribuído. -### 8.1 `RequireCalendlyModal` +1. No produto A, crie a proposta futura e capture status/payload do POST e do check. Inspecione destinatário, assunto e corpo dos links `mailto:`/Gmail sem afirmar envio externo. +2. Recarregue e revisite o produto: os fallbacks persistem e não ocorre outra tentativa automática de abrir e-mail. +3. Como especialista atribuído, veja proposta, e-mail, telefone e WhatsApp; altere e confirme. Confirme `SCHEDULED`, processo `SCHEDULING` e controles da reunião. +4. Repita no produto B confirmando a sugestão sem alteração. +5. Como não atribuído, tente ler o processo/lista, confirmar e acessar/editar o perfil privado do cliente: as operações retornam `403`, sem contatos e sem alterações. +6. Repita o caminho crítico em viewport móvel e por teclado, observando foco, labels, anúncio de sucesso/erro e retorno de foco do modal. -- Trocar o texto que afirma haver bloqueio. -- Usar `Continuar sem Calendly` no lugar de `Lembrar mais tarde`. -- Manter o comportamento dispensável por sessão. +Após cada confirmação, consulte o banco em modo somente leitura usando os IDs-base acima e os IDs retornados pelo POST. Exija exatamente um appointment e um processo por produto, vínculo recíproco correto, `appointment_datetime` efetiva, `SCHEDULED/SCHEDULING` e ambos os campos de remarcação nulos. A aparência do navegador sozinha não comprova essas condições. -### 8.2 `ProductFormPage` - -- Remover o gate de Calendly. -- Não esperar a consulta da conexão para renderizar o formulário. -- O modal global continua responsável por recomendar a conexão. - -### 8.3 `ProductPage` - -- Manter o popup atual quando existe URL Calendly. -- Sem URL, apresentar duas ações claras: - - `Enviar e-mail`; - - `Escolher data e hora`. -- Reutilizar um modal de agendamento enxuto para o segundo caminho. -- Manter o tratamento de duplicidade e o redirecionamento para processos. - -### 8.4 `ProcessCard` - -- Para `EMAIL + PENDING`, substituir a confirmação sem horário por `Definir data e hora`. -- Para `SCHEDULED`, exibir o horário aos dois participantes. -- Exibir `Alterar horário` ao especialista apenas quando a alteração ainda estiver disponível. -- Após o reagendamento, exibir `Horário alterado definitivamente`. -- Manter o início da sala exclusivamente com o especialista; o cliente entra depois que a sessão é criada. - -## 9. Erros e mensagens - -| Situação | Resposta | Comportamento da interface | -|---|---|---| -| Horário passado | `400` | manter modal aberto e explicar que deve ser futuro | -| Conflito de agenda | `409` | manter modal aberto e pedir outro horário | -| Processo ativo duplicado | `409` | direcionar para o processo existente | -| Cliente agendando por outro usuário | `403` | negar sem criar registros | -| Usuário que não é o especialista tentando definir/alterar | `403` | negar sem alterar registros | -| Segunda alteração do especialista | `409` | informar que a alteração definitiva já foi usada | -| Falha no envio da notificação | operação continua | registrar erro; não reverter agendamento | -| Falha ao consultar Calendly | nenhuma restrição | manter produtos e alternativas disponíveis | -| Falha ao abrir `mailto:` | solicitação continua | mostrar e-mail copiável e link para processos | - -## 10. Notificações - -As notificações continuam assíncronas e não críticas, seguindo o padrão existente do `NotificationService`. - -- Agendamento interno criado: avisar o especialista com cliente, produto e horário. -- Horário do fluxo por e-mail definido: avisar o cliente. -- Horário alterado definitivamente: avisar o cliente, mostrando horário anterior e novo. - -Não será implementada resposta por e-mail, convite de calendário ou confirmação adicional no MVP. - -## 11. Segurança e concorrência - -- Toda decisão de autorização ocorre no backend; o frontend apenas oculta ações indisponíveis. -- O agendamento direto verifica a identidade do cliente autenticado. -- Definição e alteração do horário verificam o especialista vinculado ao processo/agendamento. -- A validação de produto continua exigindo produto ativo, do tipo correto e pertencente ao especialista. -- A trava de agenda do especialista é adquirida antes de verificar conflitos e escrever. -- A alteração única usa atualização condicional com `specialist_rescheduled_at: null`; duas requisições concorrentes não podem consumir a alteração duas vezes. -- Criação de `Appointment`, `Process` e histórico permanece atômica. - -## 12. Estratégia de testes - -### Frontend - -- `ProductFormPage` renderiza e envia o formulário mesmo sem Calendly. -- O modal Calendly é dispensável e comunica que a integração é opcional. -- `ProductPage` mantém Calendly quando conectado e mostra as duas alternativas quando desconectado. -- O modal interno converte corretamente a data local para UTC. -- O fluxo de e-mail cria solicitação antes de abrir `mailto:` e oferece fallback copiável. -- `ProcessCard` exige data na confirmação por e-mail. -- A ação de alterar horário aparece uma vez e desaparece após sucesso. - -### Backend - -- Cliente só agenda para si mesmo. -- Agendamento interno exige horário futuro e nasce `SCHEDULED/PLATFORM`. -- Solicitação por e-mail nasce `PENDING/EMAIL` sem horário. -- Apenas o especialista registra o primeiro horário do fluxo por e-mail. -- Definição inicial mantém o processo em `SCHEDULING` e não consome reagendamento. -- Primeira alteração grava horário anterior e instante da alteração. -- Segunda alteração retorna conflito. -- Requisições concorrentes permitem apenas uma alteração. -- Conflito de agenda, produto incorreto e processo duplicado continuam bloqueados. -- Falha ao criar o processo reverte o agendamento. -- Falha de notificação não reverte alterações confirmadas. -- Testes existentes do Calendly continuam passando. - -### Verificação integrada - -Validar manualmente com dois usuários, cliente e especialista sem Calendly: - -1. cadastrar um produto; -2. iniciar uma solicitação por e-mail e registrar o horário pelo especialista; -3. criar outro agendamento escolhendo o horário na plataforma; -4. alterar uma vez e confirmar que a segunda alteração é bloqueada; -5. iniciar e acessar a sala pelos dois participantes. - -## 13. Critérios de aceite - -- Especialista sem Calendly cadastra, edita e publica produtos sem bloqueio. -- O lembrete de Calendly pode ser fechado e não contém mensagem de bloqueio. -- Cliente de produto sem Calendly escolhe entre e-mail e data/hora interna. -- Os dois caminhos criam processo rastreável em `SCHEDULING`. -- O fluxo de e-mail só ganha horário quando o especialista o registra. -- O agendamento interno nasce confirmado. -- Ambos visualizam o horário vigente. -- O especialista consegue alterá-lo uma vez, com efeito imediato. -- A segunda alteração é recusada também sob concorrência. -- O cliente é notificado quando o especialista define ou altera o horário. -- A sala interna continua acessível pelo processo no momento combinado. -- O fluxo Calendly existente não sofre regressão. - -## 14. Fora de escopo - -- agenda de disponibilidade recorrente do especialista; -- bloqueio de feriados, horário comercial ou intervalos personalizados; -- aprovação do cliente após alteração; -- múltiplas propostas de reagendamento; -- integração com Google Calendar, Outlook ou convites `.ics`; -- abertura automática da sala exatamente no horário; -- escolha de duração pelo cliente; -- chat interno para substituir o e-mail. +O gate de concorrência PostgreSQL usa `POSTGRES_CONCURRENCY_TEST_URL` no banco dedicado e executa `src/features/appointments/appointments-concurrency.postgres.spec.ts` com `--runInBand`; confira zero skips no resultado JSON. Depois execute sequencialmente os testes/builds de backend e frontend e o lint. Limite Jest a dois workers ou `--runInBand`, Vitest a dois workers/forks, e verifique `rtk free -h` antes das suites amplas. Preserve somente evidência sem credenciais ou PII no repositório. From 84294770b7cbb86f52c7f13c6c2ae2e0f822dcba Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 11:19:10 -0300 Subject: [PATCH 16/60] test: harden email scheduling E2E gates --- backend/prisma/seed-email-scheduling-e2e.ts | 13 +-- backend/test/email-scheduling.e2e-spec.ts | 90 +++++++++++++++++---- backend/test/jest-e2e.json | 3 +- backend/test/mocks/isomorphic-dompurify.ts | 20 +++++ 4 files changed, 104 insertions(+), 22 deletions(-) create mode 100644 backend/test/mocks/isomorphic-dompurify.ts diff --git a/backend/prisma/seed-email-scheduling-e2e.ts b/backend/prisma/seed-email-scheduling-e2e.ts index f7b1737..5a5e4b1 100644 --- a/backend/prisma/seed-email-scheduling-e2e.ts +++ b/backend/prisma/seed-email-scheduling-e2e.ts @@ -97,6 +97,7 @@ export function readEmailSchedulingE2EConfig( } const credentials = {} as EmailSchedulingE2EConfig['credentials']; + const namespaceEmails: string[] = []; for (const actor of ['customer', 'specialist', 'outsider'] as const) { const emailKey = `EMAIL_SCHEDULING_E2E_${actor.toUpperCase()}_EMAIL`; const passwordKey = `EMAIL_SCHEDULING_E2E_${actor.toUpperCase()}_PASSWORD`; @@ -109,15 +110,17 @@ export function readEmailSchedulingE2EConfig( throw new Error(`${passwordKey} must contain at least 6 characters`); } const [local, domain] = email.split('@'); + const httpEmail = `${local}+http@${domain}`; + namespaceEmails.push(email, httpEmail); credentials[actor] = { - email: namespace === 'http' ? `${local}+http@${domain}` : email, + email: namespace === 'http' ? httpEmail : email, password, }; } - if ( - new Set(Object.values(credentials).map(({ email }) => email)).size !== 3 - ) { - throw new Error('E2E emails must be distinct'); + if (new Set(namespaceEmails).size !== 6) { + throw new Error( + 'E2E emails must be distinct across browser and HTTP namespaces', + ); } return { databaseUrl: databaseUrl!, namespace, credentials }; } diff --git a/backend/test/email-scheduling.e2e-spec.ts b/backend/test/email-scheduling.e2e-spec.ts index 92e5283..cf15aae 100644 --- a/backend/test/email-scheduling.e2e-spec.ts +++ b/backend/test/email-scheduling.e2e-spec.ts @@ -8,6 +8,10 @@ import { readEmailSchedulingE2EConfig, seedEmailSchedulingFixtures, } from '../prisma/seed-email-scheduling-e2e'; +import { + getSanitizeCallCount, + resetSanitizeCallCount, +} from './mocks/isomorphic-dompurify'; const fixture = emailSchedulingFixtures('http'); const proposedIso = '2099-10-20T17:30:00.000Z'; @@ -100,6 +104,45 @@ describe('email scheduling fixture safety', () => { ); expect(config.namespace).toBe('http'); }); + + it.each(['browser', 'http'] as const)( + 'rejects collisions across both email namespaces before seeding %s', + (namespace) => { + expect(() => + readEmailSchedulingE2EConfig( + { + ...validEnv, + EMAIL_SCHEDULING_E2E_SPECIALIST_EMAIL: + ' CUSTOMER+HTTP@EXAMPLE.TEST ', + }, + namespace, + ), + ).toThrow(/distinct/i); + }, + ); + + it('keeps all six normalized browser and HTTP addresses distinct', () => { + const emails = (['browser', 'http'] as const).flatMap((namespace) => + Object.values( + readEmailSchedulingE2EConfig(validEnv, namespace).credentials, + ).map(({ email }) => email), + ); + expect(new Set(emails).size).toBe(6); + }); + + it('fails closed if the out-of-scope SVG sanitizer boundary is called', () => { + const boundary = + require('isomorphic-dompurify') as typeof import('./mocks/isomorphic-dompurify'); + boundary.resetSanitizeCallCount(); + try { + expect(() => boundary.default.sanitize('')).toThrow( + /SVG sanitization is outside the email scheduling E2E gate/, + ); + expect(boundary.getSanitizeCallCount()).toBe(1); + } finally { + boundary.resetSanitizeCallCount(); + } + }); }); describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { @@ -125,6 +168,12 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { } process.env.DATABASE_URL = config.databaseUrl; process.env.NOTIFICATIONS_ENABLED = 'false'; + resetSanitizeCallCount(); + // Resolve the complete application graph before connecting or seeding. + // External delivery and unrelated background jobs are outside this gate. + const { AppModule } = + require('../src/app.module') as typeof import('../src/app.module'); + expect(getSanitizeCallCount()).toBe(0); const { PrismaClient } = require('@prisma/client') as typeof import('@prisma/client'); prisma = new PrismaClient({ @@ -145,10 +194,6 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { }), ).toBe(2); - // Load the real application only after validating the isolated database. - // External delivery and unrelated background jobs are outside this gate. - const { AppModule } = - require('../src/app.module') as typeof import('../src/app.module'); const { Test } = require('@nestjs/testing') as typeof import('@nestjs/testing'); const { ClassSerializerInterceptor, ValidationPipe } = @@ -219,6 +264,7 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { ); app.useLogger(false); await app.init(); + expect(getSanitizeCallCount()).toBe(0); [customerToken, specialistToken, outsiderToken] = await Promise.all([ login('customer'), @@ -251,6 +297,7 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { delete process.env.NOTIFICATIONS_ENABLED; else process.env.NOTIFICATIONS_ENABLED = oldNotificationsEnabled; } + expect(getSanitizeCallCount()).toBe(0); }); async function login(actor: 'customer' | 'specialist' | 'outsider') { @@ -353,7 +400,7 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { specialist_id: fixture.users[1].id, car_id: productId, }, - include: { ProcessStatusHistory: true }, + include: { ProcessStatusHistory: { orderBy: { id: 'asc' } } }, }); expect(appointments).toHaveLength(1); expect(processes).toHaveLength(1); @@ -374,7 +421,7 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { }); expect(processes[0].ProcessStatusHistory).toHaveLength(1); expect(processes[0].ProcessStatusHistory[0].status).toBe('SCHEDULING'); - return processes[0]; + return { appointment: appointments[0], process: processes[0] }; } it('serves only the public business profile and blocks private profile IDOR', async () => { @@ -669,8 +716,10 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { 'SCHEDULED', changedIso, ); - expect(firstStored.notes).toContain(`proposta: ${proposedIso}`); - expect(firstStored.notes).toContain(`horário confirmado: ${changedIso}`); + expect(firstStored.process.notes).toContain(`proposta: ${proposedIso}`); + expect(firstStored.process.notes).toContain( + `horário confirmado: ${changedIso}`, + ); // A confirmed commitment conflicts; a still-pending EMAIL proposal did not. const conflict = await confirm(created[1].processId, changedIso).expect( @@ -706,15 +755,24 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { 'SCHEDULED', proposedIso, ); - const beforeRepeat = await prisma!.process.findUniqueOrThrow({ - where: { id: created[0].processId }, - }); + const beforeRepeat = await assertStoredState( + created[0].productId, + created[0].processId, + created[0].appointmentId, + 'SCHEDULED', + changedIso, + ); await confirm(created[0].processId, changedIso).expect(201); - expect( - await prisma!.process.findUniqueOrThrow({ - where: { id: created[0].processId }, - }), - ).toEqual(beforeRepeat); + const afterRepeat = await assertStoredState( + created[0].productId, + created[0].processId, + created[0].appointmentId, + 'SCHEDULED', + changedIso, + ); + // Equality covers appointment confirmation/audit timestamps, process notes + // and the full ordered history; assertStoredState also checks cardinality. + expect(afterRepeat).toEqual(beforeRepeat); await confirm(created[0].processId, secondIso).expect(400); for (const item of created) { diff --git a/backend/test/jest-e2e.json b/backend/test/jest-e2e.json index 50f8efa..bcfc11b 100644 --- a/backend/test/jest-e2e.json +++ b/backend/test/jest-e2e.json @@ -4,7 +4,8 @@ "testEnvironment": "node", "testRegex": ".e2e-spec.ts$", "moduleNameMapper": { - "^src/(.*)$": "/../src/$1" + "^src/(.*)$": "/../src/$1", + "^isomorphic-dompurify$": "/mocks/isomorphic-dompurify.ts" }, "transform": { "^.+\\.(t|j)s$": "ts-jest" diff --git a/backend/test/mocks/isomorphic-dompurify.ts b/backend/test/mocks/isomorphic-dompurify.ts new file mode 100644 index 0000000..5398303 --- /dev/null +++ b/backend/test/mocks/isomorphic-dompurify.ts @@ -0,0 +1,20 @@ +// Scheduling never sanitizes SVG. Keep LogoSanitizerService and its Nest +// wiring real, but fail if this unrelated dependency is used by the E2E gate. +let sanitizeCallCount = 0; + +export function getSanitizeCallCount() { + return sanitizeCallCount; +} + +export function resetSanitizeCallCount() { + sanitizeCallCount = 0; +} + +export default { + sanitize(_input: string): never { + sanitizeCallCount += 1; + throw new Error( + 'SVG sanitization is outside the email scheduling E2E gate', + ); + }, +}; From 3a7036e55047d8df97f1b8bb7e9058655f16019f Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 11:26:28 -0300 Subject: [PATCH 17/60] test: fix PostgreSQL fixtures and restore legacy confirmation race --- .../appointments-concurrency.postgres.spec.ts | 93 ++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts index 05e5700..afcc6f6 100644 --- a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts +++ b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts @@ -104,7 +104,7 @@ describeWithPostgres( name: 'Schedule', surname: `Fixture ${index}`, email: `schedule-${index}-${suffix}@example.test`, - rg: `${suffix.slice(0, 12)}${index}`, + rg: `${suffix.slice(0, 10)}${index}`, role: index < 2 ? UserRole.CUSTOMER : UserRole.SPECIALIST, speciality: index < 2 ? null : ProductType.CAR, password_hash: 'not-used', @@ -523,6 +523,97 @@ describeWithPostgres( }); } + it.each([AppointmentSchedulingMethod.CALENDLY, null])( + 'serializes legacy confirmPending requests for the same specialist/time (%s)', + async (schedulingMethod) => { + const pending = await Promise.all( + clientIds.map(async (clientId, index) => { + const appointment = await holder.appointment.create({ + data: { + client_id: clientId, + specialist_id: specialistId, + product_type: ProductType.CAR, + product_id: carIds[index], + status: StatusAgendamento.PENDING, + scheduling_method: schedulingMethod, + appointment_datetime: null, + }, + }); + await holder.process.create({ + data: { + client_id: clientId, + specialist_id: specialistId, + product_type: ProductType.CAR, + car_id: carIds[index], + appointment_id: appointment.id, + status: ProcessStatus.SCHEDULING, + }, + }); + return appointment; + }), + ); + const before = await holder.process.findMany({ + where: { appointment_id: { in: pending.map(({ id }) => id) } }, + include: { appointment: true }, + }); + const outcomes = await race((a, b) => [ + appointments(first, a).confirmPending( + pending[0].id, + specialistId, + proposedDate, + ), + appointments(second, b).confirmPending( + pending[1].id, + specialistId, + proposedDate, + ), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + expect( + outcomes.find(({ status }) => status === 'rejected'), + ).toMatchObject({ reason: expect.any(ConflictException) }); + const loserId = + pending[outcomes.findIndex(({ status }) => status === 'rejected')].id; + expect( + await holder.process.findUniqueOrThrow({ + where: { appointment_id: loserId }, + include: { appointment: true }, + }), + ).toEqual( + before.find(({ appointment_id }) => appointment_id === loserId), + ); + expect( + await holder.appointment.count({ + where: { + specialist_id: specialistId, + status: StatusAgendamento.SCHEDULED, + appointment_datetime: proposedDate, + }, + }), + ).toBe(1); + expect( + await holder.process.count({ + where: { + specialist_id: specialistId, + status: ProcessStatus.NEGOTIATION, + }, + }), + ).toBe(1); + expect( + await holder.processStatusHistory.count({ + where: { process: { specialist_id: specialistId } }, + }), + ).toBe(1); + await new Promise((resolve) => setImmediate(resolve)); + expect( + notifications.sendAppointmentConfirmedEmail, + ).toHaveBeenCalledTimes(1); + }, + 15_000, + ); + function callback( client: PrismaClient, attempted: Deferred, From ef2d8b5b12d6043a5bbfa844fefa80c110d0041d Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 11:37:22 -0300 Subject: [PATCH 18/60] docs: clarify sanitizer boundary in email E2E --- docs/docs/agendamento-sem-calendly.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/agendamento-sem-calendly.md b/docs/docs/agendamento-sem-calendly.md index 70b32d9..53b1cc9 100644 --- a/docs/docs/agendamento-sem-calendly.md +++ b/docs/docs/agendamento-sem-calendly.md @@ -84,7 +84,7 @@ O seed cria ou atualiza três usuários sintéticos e dois carros ativos atribu | Produto A | `c848f474-6492-4ac1-8a7d-000000000101` | | Produto B | `c848f474-6492-4ac1-8a7d-000000000102` | -O HTTP E2E usa outro prefixo, `8c26e2a3-fd13-447a-9b6c`, e deriva aliases `local+http@dominio.test` dos e-mails da sessão. Assim ele não limpa pedidos feitos com o seed de navegador. Ele inicializa o `AppModule` real, autentica as três identidades pelo login e usa guards, validação, serializer e prefixo reais. Somente fronteiras externas (SES/S3/DocuSign), recuperação de jobs e o timer de rate limit são neutralizados; autenticação, autorização, transações e persistência não são simuladas. Sem a URL explícita, o grupo HTTP é pulado; o gate dedicado exige zero testes pulados. +O HTTP E2E usa outro prefixo, `8c26e2a3-fd13-447a-9b6c`, e deriva aliases `local+http@dominio.test` dos e-mails da sessão. Assim ele não limpa pedidos feitos com o seed de navegador. Ele inicializa o `AppModule` real, autentica as três identidades pelo login e usa guards, validação, serializer e prefixo reais. Somente fronteiras externas (SES/S3/DocuSign), recuperação de jobs e o timer de rate limit são neutralizados; autenticação, autorização, transações e persistência não são simuladas. No ambiente Jest desse E2E, a fronteira `isomorphic-dompurify`/SVG é substituída por um stub *fail-closed*: qualquer chamada ao sanitizador falha imediatamente. Portanto, o HTTP E2E não comprova a sanitização; a implementação de produção e os testes próprios do sanitizador continuam usando a dependência real. Sem a URL explícita, o grupo HTTP é pulado; o gate dedicado exige zero testes pulados. O teste cobre criação pendente, identidade derivada do JWT, IDOR de GET/PATCH, bypass direto, contato autorizado na lista/detalhe, duplicidade, conflito sem PII, confirmação alterada e inalterada, idempotência e estados/cardinalidade no banco. O seed também é executado duas vezes pelo teste para comprovar a idempotência dos IDs-base. From 0e68f5fd5e53d375811f026a58725ae62c3138c9 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 11:40:29 -0300 Subject: [PATCH 19/60] test: align legacy e2e with health endpoint --- backend/test/app.e2e-spec.ts | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/backend/test/app.e2e-spec.ts b/backend/test/app.e2e-spec.ts index 36852c5..6c35b2d 100644 --- a/backend/test/app.e2e-spec.ts +++ b/backend/test/app.e2e-spec.ts @@ -3,23 +3,41 @@ import { INestApplication } from '@nestjs/common'; import request from 'supertest'; import { App } from 'supertest/types'; import { AppModule } from './../src/app.module'; +import { RateLimitGuard } from '../src/shared/guards/rate-limit.guard'; -describe('AppController (e2e)', () => { +describe('HealthController (e2e)', () => { let app: INestApplication; - beforeEach(async () => { + beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], - }).compile(); + }) + .overrideGuard(RateLimitGuard) + .useValue({ canActivate: () => true }) + .compile(); app = moduleFixture.createNestApplication(); + app.setGlobalPrefix('api'); await app.init(); }); - it('/ (GET)', () => { - return request(app.getHttpServer()) - .get('/') - .expect(200) - .expect('Hello World!'); + afterAll(async () => { + await app?.close(); + }); + + it('/api/health (GET)', async () => { + const response = await request(app.getHttpServer()) + .get('/api/health') + .expect(200); + + expect(response.body).toEqual( + expect.objectContaining({ + status: 'ok', + timestamp: expect.any(String), + service: 'bmf-lux-brokerage-backend', + environment: expect.any(String), + }), + ); + expect(Number.isNaN(Date.parse(response.body.timestamp))).toBe(false); }); }); From c9c4d89b1ac8386cbd1ba8965fd7e5438f814a48 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 11:45:49 -0300 Subject: [PATCH 20/60] fix(appointments): block SSRF in Calendly resource sync --- .../appointments/appointments.service.spec.ts | 51 +++++++++++-- .../appointments/appointments.service.ts | 8 ++ .../calendly-integration.service.spec.ts | 76 ++++++++++++++++++- .../calendly-integration.service.ts | 37 +++++---- .../dto/calendly-scheduled.dto.spec.ts | 71 +++++++++++++++++ .../dto/calendly-scheduled.dto.ts | 62 +++++++++++++++ 6 files changed, 282 insertions(+), 23 deletions(-) create mode 100644 backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts index 6086252..35c32d3 100644 --- a/backend/src/features/appointments/appointments.service.spec.ts +++ b/backend/src/features/appointments/appointments.service.spec.ts @@ -1559,6 +1559,42 @@ describe('AppointmentsService.confirmPending — snapshot da negociação', () = }); describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () => { + it('rejeita e não persiste URIs Calendly não confiáveis mesmo com horário informado', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(), + } as any; + const calendlyIntegrationService = { + resolveScheduledStartTime: jest.fn(), + } as any; + const service = new AppointmentsService( + prisma, + {} as any, + calendlyIntegrationService, + ); + + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: 'https://evil.test/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + scheduled_start_time: '2099-01-01T10:00:00.000Z', + }), + ).rejects.toThrow(BadRequestException); + expect( + calendlyIntegrationService.resolveScheduledStartTime, + ).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + it.each([ AppointmentSchedulingMethod.EMAIL, AppointmentSchedulingMethod.PLATFORM, @@ -1604,8 +1640,9 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = await expect( service.registerCalendlyScheduled(appointment.id, appointment.client_id, { - event_uri: 'https://calendly.test/events/2', - invitee_uri: 'https://calendly.test/invitees/2', + event_uri: 'https://api.calendly.com/scheduled_events/event-2', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-2/invitees/invitee-2', scheduled_start_time: '2099-01-02T10:00:00.000Z', } as any), ).rejects.toThrow(ConflictException); @@ -1647,8 +1684,9 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = appointment.id, appointment.client_id, { - event_uri: 'https://calendly.test/events/1', - invitee_uri: 'https://calendly.test/invitees/1', + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', scheduled_start_time: '2099-01-01T10:00:00.000Z', } as any, ); @@ -1691,8 +1729,9 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = await expect( service.registerCalendlyScheduled(appointment.id, appointment.client_id, { - event_uri: 'https://calendly.test/events/1', - invitee_uri: 'https://calendly.test/invitees/1', + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', scheduled_start_time: '2099-01-01T10:00:00.000Z', } as any), ).rejects.toThrow(ConflictException); diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 0bc0ac6..6a61b74 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -41,6 +41,7 @@ import { isCalendlySchedulingAvailable } from 'src/shared/utils/calendly-schedul import { parseDate, isFutureDate } from 'src/shared/utils/date.utils'; import { NotificationService } from 'src/features/notifications/notification.service'; import { CalendlyIntegrationService } from './calendly-integration.service'; +import { isCalendlyResourceUri } from './dto/calendly-scheduled.dto'; import { buildNegotiationSnapshotUpdate } from 'src/features/processes/negotiation-snapshot'; import { lockNegotiationProductMoney } from 'src/features/products/product-monetary-lock'; import { validateSpecialistProductAssociation } from 'src/features/products/product-association-validator'; @@ -1742,6 +1743,13 @@ export class AppointmentsService { calendly_sync_status: CalendlySyncStatus; appointment_datetime: Date | null; }> { + if ( + !isCalendlyResourceUri(dto.event_uri, 'event') || + !isCalendlyResourceUri(dto.invitee_uri, 'invitee') + ) { + throw new BadRequestException('URIs do Calendly inválidas'); + } + const appointment = await this.prisma.appointment.findUnique({ where: { id: appointmentId }, }); diff --git a/backend/src/features/appointments/calendly-integration.service.spec.ts b/backend/src/features/appointments/calendly-integration.service.spec.ts index d8ffc1f..bcceed1 100644 --- a/backend/src/features/appointments/calendly-integration.service.spec.ts +++ b/backend/src/features/appointments/calendly-integration.service.spec.ts @@ -160,6 +160,65 @@ describe('CalendlyIntegrationService connection lifecycle', () => { return { service, prisma, connection }; } + it.each([ + 'https://evil/scheduled_events/event-1', + 'https://evil.test/scheduled_events/event-1', + 'https://calendly.com.evil/scheduled_events/event-1', + 'https://api.calendly.com.evil.test/scheduled_events/event-1', + 'http://api.calendly.com/scheduled_events/event-1', + 'https://user@api.calendly.com/scheduled_events/event-1', + 'https://api.calendly.com:444/scheduled_events/event-1', + 'https://127.0.0.1/scheduled_events/event-1', + ])( + 'não envia o Bearer token para event_uri não confiável: %s', + async (uri) => { + const { service } = makeRefreshService(); + + await expect( + service.resolveScheduledStartTime('specialist-1', uri), + ).rejects.toThrow('event_uri do Calendly inválida'); + expect(axios.get).not.toHaveBeenCalled(); + }, + ); + + it('não segue redirect ao buscar recurso autenticado do Calendly', async () => { + const { service } = makeRefreshService(); + jest.mocked(axios.get).mockRejectedValueOnce({ + response: { + status: 302, + headers: { location: 'http://127.0.0.1/internal' }, + }, + }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/event-1', + ), + ).rejects.toBeDefined(); + expect(axios.get).toHaveBeenCalledTimes(1); + expect(axios.get).toHaveBeenCalledWith( + 'https://api.calendly.com/scheduled_events/event-1', + expect.objectContaining({ maxRedirects: 0 }), + ); + }); + + it('rejeita URI de evento não confiável retornada pelo recurso de convidado', async () => { + const { service } = makeRefreshService(); + jest.mocked(axios.get).mockResolvedValueOnce({ + data: { resource: { event: 'http://127.0.0.1/internal' } }, + }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + null, + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + ), + ).rejects.toThrow('event_uri do Calendly inválida'); + expect(axios.get).toHaveBeenCalledTimes(1); + }); + it('mantém conexão ativa quando token expirado é renovado com sucesso', async () => { const { service, prisma } = makeRefreshService(); jest @@ -180,7 +239,7 @@ describe('CalendlyIntegrationService connection lifecycle', () => { expect( await service.resolveScheduledStartTime( 'specialist-1', - '/scheduled_events/1', + 'https://api.calendly.com/scheduled_events/1', ), ).toEqual(new Date('2099-01-01T10:00:00.000Z')); expect( @@ -204,7 +263,10 @@ describe('CalendlyIntegrationService connection lifecycle', () => { jest.mocked(axios.get).mockRejectedValue({ response: { status: 401 } }); jest.mocked(axios.post).mockRejectedValue(error); await expect( - service.resolveScheduledStartTime('specialist-1', '/scheduled_events/1'), + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/1', + ), ).rejects.toBe(error); expect(prisma.calendlyConnection.updateMany).toHaveBeenCalledWith({ where: { @@ -267,7 +329,10 @@ describe('CalendlyIntegrationService connection lifecycle', () => { response: { status: 400, data: { error: 'invalid_grant' } }, }; const refreshResult = expect( - service.resolveScheduledStartTime('specialist-1', '/scheduled_events/1'), + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/1', + ), ).rejects.toBe(error); await refreshStarted; await service.handleOAuthCallback('new-code', 'new-state'); @@ -298,7 +363,10 @@ describe('CalendlyIntegrationService connection lifecycle', () => { jest.mocked(axios.get).mockRejectedValue({ response: { status: 401 } }); jest.mocked(axios.post).mockRejectedValue({ response: { status: 503 } }); await expect( - service.resolveScheduledStartTime('specialist-1', '/scheduled_events/1'), + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/1', + ), ).rejects.toBeDefined(); expect(prisma.calendlyConnection.update).not.toHaveBeenCalled(); expect(prisma.calendlyConnection.updateMany).not.toHaveBeenCalled(); diff --git a/backend/src/features/appointments/calendly-integration.service.ts b/backend/src/features/appointments/calendly-integration.service.ts index 901d71e..d58afb4 100644 --- a/backend/src/features/appointments/calendly-integration.service.ts +++ b/backend/src/features/appointments/calendly-integration.service.ts @@ -27,6 +27,10 @@ import { acquireSpecialistScheduleLock, assertSpecialistScheduleAvailable, } from './appointment-schedule-lock'; +import { + CalendlyResourceKind, + isCalendlyResourceUri, +} from './dto/calendly-scheduled.dto'; interface CalendlyTokenResponse { access_token: string; @@ -287,6 +291,9 @@ export class CalendlyIntegrationService { return null; } + if (eventUri) this.assertCalendlyResourceUri(eventUri, 'event'); + if (inviteeUri) this.assertCalendlyResourceUri(inviteeUri, 'invitee'); + const connection = await this.prisma.calendlyConnection.findUnique({ where: { user_id: specialistId }, }); @@ -299,6 +306,7 @@ export class CalendlyIntegrationService { ? await this.getCalendlyResourceWithRefresh( connection.user_id, inviteeUri, + 'invitee', ) : null; @@ -330,6 +338,7 @@ export class CalendlyIntegrationService { const eventData = await this.getCalendlyResourceWithRefresh( connection.user_id, resolvedEventUri, + 'event', ); const eventResource = eventData?.resource || eventData; const eventStartTime = @@ -505,6 +514,7 @@ export class CalendlyIntegrationService { private async getCalendlyResourceWithRefresh( userId: string, uri: string, + kind: CalendlyResourceKind, ): Promise { const connection = await this.prisma.calendlyConnection.findUnique({ where: { user_id: userId }, @@ -519,7 +529,7 @@ export class CalendlyIntegrationService { let accessToken = this.decryptToken(connection.access_token_encrypted); try { - return await this.fetchCalendlyResource(accessToken, uri); + return await this.fetchCalendlyResource(accessToken, uri, kind); } catch (error: any) { const status = error?.response?.status; if (status !== 401) { @@ -529,7 +539,7 @@ export class CalendlyIntegrationService { const refreshed = await this.refreshConnectionToken(connection); accessToken = this.decryptToken(refreshed.access_token_encrypted); - return this.fetchCalendlyResource(accessToken, uri); + return this.fetchCalendlyResource(accessToken, uri, kind); } } @@ -615,13 +625,15 @@ export class CalendlyIntegrationService { private async fetchCalendlyResource( accessToken: string, uri: string, + kind: CalendlyResourceKind, ): Promise { - const normalizedUri = this.normalizeCalendlyUri(uri); - const { data } = await axios.get(normalizedUri, { + const trustedUri = this.assertCalendlyResourceUri(uri, kind); + const { data } = await axios.get(trustedUri, { headers: { Authorization: `Bearer ${accessToken}`, }, timeout: 20000, + maxRedirects: 0, }); return data; @@ -831,16 +843,15 @@ export class CalendlyIntegrationService { ); } - private normalizeCalendlyUri(uri: string): string { - if (uri.startsWith('http://') || uri.startsWith('https://')) { - return uri; - } - - if (uri.startsWith('/')) { - return `https://api.calendly.com${uri}`; + private assertCalendlyResourceUri( + uri: string, + kind: CalendlyResourceKind, + ): string { + if (!isCalendlyResourceUri(uri, kind)) { + const field = kind === 'event' ? 'event_uri' : 'invitee_uri'; + throw new BadRequestException(`${field} do Calendly inválida`); } - - return `https://api.calendly.com/${uri}`; + return uri; } private getRequiredEnv(name: string): string { diff --git a/backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts b/backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts new file mode 100644 index 0000000..b8748e5 --- /dev/null +++ b/backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts @@ -0,0 +1,71 @@ +import { validate } from 'class-validator'; +import { plainToInstance } from 'class-transformer'; +import { CalendlyScheduledDto } from './calendly-scheduled.dto'; + +describe('CalendlyScheduledDto — Calendly resource URIs', () => { + const validPayload = { + event_uri: 'https://api.calendly.com/scheduled_events/event-123', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-123/invitees/invitee-456', + }; + + async function invalidProperties(payload: Record) { + const errors = await validate( + plainToInstance(CalendlyScheduledDto, { + ...validPayload, + ...payload, + }), + ); + return errors.map((error) => error.property); + } + + it('aceita somente os caminhos canônicos de evento e convidado', async () => { + await expect(invalidProperties({})).resolves.toEqual([]); + }); + + it('aceita HTTPS com a porta padrão explícita', async () => { + await expect( + invalidProperties({ + event_uri: + 'https://api.calendly.com:443/scheduled_events/event-123', + invitee_uri: + 'https://api.calendly.com:443/scheduled_events/event-123/invitees/invitee-456', + }), + ).resolves.toEqual([]); + }); + + it.each([ + 'https://evil/scheduled_events/event-123', + 'https://evil.test/scheduled_events/event-123', + 'https://calendly.com.evil/scheduled_events/event-123', + 'https://api.calendly.com.evil.test/scheduled_events/event-123', + 'http://api.calendly.com/scheduled_events/event-123', + 'https://user:password@api.calendly.com/scheduled_events/event-123', + 'https://api.calendly.com:444/scheduled_events/event-123', + 'https://127.0.0.1/scheduled_events/event-123', + 'https://api.calendly.com/scheduled_events/event-123/invitees/invitee-456', + ])('rejeita event_uri fora do recurso esperado: %s', async (event_uri) => { + await expect(invalidProperties({ event_uri })).resolves.toContain( + 'event_uri', + ); + }); + + it.each([ + 'https://evil/scheduled_events/event-123/invitees/invitee-456', + 'https://evil.test/scheduled_events/event-123/invitees/invitee-456', + 'https://calendly.com.evil/scheduled_events/event-123/invitees/invitee-456', + 'https://api.calendly.com.evil.test/scheduled_events/event-123/invitees/invitee-456', + 'http://api.calendly.com/scheduled_events/event-123/invitees/invitee-456', + 'https://user@api.calendly.com/scheduled_events/event-123/invitees/invitee-456', + 'https://api.calendly.com:444/scheduled_events/event-123/invitees/invitee-456', + 'https://127.0.0.1/scheduled_events/event-123/invitees/invitee-456', + 'https://api.calendly.com/scheduled_events/event-123', + ])( + 'rejeita invitee_uri fora do recurso esperado: %s', + async (invitee_uri) => { + await expect(invalidProperties({ invitee_uri })).resolves.toContain( + 'invitee_uri', + ); + }, + ); +}); diff --git a/backend/src/features/appointments/dto/calendly-scheduled.dto.ts b/backend/src/features/appointments/dto/calendly-scheduled.dto.ts index 91f8cc7..c310708 100644 --- a/backend/src/features/appointments/dto/calendly-scheduled.dto.ts +++ b/backend/src/features/appointments/dto/calendly-scheduled.dto.ts @@ -4,15 +4,77 @@ import { IsOptional, IsString, MaxLength, + registerDecorator, + ValidationArguments, + ValidationOptions, } from 'class-validator'; +export type CalendlyResourceKind = 'event' | 'invitee'; + +const CALENDLY_RESOURCE_PATHS: Record = { + event: /^\/scheduled_events\/[A-Za-z0-9_-]+$/, + invitee: /^\/scheduled_events\/[A-Za-z0-9_-]+\/invitees\/[A-Za-z0-9_-]+$/, +}; + +export function isCalendlyResourceUri( + value: unknown, + kind: CalendlyResourceKind, +): value is string { + if (typeof value !== 'string') return false; + + try { + const uri = new URL(value); + return ( + uri.protocol === 'https:' && + uri.hostname === 'api.calendly.com' && + uri.port === '' && + uri.username === '' && + uri.password === '' && + uri.search === '' && + uri.hash === '' && + CALENDLY_RESOURCE_PATHS[kind].test(uri.pathname) + ); + } catch { + return false; + } +} + +function IsCalendlyResourceUri( + kind: CalendlyResourceKind, + validationOptions?: ValidationOptions, +): PropertyDecorator { + return (target, propertyKey) => { + registerDecorator({ + name: 'isCalendlyResourceUri', + target: target.constructor, + propertyName: propertyKey.toString(), + constraints: [kind], + options: validationOptions, + validator: { + validate(value: unknown, args: ValidationArguments) { + return isCalendlyResourceUri( + value, + args.constraints[0] as CalendlyResourceKind, + ); + }, + }, + }); + }; +} + export class CalendlyScheduledDto { @IsString({ message: 'event_uri deve ser uma string' }) @MaxLength(255, { message: 'event_uri deve ter no máximo 255 caracteres' }) + @IsCalendlyResourceUri('event', { + message: 'event_uri deve apontar para um evento da API do Calendly', + }) event_uri: string; @IsString({ message: 'invitee_uri deve ser uma string' }) @MaxLength(255, { message: 'invitee_uri deve ter no máximo 255 caracteres' }) + @IsCalendlyResourceUri('invitee', { + message: 'invitee_uri deve apontar para um convidado da API do Calendly', + }) invitee_uri: string; @IsOptional() From 15a651165d294e6e5e07a3fe4db23a20530640d5 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 11:46:17 -0300 Subject: [PATCH 21/60] fix(catalog): hide specialist PII from public products --- .../features/aircrafts/aircrafts.service.ts | 16 +- backend/src/features/boats/boats.service.ts | 16 +- .../src/features/cars/cars.service.spec.ts | 3 +- backend/src/features/cars/cars.service.ts | 16 +- .../public-catalog-projection.spec.ts | 211 ++++++++++++++++++ .../shared/selects/public-catalog.select.ts | 82 +++++++ frontend/src/services/aircrafts.service.ts | 5 +- frontend/src/services/boats.service.ts | 5 +- frontend/src/services/cars.service.ts | 5 +- 9 files changed, 316 insertions(+), 43 deletions(-) create mode 100644 backend/src/features/products/public-catalog-projection.spec.ts create mode 100644 backend/src/shared/selects/public-catalog.select.ts diff --git a/backend/src/features/aircrafts/aircrafts.service.ts b/backend/src/features/aircrafts/aircrafts.service.ts index 2131904..ffebf4c 100644 --- a/backend/src/features/aircrafts/aircrafts.service.ts +++ b/backend/src/features/aircrafts/aircrafts.service.ts @@ -11,10 +11,9 @@ import { RangeAircraftFilters, } from 'src/shared/dto/filters.dto'; import { Prisma, ProductType } from '@prisma/client'; -import { Aircraft } from './entity/aircraft.entity'; -import { UserEntity } from 'src/auth/entities/user.entity'; import { AIRCRAFT_COLUMNS } from 'src/shared/constants/product-columns'; import { updateProductWithMonetaryLock } from '../products/product-monetary-lock'; +import { publicAircraftSelect } from 'src/shared/selects/public-catalog.select'; @Injectable() export class AircraftsService { @@ -195,16 +194,13 @@ export class AircraftsService { skip: skip, take: take, where: where, - include: { - images: true, - specialist: true, - }, + select: publicAircraftSelect, }), this.prismaService.aircraft.count({ where }), ]); // Converter as keys do S3 em URLs assinadas para cada aeronave - const aircraftsEntities: Aircraft[] = await Promise.all( + const aircraftsEntities = await Promise.all( aircrafts.map(async (aircraft) => { let imagesWithUrls: any[] = []; if (aircraft.images && aircraft.images.length > 0) { @@ -220,9 +216,7 @@ export class AircraftsService { ...aircraft, valor: aircraft.valor.toNumber(), images: imagesWithUrls, - specialist: aircraft.specialist - ? UserEntity.fromPrisma(aircraft.specialist) - : null, + specialist: aircraft.specialist, }; }), ); @@ -238,7 +232,7 @@ export class AircraftsService { this.logger.log(`[findOne] Buscando aeronave - ID: ${id}`); const aircraft = await this.prismaService.aircraft.findUnique({ where: { id }, - include: { images: true }, + select: publicAircraftSelect, }); if (!aircraft) { this.logger.warn(`[findOne] Aeronave não encontrada - ID: ${id}`); diff --git a/backend/src/features/boats/boats.service.ts b/backend/src/features/boats/boats.service.ts index 79d6a2e..b3efc2e 100644 --- a/backend/src/features/boats/boats.service.ts +++ b/backend/src/features/boats/boats.service.ts @@ -11,10 +11,9 @@ import { FiltersBoatMeta, RangeBoatFilters, } from 'src/shared/dto/filters.dto'; -import { Boat } from './entity/boat.entity'; -import { UserEntity } from 'src/auth/entities/user.entity'; import { BOAT_COLUMNS } from 'src/shared/constants/product-columns'; import { updateProductWithMonetaryLock } from '../products/product-monetary-lock'; +import { publicBoatSelect } from 'src/shared/selects/public-catalog.select'; @Injectable() export class BoatsService { @@ -171,16 +170,13 @@ export class BoatsService { skip: skip, take: take, where: where, - include: { - images: true, - specialist: true, - }, + select: publicBoatSelect, }), this.prismaService.boat.count({ where }), ]); // Converter as keys do S3 em URLs assinadas para cada barco - const boatEntities: Boat[] = await Promise.all( + const boatEntities = await Promise.all( boats.map(async (boat) => { let imagesWithUrls: any[] = []; if (boat.images && boat.images.length > 0) { @@ -197,9 +193,7 @@ export class BoatsService { descricao: boat.descricao_completa, valor: boat.valor.toNumber(), images: imagesWithUrls, - specialist: boat.specialist - ? UserEntity.fromPrisma(boat.specialist) - : null, + specialist: boat.specialist, }; }), ); @@ -215,7 +209,7 @@ export class BoatsService { this.logger.log(`[findOne] Buscando barco - ID: ${id}`); const boat = await this.prismaService.boat.findUnique({ where: { id }, - include: { images: true }, + select: publicBoatSelect, }); if (!boat) { this.logger.warn(`[findOne] Barco não encontrado - ID: ${id}`); diff --git a/backend/src/features/cars/cars.service.spec.ts b/backend/src/features/cars/cars.service.spec.ts index e17efcb..1bb1f63 100644 --- a/backend/src/features/cars/cars.service.spec.ts +++ b/backend/src/features/cars/cars.service.spec.ts @@ -1,5 +1,6 @@ import { CarsService } from './cars.service'; import { Prisma, ProductCurrency } from '@prisma/client'; +import { publicCarSelect } from 'src/shared/selects/public-catalog.select'; describe('CarsService — UUID do produto', () => { it('consulta o carro pelo UUID recebido', async () => { @@ -18,7 +19,7 @@ describe('CarsService — UUID do produto', () => { expect(findUnique).toHaveBeenCalledWith({ where: { id: carId }, - include: { images: true }, + select: publicCarSelect, }); }); diff --git a/backend/src/features/cars/cars.service.ts b/backend/src/features/cars/cars.service.ts index 1f2d19f..aff6492 100644 --- a/backend/src/features/cars/cars.service.ts +++ b/backend/src/features/cars/cars.service.ts @@ -11,10 +11,9 @@ import { FiltersCarMeta, RangeCarFilters, } from 'src/shared/dto/filters.dto'; -import { Car } from './entity/car.entity'; -import { UserEntity } from 'src/auth/entities/user.entity'; import { CAR_COLUMNS } from 'src/shared/constants/product-columns'; import { updateProductWithMonetaryLock } from '../products/product-monetary-lock'; +import { publicCarSelect } from 'src/shared/selects/public-catalog.select'; @Injectable() export class CarsService { @@ -152,16 +151,13 @@ export class CarsService { skip: skip, take: take, where: where, - include: { - images: true, - specialist: true, - }, + select: publicCarSelect, }), this.prismaService.car.count({ where }), ]); // Converter as keys do S3 em URLs assinadas para cada carro - const carEntities: Car[] = await Promise.all( + const carEntities = await Promise.all( cars.map(async (car) => { let imagesWithUrls: any[] = []; if (car.images && car.images.length > 0) { @@ -177,9 +173,7 @@ export class CarsService { ...car, valor: car.valor.toNumber(), images: imagesWithUrls, - specialist: car.specialist - ? UserEntity.fromPrisma(car.specialist) - : null, + specialist: car.specialist, }; }), ); @@ -195,7 +189,7 @@ export class CarsService { this.logger.log(`[findOne] Buscando carro - ID: ${id}`); const car = await this.prismaService.car.findUnique({ where: { id }, - include: { images: true }, + select: publicCarSelect, }); if (!car) { this.logger.warn(`[findOne] Carro não encontrado - ID: ${id}`); diff --git a/backend/src/features/products/public-catalog-projection.spec.ts b/backend/src/features/products/public-catalog-projection.spec.ts new file mode 100644 index 0000000..5e1d776 --- /dev/null +++ b/backend/src/features/products/public-catalog-projection.spec.ts @@ -0,0 +1,211 @@ +import { Prisma } from '@prisma/client'; +import { AircraftsService } from '../aircrafts/aircrafts.service'; +import { BoatsService } from '../boats/boats.service'; +import { CarsService } from '../cars/cars.service'; + +const privateSpecialistFields = { + cpf: '11222333000181', + rg: '12345678901', + phone: '+5511999999999', + password_hash: 'private-password-hash', + bank: 'private-bank', + agency: '0001', + checking_account: 'private-account', + calendly_user_uri: 'https://api.calendly.com/users/private', + calendly_organization_uri: 'https://api.calendly.com/organizations/private', + calendly_connection: { + access_token_encrypted: 'private-access-token', + refresh_token_encrypted: 'private-refresh-token', + webhook_uri: 'https://api.calendly.com/webhooks/private', + }, +}; + +const specialist = { + id: '22222222-2222-4222-8222-222222222222', + name: 'Ana', + surname: 'Silva', + email: 'ana.private@example.test', + ...privateSpecialistFields, +}; + +const images = [ + { + id: 1, + product_type: 'CAR', + image_url: 'public-s3-key', + is_primary: true, + created_at: new Date('2026-01-01T00:00:00.000Z'), + car_id: '11111111-1111-4111-8111-111111111111', + }, +]; + +const baseProduct = { + id: '11111111-1111-4111-8111-111111111111', + specialist_id: specialist.id, + is_active: true, + deactivated_at: null, + deactivated_by_sync_job_id: '33333333-3333-4333-8333-333333333333', + marca: 'Marca', + modelo: 'Modelo', + identificador: 'PUBLIC-1', + valor: new Prisma.Decimal('100000.00'), + currency: 'BRL', + estado: 'SP', + ano: 2026, + created_at: new Date('2026-01-01T00:00:00.000Z'), + updated_at: new Date('2026-01-02T00:00:00.000Z'), + images, + specialist, +}; + +function project(record: Record, select: Record) { + return Object.fromEntries( + Object.entries(select).map(([key, selection]) => { + const value = record[key]; + if ( + selection && + typeof selection === 'object' && + 'select' in selection && + value != null + ) { + if (Array.isArray(value)) { + return [key, value.map((item) => project(item, selection.select))]; + } + return [key, project(value, selection.select)]; + } + return [key, value]; + }), + ); +} + +function makePrisma(model: 'car' | 'boat' | 'aircraft', record: object) { + const findMany = jest.fn(async (args: any) => + args.select ? [project(record, args.select)] : [record], + ); + const findUnique = jest.fn(async (args: any) => + args.select ? project(record, args.select) : record, + ); + const delegate = { + findMany, + findUnique, + count: jest.fn().mockResolvedValue(1), + }; + return { + prisma: { + [model]: delegate, + $transaction: jest.fn(async (operations: Promise[]) => + Promise.all(operations), + ), + } as any, + findMany, + findUnique, + }; +} + +const forbiddenKeys = [ + 'cpf', + 'cnpj', + 'rg', + 'phone', + 'telefone', + 'email', + 'password_hash', + 'bank', + 'agency', + 'checking_account', + 'calendly_user_uri', + 'calendly_organization_uri', + 'calendly_connection', + 'access_token_encrypted', + 'refresh_token_encrypted', + 'webhook_uri', + 'deactivated_at', + 'deactivated_by_sync_job_id', +]; + +function expectPublicPayload(payload: unknown) { + const serialized = JSON.stringify(payload); + for (const key of forbiddenKeys) { + expect(serialized).not.toContain(`"${key}"`); + } + expect(serialized).not.toContain('private-'); +} + +describe.each([ + { + label: 'cars', + model: 'car' as const, + record: { ...baseProduct, descricao: 'Descrição', images }, + makeService: (prisma: any, s3: any) => new CarsService(prisma, s3), + list: (service: CarsService) => + service.getAllCars({ page: 1, perPage: 20, appliedFilters: {} }), + detail: (service: CarsService) => service.findOne(baseProduct.id), + }, + { + label: 'boats', + model: 'boat' as const, + record: { + ...baseProduct, + descricao_completa: 'Descrição', + images: images.map((image) => ({ + ...image, + product_type: 'BOAT', + car_id: undefined, + boat_id: baseProduct.id, + })), + }, + makeService: (prisma: any, s3: any) => new BoatsService(prisma, s3), + list: (service: BoatsService) => + service.getAllBoats({ page: 1, perPage: 20, appliedFilters: {} }), + detail: (service: BoatsService) => service.findOne(baseProduct.id), + }, + { + label: 'aircrafts', + model: 'aircraft' as const, + record: { + ...baseProduct, + descricao: 'Descrição', + images: images.map((image) => ({ + ...image, + product_type: 'AIRCRAFT', + car_id: undefined, + aircraft_id: baseProduct.id, + })), + }, + makeService: (prisma: any, s3: any) => new AircraftsService(prisma, s3), + list: (service: AircraftsService) => + service.getAllAircrafts({ page: 1, perPage: 20, appliedFilters: {} }), + detail: (service: AircraftsService) => service.findOne(baseProduct.id), + }, +])('$label public catalog projection', (scenario) => { + const s3 = { + getSignedUrl: jest.fn(async (key: string) => `https://cdn.test/${key}`), + }; + + it('uses a default-deny projection and exposes only the public specialist identity in list responses', async () => { + const { prisma, findMany } = makePrisma(scenario.model, scenario.record); + const service = scenario.makeService(prisma, s3) as any; + + const result = await scenario.list(service); + + expect(findMany.mock.calls[0][0]).toHaveProperty('select'); + expect(findMany.mock.calls[0][0]).not.toHaveProperty('include'); + expect(result.data[0].specialist).toEqual({ + id: specialist.id, + name: specialist.name, + surname: specialist.surname, + }); + expectPublicPayload(result.data[0]); + }); + + it('uses a default-deny projection for the public detail response', async () => { + const { prisma, findUnique } = makePrisma(scenario.model, scenario.record); + const service = scenario.makeService(prisma, s3) as any; + + const result = await scenario.detail(service); + + expect(findUnique.mock.calls[0][0]).toHaveProperty('select'); + expect(findUnique.mock.calls[0][0]).not.toHaveProperty('include'); + expectPublicPayload(result); + }); +}); diff --git a/backend/src/shared/selects/public-catalog.select.ts b/backend/src/shared/selects/public-catalog.select.ts new file mode 100644 index 0000000..b59ecf0 --- /dev/null +++ b/backend/src/shared/selects/public-catalog.select.ts @@ -0,0 +1,82 @@ +import { Prisma } from '@prisma/client'; + +export const publicCatalogSpecialistSelect = { + id: true, + name: true, + surname: true, +} satisfies Prisma.UserSelect; + +export const publicCatalogImageSelect = { + id: true, + image_url: true, + is_primary: true, +} satisfies Prisma.Car_imageSelect & + Prisma.Boat_imageSelect & + Prisma.Aircraft_imageSelect; + +export const publicCarSelect = { + id: true, + specialist_id: true, + marca: true, + modelo: true, + identificador: true, + valor: true, + currency: true, + estado: true, + ano: true, + descricao: true, + cor: true, + km: true, + cambio: true, + combustivel: true, + tipo_categoria: true, + created_at: true, + updated_at: true, + images: { select: publicCatalogImageSelect }, + specialist: { select: publicCatalogSpecialistSelect }, +} satisfies Prisma.CarSelect; + +export const publicBoatSelect = { + id: true, + specialist_id: true, + marca: true, + modelo: true, + identificador: true, + valor: true, + currency: true, + ano: true, + fabricante: true, + tamanho: true, + estilo: true, + combustivel: true, + motor: true, + ano_motor: true, + descricao_completa: true, + acessorios: true, + estado: true, + tipo_embarcacao: true, + created_at: true, + updated_at: true, + images: { select: publicCatalogImageSelect }, + specialist: { select: publicCatalogSpecialistSelect }, +} satisfies Prisma.BoatSelect; + +export const publicAircraftSelect = { + id: true, + specialist_id: true, + categoria: true, + ano: true, + marca: true, + modelo: true, + identificador: true, + assentos: true, + estado: true, + descricao: true, + valor: true, + currency: true, + tipo_aeronave: true, + created_at: true, + updated_at: true, + images: { select: publicCatalogImageSelect }, + specialist: { select: publicCatalogSpecialistSelect }, +} satisfies Prisma.AircraftSelect; diff --git a/frontend/src/services/aircrafts.service.ts b/frontend/src/services/aircrafts.service.ts index 73035d9..ff826f3 100644 --- a/frontend/src/services/aircrafts.service.ts +++ b/frontend/src/services/aircrafts.service.ts @@ -28,10 +28,9 @@ export interface RawAircraft { descricao?: string; specialist_id?: string; specialist?: { - id: number; + id: string; name: string; - email: string; - especialidade: string; + surname: string; }; images?: { id: number; diff --git a/frontend/src/services/boats.service.ts b/frontend/src/services/boats.service.ts index 0a05a7b..cecb442 100644 --- a/frontend/src/services/boats.service.ts +++ b/frontend/src/services/boats.service.ts @@ -33,10 +33,9 @@ export interface RawBoat { acessorios?: string; specialist_id?: string; specialist?: { - id: number; + id: string; name: string; - email: string; - especialidade: string; + surname: string; }; images?: { id: number; diff --git a/frontend/src/services/cars.service.ts b/frontend/src/services/cars.service.ts index b0a8157..4abab84 100644 --- a/frontend/src/services/cars.service.ts +++ b/frontend/src/services/cars.service.ts @@ -30,10 +30,9 @@ export interface RawCar { descricao?: string; specialist_id?: string; specialist?: { - id: number; + id: string; name: string; - email: string; - especialidade: string; + surname: string; }; images?: { id: number; From 8229f86e670a3daa8b1a9cd5eb34cb2df0c98cd0 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 11:48:24 -0300 Subject: [PATCH 22/60] fix(appointments): release scheduling process on cancellation --- .../appointments-concurrency.postgres.spec.ts | 76 +++++++- .../appointments/appointments.service.spec.ts | 166 ++++++++++++++++++ .../appointments/appointments.service.ts | 97 +++++++--- .../processes/processes.service.spec.ts | 76 ++++++++ .../features/processes/processes.service.ts | 89 ++++++---- 5 files changed, 447 insertions(+), 57 deletions(-) diff --git a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts index afcc6f6..7770c97 100644 --- a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts +++ b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts @@ -86,6 +86,7 @@ describeWithPostgres( const notifications = { sendAppointmentConfirmedEmail: jest.fn().mockResolvedValue(undefined), sendAppointmentRescheduledEmail: jest.fn().mockResolvedValue(undefined), + sendAppointmentCancelledEmail: jest.fn().mockResolvedValue(undefined), }; beforeAll(async () => { @@ -614,6 +615,77 @@ describeWithPostgres( 15_000, ); + it('keeps confirmation/cancellation races consistent and releases the product for a new request', async () => { + const request = await createRequest(holder, 0); + const outcomes = await race((a, b) => [ + appointments(first, a).updateStatus( + request.id, + { status: StatusAgendamento.CANCELLED }, + clientIds[0], + UserRole.CUSTOMER, + ), + processes(second, b).confirmAppointment( + request.process_id, + specialistId, + proposedIso, + ), + ]); + + expect(outcomes[0].status).toBe('fulfilled'); + expect( + await holder.appointment.findUniqueOrThrow({ + where: { id: request.id }, + include: { process: true }, + }), + ).toMatchObject({ + status: StatusAgendamento.CANCELLED, + process: null, + }); + expect( + await holder.process.findUnique({ where: { id: request.process_id } }), + ).toBeNull(); + + const replacement = await createRequest(holder, 0); + expect(replacement).toMatchObject({ + status: StatusAgendamento.PENDING, + }); + expect(replacement.id).not.toBe(request.id); + expect(replacement.process_id).not.toBe(request.process_id); + expect( + await holder.process.findUniqueOrThrow({ + where: { id: replacement.process_id }, + }), + ).toMatchObject({ status: ProcessStatus.SCHEDULING }); + }, 15_000); + + it('serializes the process cancellation route against confirmation without orphaning either record', async () => { + const request = await createRequest(holder, 0); + const outcomes = await race((a, b) => [ + processes(first, a).cancelAppointment( + request.process_id, + clientIds[0], + ), + processes(second, b).confirmAppointment( + request.process_id, + specialistId, + proposedIso, + ), + ]); + + expect(outcomes[0].status).toBe('fulfilled'); + expect( + await holder.appointment.findUnique({ where: { id: request.id } }), + ).toBeNull(); + expect( + await holder.process.findUnique({ where: { id: request.process_id } }), + ).toBeNull(); + + const replacement = await createRequest(holder, 0); + expect(replacement.status).toBe(StatusAgendamento.PENDING); + expect(replacement.id).not.toBe(request.id); + expect(replacement.process_id).not.toBe(request.process_id); + }, 15_000); + function callback( client: PrismaClient, attempted: Deferred, @@ -624,8 +696,8 @@ describeWithPostgres( appointment.id, clientIds[index], { - event_uri: `https://calendly.test/events/${appointment.id}`, - invitee_uri: `https://calendly.test/invitees/${appointment.id}`, + event_uri: `https://api.calendly.com/scheduled_events/${appointment.id}`, + invitee_uri: `https://api.calendly.com/scheduled_events/${appointment.id}/invitees/${appointment.id}`, scheduled_start_time: proposedIso, }, ); diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts index 35c32d3..2140c45 100644 --- a/backend/src/features/appointments/appointments.service.spec.ts +++ b/backend/src/features/appointments/appointments.service.spec.ts @@ -1000,6 +1000,102 @@ describe('AppointmentsService.createPending — integridade das partes', () => { }); describe('AppointmentsService.updateStatus — snapshot da negociação', () => { + it.each([StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED])( + 'cancela %s e remove o Process SCHEDULING na mesma transação', + async (currentStatus) => { + const client = { + id: 'client-1', + name: 'Cliente', + surname: 'Teste', + email: 'cliente@example.com', + }; + const specialist = { + id: 'specialist-1', + name: 'Especialista', + surname: 'Teste', + email: 'especialista@example.com', + speciality: ProductType.CAR, + }; + const process = { + id: 'process-1', + status: ProcessStatus.SCHEDULING, + }; + const appointment = { + id: 'appointment-1', + client_id: client.id, + specialist_id: specialist.id, + product_type: null, + product_id: null, + status: currentStatus, + notes: null, + appointment_datetime: + currentStatus === StatusAgendamento.SCHEDULED + ? new Date('2099-01-01T10:00:00.000Z') + : null, + created_at: new Date('2026-01-01T00:00:00.000Z'), + updated_at: new Date('2026-01-01T00:00:00.000Z'), + client, + specialist, + process, + }; + const updatedAppointment = { + ...appointment, + status: StatusAgendamento.CANCELLED, + process: null, + }; + const deleteHistory = jest.fn().mockResolvedValue({ count: 1 }); + const deleteProcess = jest.fn().mockResolvedValue({ count: 1 }); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + findUniqueOrThrow: jest.fn().mockResolvedValue(updatedAppointment), + }, + process: { deleteMany: deleteProcess }, + processStatusHistory: { deleteMany: deleteHistory }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + const result = await service.updateStatus( + appointment.id, + { status: StatusAgendamento.CANCELLED }, + appointment.client_id, + UserRole.CUSTOMER, + ); + + expect(tx.appointment.updateMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ + id: appointment.id, + status: currentStatus, + updated_at: appointment.updated_at, + }), + data: expect.objectContaining({ + status: StatusAgendamento.CANCELLED, + }), + }), + ); + expect(deleteHistory).toHaveBeenCalledWith({ + where: { processId: process.id }, + }); + expect(deleteProcess).toHaveBeenCalledWith({ + where: { + id: process.id, + status: ProcessStatus.SCHEDULING, + }, + }); + expect(deleteHistory.mock.invocationCallOrder[0]).toBeLessThan( + deleteProcess.mock.invocationCallOrder[0], + ); + expect(result.status).toBe(StatusAgendamento.CANCELLED); + }, + ); + it('rejeita a transição quando perde a reivindicação concorrente do appointment', async () => { const appointment = { id: 'appointment-1', @@ -1978,3 +2074,73 @@ describe('AppointmentsService — sugestões compartilham ocupação da agenda', }, ); }); + +describe('AppointmentsService.cancelPending — serialização canônica', () => { + it('adquire o lock da agenda e revalida appointment/process dentro da transação', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.PENDING, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + client: { + id: 'client-1', + name: 'Cliente', + surname: 'Teste', + email: 'cliente@example.com', + }, + specialist: { + id: 'specialist-1', + name: 'Especialista', + surname: 'Teste', + email: 'especialista@example.com', + }, + process: { id: 'process-1', status: ProcessStatus.SCHEDULING }, + }; + const historyDelete = jest.fn().mockResolvedValue({ count: 1 }); + const processDelete = jest.fn().mockResolvedValue(appointment.process); + const appointmentDelete = jest.fn().mockResolvedValue(appointment); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + delete: appointmentDelete, + }, + process: { delete: processDelete }, + processStatusHistory: { deleteMany: historyDelete }, + }; + const prisma = { + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + }, + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const notifications = { + sendAppointmentCancelledEmail: jest.fn().mockResolvedValue(undefined), + }; + const service = new AppointmentsService( + prisma, + notifications as any, + {} as any, + ); + + await service.cancelPending(appointment.id, appointment.client_id); + + expect(tx.$queryRaw).toHaveBeenCalledWith( + expect.anything(), + 'appointment-schedule:specialist-1', + ); + expect(tx.appointment.findUnique).toHaveBeenCalledWith( + expect.objectContaining({ where: { id: appointment.id } }), + ); + expect(historyDelete).toHaveBeenCalledWith({ + where: { processId: appointment.process.id }, + }); + expect(processDelete).toHaveBeenCalledWith({ + where: { id: appointment.process.id }, + }); + expect(appointmentDelete).toHaveBeenCalledWith({ + where: { id: appointment.id }, + }); + }); +}); diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 6a61b74..d6a594d 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -636,6 +636,35 @@ export class AppointmentsService { }); } + // Cancellation must release the active scheduling process atomically. + // Keeping a SCHEDULING process linked to a CANCELLED appointment makes + // the product deduplication gate reject every subsequent request. + if ( + dto.status === StatusAgendamento.CANCELLED && + lockedAppointment.process + ) { + await tx.processStatusHistory.deleteMany({ + where: { processId: lockedAppointment.process.id }, + }); + const processClaim = await tx.process.deleteMany({ + where: { + id: lockedAppointment.process.id, + status: ProcessStatus.SCHEDULING, + }, + }); + if (processClaim.count !== 1) { + throw new ConflictException({ + success: false, + error: { + code: 'APPOINTMENT_CANCELLATION_CONFLICT', + message: + 'O processo foi alterado enquanto o agendamento era cancelado', + details: { appointment_id: id }, + }, + }); + } + } + const updatedAppointment = await tx.appointment.findUniqueOrThrow({ where: { id }, include: { @@ -1566,12 +1595,12 @@ export class AppointmentsService { `[cancelPending] Cancelando agendamento ${appointmentId} por ${userId}`, ); - const appointment = await this.prisma.appointment.findUnique({ + const candidate = await this.prisma.appointment.findUnique({ where: { id: appointmentId }, - include: { client: true, specialist: true, process: true }, + select: { id: true, client_id: true, specialist_id: true }, }); - if (!appointment) { + if (!candidate) { throw new NotFoundException({ success: false, error: { code: 404, message: 'Agendamento não encontrado' }, @@ -1579,8 +1608,8 @@ export class AppointmentsService { } // Apenas cliente ou especialista podem cancelar - const isClient = appointment.client_id === userId; - const isSpecialist = appointment.specialist_id === userId; + const isClient = candidate.client_id === userId; + const isSpecialist = candidate.specialist_id === userId; if (!isClient && !isSpecialist) { throw new ForbiddenException({ success: false, @@ -1591,33 +1620,55 @@ export class AppointmentsService { }); } - // Só pode cancelar PENDING - if (appointment.status !== StatusAgendamento.PENDING) { - throw new BadRequestException({ - success: false, - error: { - code: 400, - message: - 'Apenas agendamentos PENDING podem ser cancelados por esta rota', - details: { current_status: appointment.status }, - }, + // Serializar com confirmação/reagendamento e revalidar o estado sob lock. + const appointment = await this.prisma.$transaction(async (tx) => { + await acquireSpecialistScheduleLock(tx, candidate.specialist_id); + const lockedAppointment = await tx.appointment.findUnique({ + where: { id: appointmentId }, + include: { client: true, specialist: true, process: true }, }); - } + if (!lockedAppointment) { + throw new NotFoundException({ + success: false, + error: { code: 404, message: 'Agendamento não encontrado' }, + }); + } + if ( + lockedAppointment.client_id !== userId && + lockedAppointment.specialist_id !== userId + ) { + throw new ForbiddenException({ + success: false, + error: { + code: 403, + message: 'Sem permissão para cancelar este agendamento', + }, + }); + } + if (lockedAppointment.status !== StatusAgendamento.PENDING) { + throw new BadRequestException({ + success: false, + error: { + code: 400, + message: + 'Apenas agendamentos PENDING podem ser cancelados por esta rota', + details: { current_status: lockedAppointment.status }, + }, + }); + } - // Deletar appointment e process em transação - await this.prisma.$transaction(async (tx) => { // Se existe process, deletar histórico e process primeiro - if (appointment.process) { + if (lockedAppointment.process) { await tx.processStatusHistory.deleteMany({ - where: { processId: appointment.process.id }, + where: { processId: lockedAppointment.process.id }, }); await tx.process.delete({ - where: { id: appointment.process.id }, + where: { id: lockedAppointment.process.id }, }); this.logger.log( - `[cancelPending] Process ${appointment.process.id} deletado`, + `[cancelPending] Process ${lockedAppointment.process.id} deletado`, ); } @@ -1627,6 +1678,8 @@ export class AppointmentsService { }); this.logger.log(`[cancelPending] Appointment ${appointmentId} deletado`); + + return lockedAppointment; }); // Fire-and-forget: notificar a outra parte sobre o cancelamento diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts index 793cbf1..315f12a 100644 --- a/backend/src/features/processes/processes.service.spec.ts +++ b/backend/src/features/processes/processes.service.spec.ts @@ -1940,3 +1940,79 @@ describe('ProcessesService — matriz de contatos do cliente', () => { }, ); }); + +describe('ProcessesService.cancelAppointment — serialização canônica', () => { + it('adquire o lock da agenda e revalida processo/appointment dentro da transação', async () => { + const process = { + id: 'process-1', + client_id: clientId, + specialist_id: specialistId, + status: ProcessStatus.SCHEDULING, + product_type: ProductType.CAR, + appointment_id: 'appointment-1', + appointment: { + id: 'appointment-1', + client_id: clientId, + specialist_id: specialistId, + status: StatusAgendamento.SCHEDULED, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + }, + client: { + id: clientId, + name: 'Cliente', + surname: 'Teste', + email: 'cliente@example.com', + }, + specialist: { + id: specialistId, + name: 'Especialista', + surname: 'Teste', + email: 'especialista@example.com', + }, + car: { marca: 'Porsche', modelo: '911' }, + boat: null, + aircraft: null, + }; + const historyDelete = jest.fn().mockResolvedValue({ count: 1 }); + const processDelete = jest.fn().mockResolvedValue(process); + const appointmentDelete = jest.fn().mockResolvedValue(process.appointment); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + process: { + findUnique: jest.fn().mockResolvedValue(process), + delete: processDelete, + }, + appointment: { delete: appointmentDelete }, + processStatusHistory: { deleteMany: historyDelete }, + }; + const prisma = { + process: { + findUnique: jest.fn().mockResolvedValue(process), + }, + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const notifications = { + sendAppointmentCancelledEmail: jest.fn().mockResolvedValue(undefined), + }; + const service = new ProcessesService(prisma, notifications as any); + + await service.cancelAppointment(process.id, clientId); + + expect(tx.$queryRaw).toHaveBeenCalledWith( + expect.anything(), + `appointment-schedule:${specialistId}`, + ); + expect(tx.process.findUnique).toHaveBeenCalledWith( + expect.objectContaining({ where: { id: process.id } }), + ); + expect(historyDelete).toHaveBeenCalledWith({ + where: { processId: process.id }, + }); + expect(processDelete).toHaveBeenCalledWith({ + where: { id: process.id }, + }); + expect(appointmentDelete).toHaveBeenCalledWith({ + where: { id: process.appointment.id }, + }); + }); +}); diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts index 294f14b..b6e82bf 100644 --- a/backend/src/features/processes/processes.service.ts +++ b/backend/src/features/processes/processes.service.ts @@ -2166,30 +2166,18 @@ export class ProcessesService { `[cancelAppointment] Cancelando agendamento do processo ${processId}`, ); - // Buscar processo com appointment, client, specialist e produtos - const process = await this.prismaService.process.findUnique({ + const candidate = await this.prismaService.process.findUnique({ where: { id: processId }, - include: { - appointment: true, - client: { - select: { id: true, email: true, name: true, surname: true }, - }, - specialist: { - select: { id: true, email: true, name: true, surname: true }, - }, - car: true, - boat: true, - aircraft: true, - }, + select: { id: true, client_id: true, specialist_id: true }, }); - if (!process) { + if (!candidate) { throw new NotFoundException('Processo não encontrado'); } // Verificar se o usuário é o cliente ou especialista - const isClient = process.client_id === userId; - const isSpecialist = process.specialist_id === userId; + const isClient = candidate.client_id === userId; + const isSpecialist = candidate.specialist_id === userId; if (!isClient && !isSpecialist) { throw new ForbiddenException( @@ -2197,22 +2185,55 @@ export class ProcessesService { ); } - // Verificar se está em status SCHEDULING - if (process.status !== 'SCHEDULING') { - throw new BadRequestException( - 'Apenas processos em status SCHEDULING podem ter o agendamento cancelado', - ); - } - - // Verificar se tem appointment - if (!process.appointment) { - throw new NotFoundException( - 'Agendamento não encontrado para este processo', - ); - } + // Serializar com a confirmação e revalidar toda a relação sob lock. + const process = await this.prismaService.$transaction(async (tx) => { + await acquireSpecialistScheduleLock(tx, candidate.specialist_id); + const lockedProcess = await tx.process.findUnique({ + where: { id: processId }, + include: { + appointment: true, + client: { + select: { id: true, email: true, name: true, surname: true }, + }, + specialist: { + select: { id: true, email: true, name: true, surname: true }, + }, + car: true, + boat: true, + aircraft: true, + }, + }); + if (!lockedProcess) { + throw new NotFoundException('Processo não encontrado'); + } + if ( + lockedProcess.client_id !== userId && + lockedProcess.specialist_id !== userId + ) { + throw new ForbiddenException( + 'Sem permissão para cancelar este agendamento', + ); + } + if (lockedProcess.status !== ProcessStatus.SCHEDULING) { + throw new BadRequestException( + 'Apenas processos em status SCHEDULING podem ter o agendamento cancelado', + ); + } + if (!lockedProcess.appointment) { + throw new NotFoundException( + 'Agendamento não encontrado para este processo', + ); + } + if ( + lockedProcess.appointment.id !== lockedProcess.appointment_id || + lockedProcess.appointment.client_id !== lockedProcess.client_id || + lockedProcess.appointment.specialist_id !== lockedProcess.specialist_id + ) { + throw new BadRequestException( + 'Agendamento não corresponde aos participantes do processo', + ); + } - // Deletar appointment e process em transação - await this.prismaService.$transaction(async (tx) => { // Deletar histórico do processo await tx.processStatusHistory.deleteMany({ where: { processId }, @@ -2225,8 +2246,10 @@ export class ProcessesService { // Deletar appointment await tx.appointment.delete({ - where: { id: process.appointment!.id }, + where: { id: lockedProcess.appointment.id }, }); + + return lockedProcess; }); this.logger.log( From cfe4779ad2bd019f055c52d155f03eaae9f06d8c Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 11:48:51 -0300 Subject: [PATCH 23/60] fix(appointments): scope office listings by company --- .../appointments-list-scope.spec.ts | 176 ++++++++++++++++++ .../appointments/appointments.service.ts | 75 ++++++-- 2 files changed, 240 insertions(+), 11 deletions(-) create mode 100644 backend/src/features/appointments/appointments-list-scope.spec.ts diff --git a/backend/src/features/appointments/appointments-list-scope.spec.ts b/backend/src/features/appointments/appointments-list-scope.spec.ts new file mode 100644 index 0000000..cc91be5 --- /dev/null +++ b/backend/src/features/appointments/appointments-list-scope.spec.ts @@ -0,0 +1,176 @@ +import { ForbiddenException } from '@nestjs/common'; +import { StatusAgendamento, UserRole } from '@prisma/client'; +import { AppointmentsService } from './appointments.service'; + +describe('AppointmentsService.getAppointments — escopo de visibilidade', () => { + function harness(companyId: string | null = 'company-a') { + const count = jest.fn().mockResolvedValue(3); + const findMany = jest.fn().mockResolvedValue([]); + const groupBy = jest.fn().mockResolvedValue([ + { status: StatusAgendamento.SCHEDULED, _count: 2 }, + { status: StatusAgendamento.COMPLETED, _count: 1 }, + ]); + const userFindUnique = jest.fn().mockResolvedValue({ company_id: companyId }); + const prisma = { + user: { findUnique: userFindUnique }, + appointment: { count, findMany, groupBy }, + } as any; + + return { + service: new AppointmentsService(prisma, {} as any, {} as any), + count, + findMany, + groupBy, + userFindUnique, + }; + } + + it.each(['company-a', 'company-b'])( + 'restringe OFFICE aos clientes vinculados à própria empresa (%s)', + async (companyId) => { + const { service, count, findMany, groupBy, userFindUnique } = + harness(companyId); + + const result = await service.getAppointments( + { page: 2, limit: 2, client_id: 'requested-client' }, + 'office-user', + UserRole.OFFICE, + ); + + expect(userFindUnique).toHaveBeenCalledWith({ + where: { id: 'office-user' }, + select: { company_id: true }, + }); + + const tenantScope = { + client: { + role: UserRole.CUSTOMER, + OR: [ + { consultant: { company_id: companyId } }, + { company_id: companyId }, + ], + }, + }; + const expectedWhere = { + AND: [tenantScope], + client_id: 'requested-client', + }; + + expect(count).toHaveBeenCalledWith({ where: expectedWhere }); + expect(findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: expectedWhere, + skip: 2, + take: 2, + }), + ); + expect(groupBy).toHaveBeenCalledWith( + expect.objectContaining({ where: expectedWhere }), + ); + expect(result).toEqual( + expect.objectContaining({ + success: true, + data: [], + meta: { + pagination: { + current_page: 2, + per_page: 2, + total: 3, + total_pages: 2, + has_next: false, + has_prev: true, + }, + summary: { upcoming: 2, completed: 1, cancelled: 0 }, + }, + }), + ); + }, + ); + + it('barra OFFICE sem company_id antes de consultar agendamentos', async () => { + const { service, count, findMany, groupBy } = harness(null); + + await expect( + service.getAppointments({}, 'office-without-company', UserRole.OFFICE), + ).rejects.toThrow(ForbiddenException); + + expect(count).not.toHaveBeenCalled(); + expect(findMany).not.toHaveBeenCalled(); + expect(groupBy).not.toHaveBeenCalled(); + }); + + it('barra papel desconhecido por padrão', async () => { + const { service, userFindUnique, count } = harness(); + + await expect( + service.getAppointments({}, 'unknown-user', 'NEW_ROLE' as UserRole), + ).rejects.toThrow(ForbiddenException); + + expect(userFindUnique).not.toHaveBeenCalled(); + expect(count).not.toHaveBeenCalled(); + }); + + it.each([ + [UserRole.CUSTOMER, 'customer-user', { client_id: 'customer-user' }], + [ + UserRole.SPECIALIST, + 'specialist-user', + { + OR: [ + { specialist_id: 'specialist-user' }, + { client_id: 'specialist-user' }, + ], + }, + ], + [ + UserRole.CONSULTANT, + 'consultant-user', + { + OR: [ + { specialist_id: 'consultant-user' }, + { client_id: 'consultant-user' }, + ], + }, + ], + ])('preserva o escopo de %s', async (role, userId, expectedWhere) => { + const { service, userFindUnique, count, findMany, groupBy } = harness(); + + await service.getAppointments({}, userId, role as UserRole); + + expect(userFindUnique).not.toHaveBeenCalled(); + expect(count).toHaveBeenCalledWith({ where: expectedWhere }); + expect(findMany).toHaveBeenCalledWith( + expect.objectContaining({ where: expectedWhere }), + ); + expect(groupBy).toHaveBeenCalledWith( + expect.objectContaining({ where: expectedWhere }), + ); + }); + + it('preserva a visão global e a resposta paginada do ADMIN', async () => { + const { service, userFindUnique, count, findMany, groupBy } = harness(); + + const result = await service.getAppointments( + { page: 1, limit: 20 }, + 'admin-user', + UserRole.ADMIN, + ); + + expect(userFindUnique).not.toHaveBeenCalled(); + expect(count).toHaveBeenCalledWith({ where: {} }); + expect(findMany).toHaveBeenCalledWith( + expect.objectContaining({ where: {}, skip: 0, take: 20 }), + ); + expect(groupBy).toHaveBeenCalledWith( + expect.objectContaining({ where: {} }), + ); + expect(result.meta.pagination).toEqual({ + current_page: 1, + per_page: 20, + total: 3, + total_pages: 1, + has_next: false, + has_prev: false, + }); + }); +}); diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index d6a594d..920232b 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -260,6 +260,7 @@ export class AppointmentsService { * Respeita permissões por role: * - CUSTOMER: vê apenas seus próprios agendamentos * - SPECIALIST/CONSULTANT: vê como especialista + seus clientes + * - OFFICE: vê clientes vinculados à própria empresa * - ADMIN: vê todos * * @param query Query parameters (paginação, filtros, ordenação) @@ -295,20 +296,72 @@ export class AppointmentsService { const limit = query.limit || 20; const skip = (page - 1) * limit; - // Construir filtro WHERE conforme permissões + // Construir filtro WHERE conforme permissões. ADMIN é o único papel com + // visão global; qualquer papel sem regra explícita deve falhar fechado. const where: any = {}; - // Aplicar filtros de role - if (userRole === UserRole.CUSTOMER) { - where.client_id = userId; // Customer vê apenas seus agendamentos como cliente - } else if ( - userRole === UserRole.SPECIALIST || - userRole === UserRole.CONSULTANT - ) { - // Specialist vê como especialista OU como cliente - where.OR = [{ specialist_id: userId }, { client_id: userId }]; + switch (userRole) { + case UserRole.ADMIN: + break; + + case UserRole.CUSTOMER: + where.client_id = userId; + break; + + case UserRole.SPECIALIST: + case UserRole.CONSULTANT: + where.OR = [{ specialist_id: userId }, { client_id: userId }]; + break; + + case UserRole.OFFICE: { + const office = await this.prisma.user.findUnique({ + where: { id: userId }, + select: { company_id: true }, + }); + if (!office?.company_id) { + this.logger.error( + `[getAppointments] OFFICE user=${userId} sem company_id — config inválida`, + ); + throw new ForbiddenException({ + success: false, + error: { + code: 403, + message: 'Escritório sem empresa vinculada', + details: { user_id: userId }, + }, + }); + } + + // Mantém a mesma definição de cliente do escritório aplicada por + // OfficeService.listClients e ProcessesService: vínculo direto com a + // empresa ou indireto por um consultor pertencente a ela. + where.AND = [ + { + client: { + role: UserRole.CUSTOMER, + OR: [ + { consultant: { company_id: office.company_id } }, + { company_id: office.company_id }, + ], + }, + }, + ]; + break; + } + + default: + this.logger.warn( + `[getAppointments] acesso negado role=${userRole} user=${userId}`, + ); + throw new ForbiddenException({ + success: false, + error: { + code: 403, + message: 'Acesso negado', + details: { user_id: userId }, + }, + }); } - // ADMIN vê todos (sem filtro de user_id) // Aplicar filtros de query if (query.status) { From 0b35e2844a41e338b84b348fa79a0d79c26dc254 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 11:51:57 -0300 Subject: [PATCH 24/60] fix(processes): enforce scoped authorization --- .../processes/processes.controller.ts | 37 +- .../processes/processes.service.spec.ts | 352 +++++++++++++++++- .../features/processes/processes.service.ts | 224 +++++++++-- 3 files changed, 561 insertions(+), 52 deletions(-) diff --git a/backend/src/features/processes/processes.controller.ts b/backend/src/features/processes/processes.controller.ts index a3c72a9..5574965 100644 --- a/backend/src/features/processes/processes.controller.ts +++ b/backend/src/features/processes/processes.controller.ts @@ -143,12 +143,13 @@ export class ProcessesController { @Get(':id') async getById( @Param('id', new ParseUUIDPipe()) processId: string, - @Req() req: { user?: { id: string; role?: string } }, + @Req() req: { user?: UserEntity }, ): Promise> { const process = await this.processesService.getById( processId, req.user?.id, req.user?.role, + req.user?.company_id, ); return { @@ -253,6 +254,7 @@ export class ProcessesController { updateProcessDto, userId, userRole, + req.user?.company_id, ); return { @@ -314,9 +316,20 @@ export class ProcessesController { @Get(':id/completion-reason') async getCompletionReason( @Param('id', new ParseUUIDPipe()) processId: string, + @Req() req: { user?: UserEntity }, ): Promise> { - const reason = - await this.processesService.getProcessCompletionReason(processId); + const user = req.user; + if (!user) { + throw new UnauthorizedException('Usuário autenticado não identificado'); + } + const reason = await this.processesService.getProcessCompletionReason( + processId, + { + id: user.id, + role: user.role, + companyId: user.company_id, + }, + ); return { success: true, @@ -336,9 +349,18 @@ export class ProcessesController { @Get(':id/with-contract') async getWithContract( @Param('id', new ParseUUIDPipe()) processId: string, + @Req() req: { user?: UserEntity }, ): Promise> { + const user = req.user; + if (!user) { + throw new UnauthorizedException('Usuário autenticado não identificado'); + } const processWithContract = - await this.processesService.getByIdWithActiveContract(processId); + await this.processesService.getByIdWithActiveContract(processId, { + id: user.id, + role: user.role, + companyId: user.company_id, + }); return { success: true, @@ -412,11 +434,18 @@ export class ProcessesController { @Req() req: any, ): Promise> { const userId = req.user?.sub || req.user?.id; + const userRole = req.user?.role; + + if (!userId || !userRole) { + throw new UnauthorizedException('Usuário autenticado não identificado'); + } const result = await this.processesService.rejectProcess( processId, userId, rejectProcessDto.rejection_reason, + userRole, + req.user?.company_id, ); return { diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts index 315f12a..616b398 100644 --- a/backend/src/features/processes/processes.service.spec.ts +++ b/backend/src/features/processes/processes.service.spec.ts @@ -1845,7 +1845,6 @@ describe('ProcessesService — matriz de contatos do cliente', () => { [UserRole.ADMIN, 'admin-1'], [UserRole.CONSULTANT, 'consultant-1'], [UserRole.CUSTOMER, clientId], - [undefined, undefined], ] as const)('detail gives %s no client contacts', async (role, id) => { const result = await makeService( StatusAgendamento.PENDING, @@ -1857,6 +1856,16 @@ describe('ProcessesService — matriz de contatos do cliente', () => { expect(result.specialist.phone).toBeNull(); }); + it('detail denies an unidentified actor', async () => { + await expect( + makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getById('process-1', undefined, undefined), + ).rejects.toThrow(ForbiddenException); + }); + it.each([ [UserRole.SPECIALIST, 'other-specialist'], [UserRole.OFFICE, 'office-1'], @@ -1870,14 +1879,14 @@ describe('ProcessesService — matriz de contatos do cliente', () => { ).rejects.toThrow(ForbiddenException); }); - it('an actor with the specialist ID but another role cannot read client contacts', async () => { - const result = await makeService( - StatusAgendamento.PENDING, - AppointmentSchedulingMethod.EMAIL, - ProcessStatus.SCHEDULING, - ).getById('process-1', specialistId, UserRole.CONSULTANT); - expect(result.client).not.toHaveProperty('email'); - expect(result.client.phone).toBeNull(); + it('an actor with the specialist ID but another role cannot read the detail', async () => { + await expect( + makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getById('process-1', specialistId, UserRole.CONSULTANT), + ).rejects.toThrow(ForbiddenException); }); it('client list and unscoped legacy specialist projection contain no client contacts', async () => { @@ -1941,6 +1950,331 @@ describe('ProcessesService — matriz de contatos do cliente', () => { ); }); +describe('ProcessesService — autorização centralizada de processos', () => { + const ownerClientId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; + const assignedSpecialistId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'; + const outsiderId = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc'; + const consultantId = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd'; + const clientCompanyId = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee'; + const otherCompanyId = 'ffffffff-ffff-4fff-8fff-ffffffffffff'; + + function protectedProcess(overrides: Record = {}) { + return { + id: '99999999-9999-4999-8999-999999999999', + client_id: ownerClientId, + specialist_id: assignedSpecialistId, + status: ProcessStatus.SCHEDULING, + updated_at: new Date('2026-01-01T00:00:00.000Z'), + notes: null, + product_type: null, + active_contract_id: 'contract-1', + created_at: new Date('2026-01-01T00:00:00.000Z'), + client: { + id: ownerClientId, + email: 'cliente@example.com', + name: 'Cliente', + surname: 'Teste', + consultant_id: consultantId, + company_id: null, + consultant: { company_id: clientCompanyId }, + }, + specialist: { + id: assignedSpecialistId, + email: 'especialista@example.com', + name: 'Especialista', + surname: 'Teste', + }, + car: null, + boat: null, + aircraft: null, + ...overrides, + }; + } + + function updateService(process = protectedProcess()) { + const processUpdateMany = jest.fn().mockResolvedValue({ count: 1 }); + const tx = { + process: { + findUniqueOrThrow: jest.fn().mockResolvedValue(process), + updateMany: processUpdateMany, + }, + processStatusHistory: { + create: jest.fn().mockResolvedValue({}), + findMany: jest.fn().mockResolvedValue([]), + }, + }; + const prisma = { + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + return { + service: new ProcessesService(prisma, { + sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined), + } as any), + processUpdateMany, + }; + } + + function rejectionService(process = protectedProcess()) { + const processUpdate = jest.fn().mockResolvedValue({ + ...process, + status: ProcessStatus.REJECTED, + updated_at: new Date('2026-01-02T00:00:00.000Z'), + }); + const tx = { + process: { + findUniqueOrThrow: jest.fn().mockResolvedValue(process), + update: processUpdate, + }, + processStatusHistory: { + create: jest.fn().mockResolvedValue({}), + findMany: jest.fn().mockResolvedValue([]), + }, + processRejection: { create: jest.fn().mockResolvedValue({}) }, + }; + const prisma = { + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + return { + service: new ProcessesService(prisma, { + sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined), + } as any), + processUpdate, + }; + } + + it.each([ + ProcessStatus.NEGOTIATION, + ProcessStatus.DOCUMENTATION, + ProcessStatus.COMPLETED, + ])('CUSTOMER não pode avançar seu processo para %s', async (nextStatus) => { + const { service, processUpdateMany } = updateService(); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: nextStatus, notes: 'tentativa indevida' }, + ownerClientId, + UserRole.CUSTOMER, + ), + ).rejects.toThrow(ForbiddenException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('OFFICE de outra empresa não pode alterar status', async () => { + const { service, processUpdateMany } = updateService(); + + await expect( + (service.update as any)( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.NEGOTIATION }, + 'office-1', + UserRole.OFFICE, + otherCompanyId, + ), + ).rejects.toThrow(ForbiddenException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('especialista atribuído não pode pular de SCHEDULING para COMPLETED', async () => { + const { service, processUpdateMany } = updateService(); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.COMPLETED }, + assignedSpecialistId, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(BadRequestException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('especialista atribuído pode fazer a transição adjacente SCHEDULING para NEGOTIATION', async () => { + const { service, processUpdateMany } = updateService(); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.NEGOTIATION }, + assignedSpecialistId, + UserRole.SPECIALIST, + ), + ).resolves.toBeDefined(); + + expect(processUpdateMany).toHaveBeenCalledTimes(1); + }); + + it('OFFICE da empresa do cliente pode fazer transição adjacente', async () => { + const { service, processUpdateMany } = updateService(); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.NEGOTIATION }, + 'office-1', + UserRole.OFFICE, + clientCompanyId, + ), + ).resolves.toBeDefined(); + + expect(processUpdateMany).toHaveBeenCalledTimes(1); + }); + + it('outsider não pode rejeitar processo alheio', async () => { + const { service, processUpdate } = rejectionService(); + + await expect( + (service.rejectProcess as any)( + '99999999-9999-4999-8999-999999999999', + outsiderId, + undefined, + UserRole.CUSTOMER, + null, + ), + ).rejects.toThrow(ForbiddenException); + + expect(processUpdate).not.toHaveBeenCalled(); + }); + + it('cliente pode rejeitar o próprio processo ativo', async () => { + const { service, processUpdate } = rejectionService(); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + ownerClientId, + 'Não tenho mais interesse', + UserRole.CUSTOMER, + ), + ).resolves.toEqual( + expect.objectContaining({ status: ProcessStatus.REJECTED }), + ); + + expect(processUpdate).toHaveBeenCalledTimes(1); + }); + + it('não permite rejeitar processo já concluído', async () => { + const { service, processUpdate } = rejectionService( + protectedProcess({ status: ProcessStatus.COMPLETED }), + ); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + assignedSpecialistId, + undefined, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(BadRequestException); + + expect(processUpdate).not.toHaveBeenCalled(); + }); + + it.each([ + ['completion reason', 'getProcessCompletionReason'], + ['active contract', 'getByIdWithActiveContract'], + ])('outsider não pode ler %s', async (_label, method) => { + const prisma = { + process: { findUnique: jest.fn().mockResolvedValue(protectedProcess()) }, + processStatusHistory: { + findFirst: jest.fn().mockResolvedValue({ reason: 'CONTRACT_SIGNED' }), + }, + contract: { + findUnique: jest.fn().mockResolvedValue({ id: 'contract-1' }), + }, + } as any; + const service = new ProcessesService(prisma, {} as any); + + await expect( + (service[method] as any)('99999999-9999-4999-8999-999999999999', { + id: outsiderId, + role: UserRole.CUSTOMER, + companyId: null, + }), + ).rejects.toThrow(ForbiddenException); + }); + + it.each([ + ['completion reason', 'getProcessCompletionReason'], + ['active contract', 'getByIdWithActiveContract'], + ])('OFFICE de outra empresa não pode ler %s', async (_label, method) => { + const prisma = { + process: { findUnique: jest.fn().mockResolvedValue(protectedProcess()) }, + processStatusHistory: { + findFirst: jest.fn().mockResolvedValue({ reason: 'CONTRACT_SIGNED' }), + }, + contract: { + findUnique: jest.fn().mockResolvedValue({ id: 'contract-1' }), + }, + } as any; + const service = new ProcessesService(prisma, {} as any); + + await expect( + (service[method] as any)('99999999-9999-4999-8999-999999999999', { + id: 'office-1', + role: UserRole.OFFICE, + companyId: otherCompanyId, + }), + ).rejects.toThrow(ForbiddenException); + }); + + it.each([ + [UserRole.CONSULTANT, consultantId, null], + [UserRole.OFFICE, 'office-1', clientCompanyId], + ])( + '%s vinculado ao cliente pode ler contrato ativo', + async (role, id, companyId) => { + const prisma = { + process: { + findUnique: jest.fn().mockResolvedValue(protectedProcess()), + }, + contract: { + findUnique: jest.fn().mockResolvedValue({ id: 'contract-1' }), + }, + } as any; + const service = new ProcessesService(prisma, {} as any); + + await expect( + service.getByIdWithActiveContract( + '99999999-9999-4999-8999-999999999999', + { id, role, companyId }, + ), + ).resolves.toEqual( + expect.objectContaining({ id: protectedProcess().id }), + ); + }, + ); + + it('OFFICE mantém acesso quando o consultor é da empresa, mesmo com vínculo direto legado diferente', async () => { + const process = protectedProcess({ + client: { + id: ownerClientId, + consultant_id: consultantId, + company_id: otherCompanyId, + consultant: { company_id: clientCompanyId }, + }, + }); + const prisma = { + process: { findUnique: jest.fn().mockResolvedValue(process) }, + contract: { + findUnique: jest.fn().mockResolvedValue({ id: 'contract-1' }), + }, + } as any; + const service = new ProcessesService(prisma, {} as any); + + await expect( + service.getByIdWithActiveContract(process.id, { + id: 'office-1', + role: UserRole.OFFICE, + companyId: clientCompanyId, + }), + ).resolves.toEqual(expect.objectContaining({ id: process.id })); + }); +}); + describe('ProcessesService.cancelAppointment — serialização canônica', () => { it('adquire o lock da agenda e revalida processo/appointment dentro da transação', async () => { const process = { diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts index b6e82bf..36b8f52 100644 --- a/backend/src/features/processes/processes.service.ts +++ b/backend/src/features/processes/processes.service.ts @@ -51,6 +51,30 @@ export type ProcessesRequester = { companyId?: string | null; }; +type ProcessAccessAction = 'read' | 'update-status' | 'reject'; + +type ProcessAccessRecord = { + client_id: string; + specialist_id: string; + client?: { + consultant_id?: string | null; + company_id?: string | null; + consultant?: { company_id?: string | null } | null; + } | null; +}; + +const PROCESS_STATUS_TRANSITIONS: Record< + ProcessStatus, + readonly ProcessStatus[] +> = { + [ProcessStatus.SCHEDULING]: [ProcessStatus.NEGOTIATION], + [ProcessStatus.NEGOTIATION]: [ProcessStatus.DOCUMENTATION], + [ProcessStatus.PROCESSING_CONTRACT]: [ProcessStatus.DOCUMENTATION], + [ProcessStatus.DOCUMENTATION]: [ProcessStatus.COMPLETED], + [ProcessStatus.COMPLETED]: [], + [ProcessStatus.REJECTED]: [], +}; + /** * Dados para abrir um processo em nome de um cliente. * @@ -76,6 +100,62 @@ export class ProcessesService { private readonly notificationService: NotificationService, ) {} + /** + * Política única de acesso a um processo. Todo papel desconhecido e toda + * combinação de ação/vínculo não declarada são negados por padrão. + */ + private assertProcessAccess( + process: ProcessAccessRecord, + requester: ProcessesRequester, + action: ProcessAccessAction, + ): void { + const isAssignedSpecialist = + requester.role === UserRole.SPECIALIST && + process.specialist_id === requester.id; + const isClient = + requester.role === UserRole.CUSTOMER && + process.client_id === requester.id; + const isClientConsultant = + requester.role === UserRole.CONSULTANT && + process.client?.consultant_id === requester.id; + const isClientOffice = + requester.role === UserRole.OFFICE && + !!requester.companyId && + (process.client?.company_id === requester.companyId || + process.client?.consultant?.company_id === requester.companyId); + + const allowed = + requester.role === UserRole.ADMIN || + (action === 'read' && + (isAssignedSpecialist || + isClient || + isClientConsultant || + isClientOffice)) || + (action === 'update-status' && + (isAssignedSpecialist || isClientOffice)) || + (action === 'reject' && (isAssignedSpecialist || isClient)); + + if (!allowed) { + this.logger.warn( + `[process-access] negado action=${action} role=${requester.role} user=${requester.id}`, + ); + throw new ForbiddenException( + 'Você não tem permissão para acessar este processo', + ); + } + } + + private assertStatusTransition( + currentStatus: ProcessStatus, + nextStatus: ProcessStatus, + ): void { + if (!PROCESS_STATUS_TRANSITIONS[currentStatus]?.includes(nextStatus)) { + throw new BadRequestException( + `Transição de ${currentStatus} para ${nextStatus} não permitida`, + ); + } + } + /** * Cria um objeto "product" de acordo com o processo enviado * @@ -788,13 +868,18 @@ export class ProcessesService { async getById( processId: string, userId?: string, - userRole?: string, + userRole?: UserRole, + companyId?: string | null, ): Promise { try { const process = await this.prismaService.process.findUniqueOrThrow({ where: { id: processId }, include: { - client: true, + client: { + include: { + consultant: { select: { company_id: true } }, + }, + }, car: true, boat: true, aircraft: true, @@ -811,23 +896,15 @@ export class ProcessesService { }, }); - if (userId && userRole !== 'ADMIN') { - const isParticipant = - process.client_id === userId || - process.specialist_id === userId || - process.client?.consultant_id === userId; - - if (!isParticipant) { - throw new ForbiddenException({ - success: false, - error: { - code: 403, - message: 'Você não é participante deste processo', - details: { user_id: userId, process_id: processId }, - }, - }); - } - } + this.assertProcessAccess( + process, + { + id: userId ?? '', + role: userRole as UserRole, + companyId, + }, + 'read', + ); const contactVisible = this.isAppointmentContactVisible( process.appointment?.status, @@ -1096,6 +1173,7 @@ export class ProcessesService { updateProcessDto: UpdateProcessDto, callerId?: string, callerRole?: UserRole, + callerCompanyId?: string | null, ): Promise { try { // Transction para atualizar o processo, adicionar mais uma linha sobre o histórico de status do processo, e obter o histórico atualizado @@ -1106,7 +1184,14 @@ export class ProcessesService { where: { id: processId }, include: { client: { - select: { email: true, name: true, surname: true }, + select: { + email: true, + name: true, + surname: true, + consultant_id: true, + company_id: true, + consultant: { select: { company_id: true } }, + }, }, specialist: { select: { email: true, name: true, surname: true }, @@ -1117,33 +1202,40 @@ export class ProcessesService { }, }); - // Autorização: apenas participantes do processo (cliente ou especialista) - // ou staff (ADMIN/OFFICE) podem alterar o status. Evita que qualquer - // usuário autenticado dirija um processo alheio. - const isStaff = - callerRole === UserRole.ADMIN || callerRole === UserRole.OFFICE; - const isParticipant = - !!callerId && - (existingProcess.client_id === callerId || - existingProcess.specialist_id === callerId); - if (!isStaff && !isParticipant) { - throw new ForbiddenException( - 'Você não tem permissão para alterar este processo', - ); - } + this.assertProcessAccess( + existingProcess, + { + id: callerId ?? '', + role: callerRole as UserRole, + companyId: callerCompanyId, + }, + 'update-status', + ); //Verificar se ele já está com o status atualizado if (existingProcess.status === updateProcessDto.status) { throw new BadRequestException(); } + this.assertStatusTransition( + existingProcess.status, + updateProcessDto.status, + ); + if (updateProcessDto.status === ProcessStatus.NEGOTIATION) { await lockNegotiationProductMoney(tx, existingProcess); existingProcess = await tx.process.findUniqueOrThrow({ where: { id: processId }, include: { client: { - select: { email: true, name: true, surname: true }, + select: { + email: true, + name: true, + surname: true, + consultant_id: true, + company_id: true, + consultant: { select: { company_id: true } }, + }, }, specialist: { select: { email: true, name: true, surname: true }, @@ -1614,10 +1706,24 @@ export class ProcessesService { * @returns {Promise} - Razão de conclusão ou null * @throws {NotFoundException} - Processo não encontrado */ - async getProcessCompletionReason(processId: string): Promise { + async getProcessCompletionReason( + processId: string, + requester: ProcessesRequester, + ): Promise { const process = await this.prismaService.process.findUnique({ where: { id: processId }, - select: { id: true }, + select: { + id: true, + client_id: true, + specialist_id: true, + client: { + select: { + consultant_id: true, + company_id: true, + consultant: { select: { company_id: true } }, + }, + }, + }, }); if (!process) { @@ -1626,6 +1732,8 @@ export class ProcessesService { ); } + this.assertProcessAccess(process, requester, 'read'); + const statusHistory = await this.prismaService.processStatusHistory.findFirst({ where: { processId }, @@ -1643,13 +1751,21 @@ export class ProcessesService { * @returns {Promise} - Processo com contrato ativo * @throws {NotFoundException} - Processo não encontrado */ - async getByIdWithActiveContract(processId: string): Promise { + async getByIdWithActiveContract( + processId: string, + requester: ProcessesRequester, + ): Promise { const process = await this.prismaService.process.findUnique({ where: { id: processId }, include: { car: true, boat: true, aircraft: true, + client: { + include: { + consultant: { select: { company_id: true } }, + }, + }, }, }); @@ -1659,6 +1775,8 @@ export class ProcessesService { ); } + this.assertProcessAccess(process, requester, 'read'); + // Se houver contrato ativo, buscar seus dados completos let activeContract = null; if (process.active_contract_id) { @@ -1832,6 +1950,8 @@ export class ProcessesService { processId: string, rejectedById: string, rejectionReason?: string, + requesterRole?: UserRole, + requesterCompanyId?: string | null, ): Promise { try { const [updatedProcess, updatedStatusHistory] = @@ -1841,7 +1961,15 @@ export class ProcessesService { where: { id: processId }, include: { client: { - select: { id: true, email: true, name: true, surname: true }, + select: { + id: true, + email: true, + name: true, + surname: true, + consultant_id: true, + company_id: true, + consultant: { select: { company_id: true } }, + }, }, specialist: { select: { id: true, email: true, name: true, surname: true }, @@ -1852,10 +1980,25 @@ export class ProcessesService { }, }); + this.assertProcessAccess( + existingProcess, + { + id: rejectedById ?? '', + role: requesterRole as UserRole, + companyId: requesterCompanyId, + }, + 'reject', + ); + // Verificar se já está rejeitado if (existingProcess.status === 'REJECTED') { throw new BadRequestException('Processo já está rejeitado'); } + if (existingProcess.status === ProcessStatus.COMPLETED) { + throw new BadRequestException( + 'Processo concluído não pode ser rejeitado', + ); + } // Atualizar status para REJECTED const process = await tx.process.update({ @@ -1922,6 +2065,9 @@ export class ProcessesService { status_history: updatedStatusHistory, }; } catch (err) { + if (err instanceof HttpException) { + throw err; + } if (err.code === 'P2025') { throw new NotFoundException('Processo não encontrado'); } From e607311e1a27e342562a5bdf29772639753b69b3 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 11:56:24 -0300 Subject: [PATCH 25/60] fix(appointments): serialize cancellation with process advances --- .../appointments-concurrency.postgres.spec.ts | 47 +++++++++++++ .../appointments/appointments.service.spec.ts | 69 ++++++++++++++++++- .../appointments/appointments.service.ts | 27 ++++++++ .../dto/get-appointments-query.dto.ts | 3 +- .../dto/update-appointment-status.dto.ts | 12 ++-- .../processes/processes.service.spec.ts | 15 ++++ .../features/processes/processes.service.ts | 49 +++++++++++++ 7 files changed, 213 insertions(+), 9 deletions(-) diff --git a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts index 7770c97..503ccf5 100644 --- a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts +++ b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts @@ -87,6 +87,7 @@ describeWithPostgres( sendAppointmentConfirmedEmail: jest.fn().mockResolvedValue(undefined), sendAppointmentRescheduledEmail: jest.fn().mockResolvedValue(undefined), sendAppointmentCancelledEmail: jest.fn().mockResolvedValue(undefined), + sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined), }; beforeAll(async () => { @@ -686,6 +687,52 @@ describeWithPostgres( expect(replacement.process_id).not.toBe(request.process_id); }, 15_000); + it.each(['appointment', 'process'] as const)( + 'serializes %s cancellation against a process status advance', + async (route) => { + const request = await createRequest(holder, 0); + const outcomes = await race((a, b) => [ + route === 'appointment' + ? appointments(first, a).cancelPending(request.id, clientIds[0]) + : processes(first, a).cancelAppointment( + request.process_id, + clientIds[0], + ), + processes(second, b).update( + request.process_id, + { + status: ProcessStatus.NEGOTIATION, + notes: 'advance concorrente', + }, + specialistId, + UserRole.SPECIALIST, + ), + ]); + + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + const storedProcess = await holder.process.findUnique({ + where: { id: request.process_id }, + }); + const storedAppointment = await holder.appointment.findUnique({ + where: { id: request.id }, + }); + if (outcomes[0].status === 'fulfilled') { + expect(storedProcess).toBeNull(); + expect(storedAppointment).toBeNull(); + } else { + expect(storedProcess).toMatchObject({ + status: ProcessStatus.NEGOTIATION, + }); + expect(storedAppointment).toMatchObject({ + status: StatusAgendamento.PENDING, + }); + } + }, + 15_000, + ); + function callback( client: PrismaClient, attempted: Deferred, diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts index 2140c45..fa70ac0 100644 --- a/backend/src/features/appointments/appointments.service.spec.ts +++ b/backend/src/features/appointments/appointments.service.spec.ts @@ -11,6 +11,7 @@ import { validate } from 'class-validator'; import { CreateAppointmentDto } from './dto/create-appointment.dto'; import { CreatePendingAppointmentDto } from './dto/create-pending-appointment.dto'; import { CreatePlatformAppointmentDto } from './dto/create-platform-appointment.dto'; +import { GetAppointmentsQueryDto } from './dto/get-appointments-query.dto'; import { AppointmentsService } from './appointments.service'; import { BadRequestException, @@ -108,6 +109,23 @@ describe('CreateAppointmentDto — seleção de produto', () => { }); }); +describe('GetAppointmentsQueryDto — limite de paginação', () => { + it('rejeita limit maior que 100', async () => { + const dto = Object.assign(new GetAppointmentsQueryDto(), { limit: 101 }); + + const errors = await validate(dto); + + expect(errors).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + property: 'limit', + constraints: expect.objectContaining({ max: expect.any(String) }), + }), + ]), + ); + }); +}); + describe('AppointmentsService.createPending — associação e atomicidade', () => { const client = { id: 'client-1', @@ -1000,6 +1018,37 @@ describe('AppointmentsService.createPending — integridade das partes', () => { }); describe('AppointmentsService.updateStatus — snapshot da negociação', () => { + it.each([ProcessStatus.NEGOTIATION, ProcessStatus.DOCUMENTATION])( + 'rejeita cancelamento quando o Process já avançou para %s antes de iniciar a transação', + async (processStatus) => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.SCHEDULED, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + process: { id: 'process-1', status: processStatus }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(), + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + await expect( + service.updateStatus( + appointment.id, + { status: StatusAgendamento.CANCELLED }, + appointment.client_id, + UserRole.CUSTOMER, + ), + ).rejects.toThrow( + 'Não é possível cancelar uma reunião cujo processo já avançou', + ); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }, + ); + it.each([StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED])( 'cancela %s e remove o Process SCHEDULING na mesma transação', async (currentStatus) => { @@ -2095,9 +2144,14 @@ describe('AppointmentsService.cancelPending — serialização canônica', () => surname: 'Teste', email: 'especialista@example.com', }, - process: { id: 'process-1', status: ProcessStatus.SCHEDULING }, + process: { + id: 'process-1', + status: ProcessStatus.SCHEDULING, + updated_at: new Date('2026-01-01T00:00:00.000Z'), + }, }; const historyDelete = jest.fn().mockResolvedValue({ count: 1 }); + const processClaim = jest.fn().mockResolvedValue({ count: 1 }); const processDelete = jest.fn().mockResolvedValue(appointment.process); const appointmentDelete = jest.fn().mockResolvedValue(appointment); const tx = { @@ -2106,7 +2160,7 @@ describe('AppointmentsService.cancelPending — serialização canônica', () => findUnique: jest.fn().mockResolvedValue(appointment), delete: appointmentDelete, }, - process: { delete: processDelete }, + process: { updateMany: processClaim, delete: processDelete }, processStatusHistory: { deleteMany: historyDelete }, }; const prisma = { @@ -2136,6 +2190,17 @@ describe('AppointmentsService.cancelPending — serialização canônica', () => expect(historyDelete).toHaveBeenCalledWith({ where: { processId: appointment.process.id }, }); + expect(processClaim).toHaveBeenCalledWith({ + where: { + id: appointment.process.id, + status: ProcessStatus.SCHEDULING, + updated_at: appointment.process.updated_at, + }, + data: { updated_at: expect.any(Date) }, + }); + expect(processClaim.mock.invocationCallOrder[0]).toBeLessThan( + historyDelete.mock.invocationCallOrder[0], + ); expect(processDelete).toHaveBeenCalledWith({ where: { id: appointment.process.id }, }); diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 920232b..76ffaf6 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -619,6 +619,15 @@ export class AppointmentsService { 'Apenas agendamentos pendentes ou agendados podem ser cancelados', ); } + if ( + dto.status === StatusAgendamento.CANCELLED && + current.process && + current.process.status !== ProcessStatus.SCHEDULING + ) { + throw new BadRequestException( + 'Não é possível cancelar uma reunião cujo processo já avançou', + ); + } }; const appointment = await this.prisma.appointment.findUnique({ @@ -1712,6 +1721,24 @@ export class AppointmentsService { // Se existe process, deletar histórico e process primeiro if (lockedAppointment.process) { + if (lockedAppointment.process.status !== ProcessStatus.SCHEDULING) { + throw new BadRequestException( + 'Não é possível cancelar uma reunião cujo processo já avançou', + ); + } + const processClaim = await tx.process.updateMany({ + where: { + id: lockedAppointment.process.id, + status: ProcessStatus.SCHEDULING, + updated_at: lockedAppointment.process.updated_at, + }, + data: { updated_at: new Date() }, + }); + if (processClaim.count !== 1) { + throw new ConflictException( + 'O processo foi alterado enquanto o agendamento era cancelado', + ); + } await tx.processStatusHistory.deleteMany({ where: { processId: lockedAppointment.process.id }, }); diff --git a/backend/src/features/appointments/dto/get-appointments-query.dto.ts b/backend/src/features/appointments/dto/get-appointments-query.dto.ts index 4080658..a35a777 100644 --- a/backend/src/features/appointments/dto/get-appointments-query.dto.ts +++ b/backend/src/features/appointments/dto/get-appointments-query.dto.ts @@ -6,6 +6,7 @@ import { IsDateString, IsUUID, IsIn, + Max, } from 'class-validator'; import { Type } from 'class-transformer'; import { ProductType } from '@prisma/client'; @@ -45,7 +46,7 @@ export class GetAppointmentsQueryDto { @Type(() => Number) @IsInt({ message: 'limit deve ser um número inteiro' }) @Min(1, { message: 'limit deve ser no mínimo 1' }) - @Type(() => Number) + @Max(100, { message: 'limit deve ser no máximo 100' }) limit?: number = 20; // ═══════════════════════════════════════════════════════════════════════════ diff --git a/backend/src/features/appointments/dto/update-appointment-status.dto.ts b/backend/src/features/appointments/dto/update-appointment-status.dto.ts index 24bed59..2c7baad 100644 --- a/backend/src/features/appointments/dto/update-appointment-status.dto.ts +++ b/backend/src/features/appointments/dto/update-appointment-status.dto.ts @@ -7,7 +7,7 @@ import { StatusAgendamento } from '@prisma/client'; * Fluxo de status: * 1. SCHEDULED (padrão ao criar) * 2. COMPLETED (quando reunião ocorre) → Move Process para NEGOTIATION (se estava em SCHEDULING) - * 3. CANCELLED (se cancelado) + * 3. CANCELLED (somente enquanto o Process ainda está em SCHEDULING) * * Frontend: * - Botão "Confirmar realização" (especialista) → status = COMPLETED @@ -21,14 +21,14 @@ export class UpdateAppointmentStatusDto { * * Transições permitidas: * - SCHEDULED → COMPLETED: move Process para NEGOTIATION - * - SCHEDULED → CANCELLED: cancela agendamento - * - COMPLETED → CANCELLED: undo (reverter) - * - CANCELLED → SCHEDULED: reativar (raramente usado) + * - PENDING/SCHEDULED → CANCELLED: cancela enquanto o Process está em SCHEDULING + * - COMPLETED ou Process em NEGOTIATION+: cancelamento rejeitado + * - CANCELLED → SCHEDULED: não permitido por esta rota * * Backend validará: * - Transições lógicas (ex: não voltar de COMPLETED para SCHEDULED sem razão) - * - Se status=COMPLETED, Process está em SCHEDULING ou NEGOTIATION - * - Evitar conflito: se Process já está em NEGOTIATION, manter sem retroceder + * - Se status=COMPLETED, o appointment ainda está SCHEDULED + * - Se status=CANCELLED, o Process vinculado ainda está em SCHEDULING */ @IsEnum(StatusAgendamento, { message: 'status deve ser SCHEDULED, COMPLETED ou CANCELLED', diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts index 616b398..d62f3fd 100644 --- a/backend/src/features/processes/processes.service.spec.ts +++ b/backend/src/features/processes/processes.service.spec.ts @@ -1994,6 +1994,7 @@ describe('ProcessesService — autorização centralizada de processos', () => { function updateService(process = protectedProcess()) { const processUpdateMany = jest.fn().mockResolvedValue({ count: 1 }); const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), process: { findUniqueOrThrow: jest.fn().mockResolvedValue(process), updateMany: processUpdateMany, @@ -2282,6 +2283,7 @@ describe('ProcessesService.cancelAppointment — serialização canônica', () = client_id: clientId, specialist_id: specialistId, status: ProcessStatus.SCHEDULING, + updated_at: new Date('2026-01-01T00:00:00.000Z'), product_type: ProductType.CAR, appointment_id: 'appointment-1', appointment: { @@ -2308,12 +2310,14 @@ describe('ProcessesService.cancelAppointment — serialização canônica', () = aircraft: null, }; const historyDelete = jest.fn().mockResolvedValue({ count: 1 }); + const processClaim = jest.fn().mockResolvedValue({ count: 1 }); const processDelete = jest.fn().mockResolvedValue(process); const appointmentDelete = jest.fn().mockResolvedValue(process.appointment); const tx = { $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), process: { findUnique: jest.fn().mockResolvedValue(process), + updateMany: processClaim, delete: processDelete, }, appointment: { delete: appointmentDelete }, @@ -2342,6 +2346,17 @@ describe('ProcessesService.cancelAppointment — serialização canônica', () = expect(historyDelete).toHaveBeenCalledWith({ where: { processId: process.id }, }); + expect(processClaim).toHaveBeenCalledWith({ + where: { + id: process.id, + status: ProcessStatus.SCHEDULING, + updated_at: process.updated_at, + }, + data: { updated_at: expect.any(Date) }, + }); + expect(processClaim.mock.invocationCallOrder[0]).toBeLessThan( + historyDelete.mock.invocationCallOrder[0], + ); expect(processDelete).toHaveBeenCalledWith({ where: { id: process.id }, }); diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts index 36b8f52..5cb7ae4 100644 --- a/backend/src/features/processes/processes.service.ts +++ b/backend/src/features/processes/processes.service.ts @@ -1212,6 +1212,41 @@ export class ProcessesService { 'update-status', ); + await acquireSpecialistScheduleLock( + tx, + existingProcess.specialist_id, + ); + existingProcess = await tx.process.findUniqueOrThrow({ + where: { id: processId }, + include: { + client: { + select: { + email: true, + name: true, + surname: true, + consultant_id: true, + company_id: true, + consultant: { select: { company_id: true } }, + }, + }, + specialist: { + select: { email: true, name: true, surname: true }, + }, + car: true, + boat: true, + aircraft: true, + }, + }); + this.assertProcessAccess( + existingProcess, + { + id: callerId ?? '', + role: callerRole as UserRole, + companyId: callerCompanyId, + }, + 'update-status', + ); + //Verificar se ele já está com o status atualizado if (existingProcess.status === updateProcessDto.status) { throw new BadRequestException(); @@ -2380,6 +2415,20 @@ export class ProcessesService { ); } + const processClaim = await tx.process.updateMany({ + where: { + id: processId, + status: ProcessStatus.SCHEDULING, + updated_at: lockedProcess.updated_at, + }, + data: { updated_at: new Date() }, + }); + if (processClaim.count !== 1) { + throw new ConflictException( + 'O processo foi alterado enquanto o agendamento era cancelado', + ); + } + // Deletar histórico do processo await tx.processStatusHistory.deleteMany({ where: { processId }, From 65ae6b5681bc121fffde47b9d587af2b7946e5b1 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 11:56:56 -0300 Subject: [PATCH 26/60] fix(appointments): canonicalize Calendly widget URIs --- .../appointments/appointments.service.spec.ts | 122 +++++++++++++++++- .../appointments/appointments.service.ts | 41 ++++-- .../calendly-integration.service.spec.ts | 104 ++++++++++++++- .../calendly-integration.service.ts | 74 ++++++++--- .../dto/calendly-scheduled.dto.spec.ts | 29 +++++ .../dto/calendly-scheduled.dto.ts | 65 +++++++--- 6 files changed, 375 insertions(+), 60 deletions(-) diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts index fa70ac0..5dd9ab8 100644 --- a/backend/src/features/appointments/appointments.service.spec.ts +++ b/backend/src/features/appointments/appointments.service.spec.ts @@ -1740,6 +1740,25 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = expect(prisma.$transaction).not.toHaveBeenCalled(); }); + it('rejeita evento e convidado que não pertencem ao mesmo agendamento', async () => { + const prisma = { + appointment: { findUnique: jest.fn() }, + $transaction: jest.fn(), + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + await expect( + service.registerCalendlyScheduled('appointment-1', 'client-1', { + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-2/invitees/invitee-1', + scheduled_start_time: '2099-01-01T10:00:00.000Z', + }), + ).rejects.toThrow('URIs do Calendly pertencem a eventos diferentes'); + expect(prisma.appointment.findUnique).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + it.each([ AppointmentSchedulingMethod.EMAIL, AppointmentSchedulingMethod.PLATFORM, @@ -1760,11 +1779,92 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = await expect( service.registerCalendlyScheduled(appointment.id, appointment.client_id, { - event_uri: 'https://calendly.test/events/1', - invitee_uri: 'https://calendly.test/invitees/1', + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', scheduled_start_time: '2099-01-01T10:00:00.000Z', } as any), ).rejects.toThrow(BadRequestException); + expect(prisma.appointment.findUnique).toHaveBeenCalledTimes(1); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + + it('considera idempotente a mesma URI oficial após canonicalização', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.SCHEDULED, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: + 'https://calendly.com/api/v2/scheduled_events/event-1', + calendly_sync_status: 'SYNCED', + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(), + } as any; + const calendlyIntegrationService = { + resolveScheduledStartTime: jest.fn(), + } as any; + const service = new AppointmentsService( + prisma, + {} as any, + calendlyIntegrationService, + ); + + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }), + ).resolves.toEqual({ + appointment_id: appointment.id, + calendly_sync_status: appointment.calendly_sync_status, + appointment_datetime: appointment.appointment_datetime, + }); + expect( + calendlyIntegrationService.resolveScheduledStartTime, + ).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + + it('não ignora falha de integridade detectada na resposta do Calendly', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: null, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(), + } as any; + const integrityError = new BadRequestException( + 'URIs do Calendly pertencem a eventos diferentes', + ); + const calendlyIntegrationService = { + resolveScheduledStartTime: jest.fn().mockRejectedValue(integrityError), + } as any; + const service = new AppointmentsService( + prisma, + {} as any, + calendlyIntegrationService, + ); + + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }), + ).rejects.toBe(integrityError); expect(prisma.$transaction).not.toHaveBeenCalled(); }); @@ -1794,7 +1894,7 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = expect(prisma.$transaction).not.toHaveBeenCalled(); }); - it('serializes and rechecks the resolved time in the write transaction', async () => { + it('normalizes, serializes and rechecks the resolved time in the write transaction', async () => { const appointment = { id: 'appointment-1', client_id: 'client-1', @@ -1829,9 +1929,10 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = appointment.id, appointment.client_id, { - event_uri: 'https://api.calendly.com/scheduled_events/event-1', + event_uri: + 'https://calendly.com/api/v2/scheduled_events/event-1', invitee_uri: - 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + 'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', scheduled_start_time: '2099-01-01T10:00:00.000Z', } as any, ); @@ -1842,7 +1943,16 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = ); expect(tx.appointment.findFirst).toHaveBeenCalled(); expect(prisma.appointment.update).not.toHaveBeenCalled(); - expect(tx.appointment.update).toHaveBeenCalledTimes(1); + expect(tx.appointment.update).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }), + }), + ); }); it('rejects a reschedule that overlaps an already SCHEDULED appointment', async () => { diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 76ffaf6..008f278 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -41,7 +41,7 @@ import { isCalendlySchedulingAvailable } from 'src/shared/utils/calendly-schedul import { parseDate, isFutureDate } from 'src/shared/utils/date.utils'; import { NotificationService } from 'src/features/notifications/notification.service'; import { CalendlyIntegrationService } from './calendly-integration.service'; -import { isCalendlyResourceUri } from './dto/calendly-scheduled.dto'; +import { parseCalendlyResourceUri } from './dto/calendly-scheduled.dto'; import { buildNegotiationSnapshotUpdate } from 'src/features/processes/negotiation-snapshot'; import { lockNegotiationProductMoney } from 'src/features/products/product-monetary-lock'; import { validateSpecialistProductAssociation } from 'src/features/products/product-association-validator'; @@ -1876,12 +1876,21 @@ export class AppointmentsService { calendly_sync_status: CalendlySyncStatus; appointment_datetime: Date | null; }> { - if ( - !isCalendlyResourceUri(dto.event_uri, 'event') || - !isCalendlyResourceUri(dto.invitee_uri, 'invitee') - ) { + const eventReference = parseCalendlyResourceUri(dto.event_uri, 'event'); + const inviteeReference = parseCalendlyResourceUri( + dto.invitee_uri, + 'invitee', + ); + if (!eventReference || !inviteeReference) { throw new BadRequestException('URIs do Calendly inválidas'); } + if (eventReference.eventId !== inviteeReference.eventId) { + throw new BadRequestException( + 'URIs do Calendly pertencem a eventos diferentes', + ); + } + const eventUri = eventReference.canonicalUri; + const inviteeUri = inviteeReference.canonicalUri; const appointment = await this.prisma.appointment.findUnique({ where: { id: appointmentId }, @@ -1939,7 +1948,8 @@ export class AppointmentsService { if ( appointment.calendly_event_uri && - appointment.calendly_event_uri === dto.event_uri + parseCalendlyResourceUri(appointment.calendly_event_uri, 'event') + ?.canonicalUri === eventUri ) { return { appointment_id: appointment.id, @@ -1967,10 +1977,13 @@ export class AppointmentsService { scheduledStartTime = await this.calendlyIntegrationService.resolveScheduledStartTime( appointment.specialist_id, - dto.event_uri, - dto.invitee_uri, + eventUri, + inviteeUri, ); } catch (error: any) { + if (error instanceof BadRequestException) { + throw error; + } this.logger.warn( `[registerCalendlyScheduled] Falha ao buscar horário no Calendly API: ${error?.message}`, ); @@ -2023,7 +2036,13 @@ export class AppointmentsService { if (lockedAppointment.specialist_rescheduled_at) { throw this.buildRescheduleAlreadyUsedError(appointmentId); } - if (lockedAppointment.calendly_event_uri === dto.event_uri) { + if ( + lockedAppointment.calendly_event_uri && + parseCalendlyResourceUri( + lockedAppointment.calendly_event_uri, + 'event', + )?.canonicalUri === eventUri + ) { return lockedAppointment; } @@ -2046,8 +2065,8 @@ export class AppointmentsService { return tx.appointment.update({ where: { id: lockedAppointment.id }, data: { - calendly_event_uri: dto.event_uri, - calendly_invitee_uri: dto.invitee_uri, + calendly_event_uri: eventUri, + calendly_invitee_uri: inviteeUri, calendly_scheduled_at: dto.client_observed_at ? new Date(dto.client_observed_at) : new Date(), diff --git a/backend/src/features/appointments/calendly-integration.service.spec.ts b/backend/src/features/appointments/calendly-integration.service.spec.ts index bcceed1..a035817 100644 --- a/backend/src/features/appointments/calendly-integration.service.spec.ts +++ b/backend/src/features/appointments/calendly-integration.service.spec.ts @@ -203,6 +203,70 @@ describe('CalendlyIntegrationService connection lifecycle', () => { ); }); + it.each([ + 'https://calendly.com/api/v2/scheduled_events/event-1', + 'https://api.calendly.com/api/v2/scheduled_events/event-1', + ])('normaliza URI oficial antes da requisição autenticada: %s', async (uri) => { + const { service } = makeRefreshService(); + jest.mocked(axios.get).mockResolvedValueOnce({ + data: { resource: { start_time: '2099-01-01T10:00:00.000Z' } }, + }); + + await expect( + service.resolveScheduledStartTime('specialist-1', uri), + ).resolves.toEqual(new Date('2099-01-01T10:00:00.000Z')); + expect(axios.get).toHaveBeenCalledWith( + 'https://api.calendly.com/scheduled_events/event-1', + expect.objectContaining({ maxRedirects: 0 }), + ); + }); + + it('rejeita evento divergente retornado pelo convidado mesmo quando há horário', async () => { + const { service } = makeRefreshService(); + jest.mocked(axios.get).mockResolvedValueOnce({ + data: { + resource: { + event: 'https://api.calendly.com/scheduled_events/event-2', + start_time: '2099-01-01T10:00:00.000Z', + }, + }, + }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://calendly.com/api/v2/scheduled_events/event-1', + 'https://calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', + ), + ).rejects.toThrow('URIs do Calendly pertencem a eventos diferentes'); + expect(axios.get).toHaveBeenCalledTimes(1); + }); + + it('aceita evento equivalente retornado pelo convidado e mantém fetch canônico', async () => { + const { service } = makeRefreshService(); + jest.mocked(axios.get).mockResolvedValueOnce({ + data: { + resource: { + event: + 'https://api.calendly.com/api/v2/scheduled_events/event-1', + start_time: '2099-01-01T10:00:00.000Z', + }, + }, + }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://calendly.com/api/v2/scheduled_events/event-1', + 'https://calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', + ), + ).resolves.toEqual(new Date('2099-01-01T10:00:00.000Z')); + expect(axios.get).toHaveBeenCalledWith( + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + expect.objectContaining({ maxRedirects: 0 }), + ); + }); + it('rejeita URI de evento não confiável retornada pelo recurso de convidado', async () => { const { service } = makeRefreshService(); jest.mocked(axios.get).mockResolvedValueOnce({ @@ -381,7 +445,8 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { const appointment = { id: 'appointment-1', specialist_id: 'specialist-1', - calendly_event_uri: 'https://calendly.test/events/1', + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/event-1', scheduling_method: method, specialist_rescheduled_at: null, }; @@ -418,7 +483,8 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { const appointment = { id: 'appointment-1', specialist_id: 'specialist-1', - calendly_event_uri: 'https://calendly.test/events/1', + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/event-1', scheduling_method: AppointmentSchedulingMethod.CALENDLY, specialist_rescheduled_at: new Date('2026-01-01T00:00:00.000Z'), }; @@ -452,7 +518,8 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { id: 'appointment-1', client_id: 'client-1', specialist_id: 'specialist-1', - calendly_event_uri: 'https://calendly.test/events/1', + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/event-1', calendly_invitee_uri: null, calendly_sync_status: 'PENDING', appointment_datetime: null, @@ -483,8 +550,10 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { { event: 'invitee.created', payload: { - event: appointment.calendly_event_uri, - invitee: 'https://calendly.test/invitees/1', + event: + 'https://calendly.com/api/v2/scheduled_events/event-1', + invitee: + 'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', scheduled_event: { start_time: '2099-01-01T10:00:00.000Z', }, @@ -495,6 +564,20 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { ); expect(prisma.$transaction).toHaveBeenCalledTimes(1); + expect(prisma.appointment.findFirst).toHaveBeenCalledWith({ + where: { + OR: [ + { + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/event-1', + }, + { + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }, + ], + }, + }); expect(tx.$queryRaw).toHaveBeenCalledTimes(1); expect(tx.appointment.findUnique).toHaveBeenCalledWith({ where: { id: appointment.id }, @@ -507,7 +590,16 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { }), }), ); - expect(tx.appointment.update).toHaveBeenCalledTimes(1); + expect(tx.appointment.update).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }), + }), + ); expect(prisma.appointment.update).not.toHaveBeenCalled(); }); }); diff --git a/backend/src/features/appointments/calendly-integration.service.ts b/backend/src/features/appointments/calendly-integration.service.ts index d58afb4..f307711 100644 --- a/backend/src/features/appointments/calendly-integration.service.ts +++ b/backend/src/features/appointments/calendly-integration.service.ts @@ -29,7 +29,8 @@ import { } from './appointment-schedule-lock'; import { CalendlyResourceKind, - isCalendlyResourceUri, + CalendlyResourceReference, + parseCalendlyResourceUri, } from './dto/calendly-scheduled.dto'; interface CalendlyTokenResponse { @@ -291,8 +292,13 @@ export class CalendlyIntegrationService { return null; } - if (eventUri) this.assertCalendlyResourceUri(eventUri, 'event'); - if (inviteeUri) this.assertCalendlyResourceUri(inviteeUri, 'invitee'); + const eventReference = eventUri + ? this.parseCalendlyResourceUri(eventUri, 'event') + : null; + const inviteeReference = inviteeUri + ? this.parseCalendlyResourceUri(inviteeUri, 'invitee') + : null; + this.assertSameCalendlyEvent(eventReference, inviteeReference); const connection = await this.prisma.calendlyConnection.findUnique({ where: { user_id: specialistId }, @@ -302,15 +308,25 @@ export class CalendlyIntegrationService { return null; } - const inviteeData = inviteeUri + const inviteeData = inviteeReference ? await this.getCalendlyResourceWithRefresh( connection.user_id, - inviteeUri, + inviteeReference.canonicalUri, 'invitee', ) : null; const inviteeResource = inviteeData?.resource || inviteeData; + const inviteeEventUri = + inviteeResource?.event || inviteeResource?.scheduled_event?.uri; + const inviteeEventReference = inviteeEventUri + ? this.parseCalendlyResourceUri(inviteeEventUri, 'event') + : null; + this.assertSameCalendlyEvent( + eventReference, + inviteeReference, + inviteeEventReference, + ); const inviteeStartTime = inviteeResource?.start_time || inviteeResource?.event_start_time || @@ -328,9 +344,9 @@ export class CalendlyIntegrationService { } const resolvedEventUri = - eventUri || - inviteeResource?.event || - inviteeResource?.scheduled_event?.uri; + eventReference?.canonicalUri || + inviteeEventReference?.canonicalUri || + inviteeReference?.canonicalEventUri; if (!resolvedEventUri) { return null; } @@ -379,19 +395,29 @@ export class CalendlyIntegrationService { }; } - const eventUri = payload.event || payload.scheduled_event?.uri; - const inviteeUri = + const rawEventUri = payload.event || payload.scheduled_event?.uri; + const rawInviteeUri = typeof payload.invitee === 'string' ? payload.invitee : payload.invitee?.uri; - if (!eventUri && !inviteeUri) { + if (!rawEventUri && !rawInviteeUri) { return { processed: false, message: 'Webhook sem event/invitee uri', }; } + const eventReference = rawEventUri + ? this.parseCalendlyResourceUri(rawEventUri, 'event') + : null; + const inviteeReference = rawInviteeUri + ? this.parseCalendlyResourceUri(rawInviteeUri, 'invitee') + : null; + this.assertSameCalendlyEvent(eventReference, inviteeReference); + const eventUri = eventReference?.canonicalUri; + const inviteeUri = inviteeReference?.canonicalUri; + const appointment = await this.prisma.appointment.findFirst({ where: { OR: [ @@ -627,7 +653,7 @@ export class CalendlyIntegrationService { uri: string, kind: CalendlyResourceKind, ): Promise { - const trustedUri = this.assertCalendlyResourceUri(uri, kind); + const trustedUri = this.parseCalendlyResourceUri(uri, kind).canonicalUri; const { data } = await axios.get(trustedUri, { headers: { Authorization: `Bearer ${accessToken}`, @@ -843,15 +869,31 @@ export class CalendlyIntegrationService { ); } - private assertCalendlyResourceUri( + private parseCalendlyResourceUri( uri: string, kind: CalendlyResourceKind, - ): string { - if (!isCalendlyResourceUri(uri, kind)) { + ): CalendlyResourceReference { + const reference = parseCalendlyResourceUri(uri, kind); + if (!reference) { const field = kind === 'event' ? 'event_uri' : 'invitee_uri'; throw new BadRequestException(`${field} do Calendly inválida`); } - return uri; + return reference; + } + + private assertSameCalendlyEvent( + ...references: Array + ): void { + const eventIds = references + .filter((reference): reference is CalendlyResourceReference => + Boolean(reference), + ) + .map((reference) => reference.eventId); + if (new Set(eventIds).size > 1) { + throw new BadRequestException( + 'URIs do Calendly pertencem a eventos diferentes', + ); + } } private getRequiredEnv(name: string): string { diff --git a/backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts b/backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts index b8748e5..9568e39 100644 --- a/backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts +++ b/backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts @@ -34,6 +34,23 @@ describe('CalendlyScheduledDto — Calendly resource URIs', () => { ).resolves.toEqual([]); }); + it.each([ + { + event_uri: + 'https://calendly.com/api/v2/scheduled_events/event-123', + invitee_uri: + 'https://calendly.com/api/v2/scheduled_events/event-123/invitees/invitee-456', + }, + { + event_uri: + 'https://api.calendly.com/api/v2/scheduled_events/event-123', + invitee_uri: + 'https://api.calendly.com/api/v2/scheduled_events/event-123/invitees/invitee-456', + }, + ])('aceita a família oficial usada pelo react-calendly: %o', async (uris) => { + await expect(invalidProperties(uris)).resolves.toEqual([]); + }); + it.each([ 'https://evil/scheduled_events/event-123', 'https://evil.test/scheduled_events/event-123', @@ -41,8 +58,14 @@ describe('CalendlyScheduledDto — Calendly resource URIs', () => { 'https://api.calendly.com.evil.test/scheduled_events/event-123', 'http://api.calendly.com/scheduled_events/event-123', 'https://user:password@api.calendly.com/scheduled_events/event-123', + 'https://%61pi.calendly.com@evil.test/scheduled_events/event-123', + 'https://api.calendly.com\\@evil.test/scheduled_events/event-123', 'https://api.calendly.com:444/scheduled_events/event-123', 'https://127.0.0.1/scheduled_events/event-123', + 'https://api.calendly.com/scheduled_events/event%2f123', + 'https://api.calendly.com/scheduled_events/event%3fadmin', + 'https://api.calendly.com/scheduled_events/event%23admin', + 'https://api.calendly.com/scheduled_events/ignored/../event-123', 'https://api.calendly.com/scheduled_events/event-123/invitees/invitee-456', ])('rejeita event_uri fora do recurso esperado: %s', async (event_uri) => { await expect(invalidProperties({ event_uri })).resolves.toContain( @@ -57,8 +80,14 @@ describe('CalendlyScheduledDto — Calendly resource URIs', () => { 'https://api.calendly.com.evil.test/scheduled_events/event-123/invitees/invitee-456', 'http://api.calendly.com/scheduled_events/event-123/invitees/invitee-456', 'https://user@api.calendly.com/scheduled_events/event-123/invitees/invitee-456', + 'https://%61pi.calendly.com@evil.test/scheduled_events/event-123/invitees/invitee-456', + 'https://api.calendly.com\\@evil.test/scheduled_events/event-123/invitees/invitee-456', 'https://api.calendly.com:444/scheduled_events/event-123/invitees/invitee-456', 'https://127.0.0.1/scheduled_events/event-123/invitees/invitee-456', + 'https://api.calendly.com/scheduled_events/event%2f123/invitees/invitee-456', + 'https://api.calendly.com/scheduled_events/event-123/invitees/invitee%3f456', + 'https://api.calendly.com/scheduled_events/event-123/invitees/invitee%23456', + 'https://api.calendly.com/scheduled_events/event-123/invitees/ignored/../invitee-456', 'https://api.calendly.com/scheduled_events/event-123', ])( 'rejeita invitee_uri fora do recurso esperado: %s', diff --git a/backend/src/features/appointments/dto/calendly-scheduled.dto.ts b/backend/src/features/appointments/dto/calendly-scheduled.dto.ts index c310708..56f5cb2 100644 --- a/backend/src/features/appointments/dto/calendly-scheduled.dto.ts +++ b/backend/src/features/appointments/dto/calendly-scheduled.dto.ts @@ -11,32 +11,55 @@ import { export type CalendlyResourceKind = 'event' | 'invitee'; -const CALENDLY_RESOURCE_PATHS: Record = { - event: /^\/scheduled_events\/[A-Za-z0-9_-]+$/, - invitee: /^\/scheduled_events\/[A-Za-z0-9_-]+\/invitees\/[A-Za-z0-9_-]+$/, -}; +export interface CalendlyResourceReference { + canonicalUri: string; + canonicalEventUri: string; + eventId: string; + inviteeId?: string; +} -export function isCalendlyResourceUri( +const CALENDLY_RESOURCE_PATTERNS = [ + /^https:\/\/api\.calendly\.com(?::443)?\/(?:api\/v2\/)?scheduled_events\/([A-Za-z0-9_-]+)(?:\/invitees\/([A-Za-z0-9_-]+))?$/i, + /^https:\/\/calendly\.com(?::443)?\/api\/v2\/scheduled_events\/([A-Za-z0-9_-]+)(?:\/invitees\/([A-Za-z0-9_-]+))?$/i, +]; + +export function parseCalendlyResourceUri( value: unknown, kind: CalendlyResourceKind, -): value is string { - if (typeof value !== 'string') return false; +): CalendlyResourceReference | null { + if (typeof value !== 'string') return null; - try { - const uri = new URL(value); - return ( - uri.protocol === 'https:' && - uri.hostname === 'api.calendly.com' && - uri.port === '' && - uri.username === '' && - uri.password === '' && - uri.search === '' && - uri.hash === '' && - CALENDLY_RESOURCE_PATHS[kind].test(uri.pathname) - ); - } catch { - return false; + const match = CALENDLY_RESOURCE_PATTERNS.map((pattern) => + pattern.exec(value), + ).find((candidate) => candidate?.[0] === value); + if (!match) return null; + + const [, eventId, inviteeId] = match; + if ( + (kind === 'event' && inviteeId !== undefined) || + (kind === 'invitee' && inviteeId === undefined) + ) { + return null; } + + const canonicalEventUri = + `https://api.calendly.com/scheduled_events/${eventId}`; + return { + eventId, + inviteeId, + canonicalEventUri, + canonicalUri: + kind === 'invitee' + ? `${canonicalEventUri}/invitees/${inviteeId}` + : canonicalEventUri, + }; +} + +export function isCalendlyResourceUri( + value: unknown, + kind: CalendlyResourceKind, +): value is string { + return parseCalendlyResourceUri(value, kind) !== null; } function IsCalendlyResourceUri( From 3a338f62123558e79435c62b3a25435ca71abdfb Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 12:00:32 -0300 Subject: [PATCH 27/60] fix(processes): preserve completed appointments on cancel --- .../processes/processes.service.spec.ts | 52 +++++++++++++++++++ .../features/processes/processes.service.ts | 8 +++ 2 files changed, 60 insertions(+) diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts index d62f3fd..558b13f 100644 --- a/backend/src/features/processes/processes.service.spec.ts +++ b/backend/src/features/processes/processes.service.spec.ts @@ -2364,4 +2364,56 @@ describe('ProcessesService.cancelAppointment — serialização canônica', () = where: { id: process.appointment.id }, }); }); + + it('não apaga processo SCHEDULING quando o appointment já está COMPLETED', async () => { + const process = { + id: 'process-1', + client_id: clientId, + specialist_id: specialistId, + status: ProcessStatus.SCHEDULING, + updated_at: new Date('2026-01-01T00:00:00.000Z'), + appointment_id: 'appointment-1', + appointment: { + id: 'appointment-1', + client_id: clientId, + specialist_id: specialistId, + status: StatusAgendamento.COMPLETED, + }, + client: { id: clientId }, + specialist: { id: specialistId }, + car: null, + boat: null, + aircraft: null, + }; + const processClaim = jest.fn(); + const processDelete = jest.fn(); + const appointmentDelete = jest.fn(); + const historyDelete = jest.fn(); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + process: { + findUnique: jest.fn().mockResolvedValue(process), + updateMany: processClaim, + delete: processDelete, + }, + appointment: { delete: appointmentDelete }, + processStatusHistory: { deleteMany: historyDelete }, + }; + const prisma = { + process: { findUnique: jest.fn().mockResolvedValue(process) }, + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const service = new ProcessesService(prisma, {} as any); + + await expect( + service.cancelAppointment(process.id, clientId), + ).rejects.toThrow( + 'Apenas agendamentos pendentes ou agendados podem ser cancelados', + ); + + expect(processClaim).not.toHaveBeenCalled(); + expect(historyDelete).not.toHaveBeenCalled(); + expect(processDelete).not.toHaveBeenCalled(); + expect(appointmentDelete).not.toHaveBeenCalled(); + }); }); diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts index 5cb7ae4..750d332 100644 --- a/backend/src/features/processes/processes.service.ts +++ b/backend/src/features/processes/processes.service.ts @@ -2414,6 +2414,14 @@ export class ProcessesService { 'Agendamento não corresponde aos participantes do processo', ); } + if ( + lockedProcess.appointment.status !== StatusAgendamento.PENDING && + lockedProcess.appointment.status !== StatusAgendamento.SCHEDULED + ) { + throw new BadRequestException( + 'Apenas agendamentos pendentes ou agendados podem ser cancelados', + ); + } const processClaim = await tx.process.updateMany({ where: { From 963a4a908e06b14d73cb3144c1c338240e3aa3f9 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 12:00:36 -0300 Subject: [PATCH 28/60] fix(appointments): repair legacy Calendly URIs --- .../appointments/appointments.service.spec.ts | 19 +++- .../appointments/appointments.service.ts | 42 +++++++- .../calendly-integration.service.spec.ts | 99 +++++++++++++++++-- .../calendly-integration.service.ts | 30 +++++- .../dto/calendly-scheduled.dto.ts | 17 ++++ 5 files changed, 192 insertions(+), 15 deletions(-) diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts index 5dd9ab8..1b066fd 100644 --- a/backend/src/features/appointments/appointments.service.spec.ts +++ b/backend/src/features/appointments/appointments.service.spec.ts @@ -1799,11 +1799,15 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = specialist_rescheduled_at: null, calendly_event_uri: 'https://calendly.com/api/v2/scheduled_events/event-1', + calendly_invitee_uri: null, calendly_sync_status: 'SYNCED', appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), }; const prisma = { - appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, $transaction: jest.fn(), } as any; const calendlyIntegrationService = { @@ -1829,6 +1833,19 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = expect( calendlyIntegrationService.resolveScheduledStartTime, ).not.toHaveBeenCalled(); + expect(prisma.appointment.updateMany).toHaveBeenCalledWith({ + where: { + id: appointment.id, + calendly_event_uri: appointment.calendly_event_uri, + calendly_invitee_uri: null, + }, + data: { + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }, + }); expect(prisma.$transaction).not.toHaveBeenCalled(); }); diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 008f278..bb8aebe 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -1951,11 +1951,31 @@ export class AppointmentsService { parseCalendlyResourceUri(appointment.calendly_event_uri, 'event') ?.canonicalUri === eventUri ) { - return { - appointment_id: appointment.id, - calendly_sync_status: appointment.calendly_sync_status, - appointment_datetime: appointment.appointment_datetime, - }; + let canonicalized = true; + if ( + appointment.calendly_event_uri !== eventUri || + appointment.calendly_invitee_uri !== inviteeUri + ) { + const repair = await this.prisma.appointment.updateMany({ + where: { + id: appointment.id, + calendly_event_uri: appointment.calendly_event_uri, + calendly_invitee_uri: appointment.calendly_invitee_uri, + }, + data: { + calendly_event_uri: eventUri, + calendly_invitee_uri: inviteeUri, + }, + }); + canonicalized = repair.count === 1; + } + if (canonicalized) { + return { + appointment_id: appointment.id, + calendly_sync_status: appointment.calendly_sync_status, + appointment_datetime: appointment.appointment_datetime, + }; + } } let scheduledStartTime = dto.scheduled_start_time @@ -2043,6 +2063,18 @@ export class AppointmentsService { 'event', )?.canonicalUri === eventUri ) { + if ( + lockedAppointment.calendly_event_uri !== eventUri || + lockedAppointment.calendly_invitee_uri !== inviteeUri + ) { + return tx.appointment.update({ + where: { id: lockedAppointment.id }, + data: { + calendly_event_uri: eventUri, + calendly_invitee_uri: inviteeUri, + }, + }); + } return lockedAppointment; } diff --git a/backend/src/features/appointments/calendly-integration.service.spec.ts b/backend/src/features/appointments/calendly-integration.service.spec.ts index a035817..4d7fb41 100644 --- a/backend/src/features/appointments/calendly-integration.service.spec.ts +++ b/backend/src/features/appointments/calendly-integration.service.spec.ts @@ -519,8 +519,9 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { client_id: 'client-1', specialist_id: 'specialist-1', calendly_event_uri: - 'https://api.calendly.com/scheduled_events/event-1', - calendly_invitee_uri: null, + 'https://calendly.com/api/v2/scheduled_events/event-1', + calendly_invitee_uri: + 'https://calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', calendly_sync_status: 'PENDING', appointment_datetime: null, }; @@ -568,12 +569,23 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { where: { OR: [ { - calendly_event_uri: - 'https://api.calendly.com/scheduled_events/event-1', + calendly_event_uri: { + in: expect.arrayContaining([ + 'https://api.calendly.com/scheduled_events/event-1', + 'https://api.calendly.com/api/v2/scheduled_events/event-1', + 'https://calendly.com/api/v2/scheduled_events/event-1', + 'https://api.calendly.com:443/scheduled_events/event-1', + ]), + }, }, { - calendly_invitee_uri: - 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + calendly_invitee_uri: { + in: expect.arrayContaining([ + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + 'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', + 'https://calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', + ]), + }, }, ], }, @@ -602,4 +614,79 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { ); expect(prisma.appointment.update).not.toHaveBeenCalled(); }); + + it('encontra e canonicaliza registro legado ao cancelar pelo webhook', async () => { + const appointment = { + id: 'appointment-1', + specialist_id: 'specialist-1', + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: + 'https://calendly.com/api/v2/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', + }; + const prisma = { + appointment: { + findFirst: jest.fn().mockResolvedValue(appointment), + update: jest.fn().mockResolvedValue(appointment), + }, + }; + const service = new CalendlyIntegrationService(prisma as any); + jest + .spyOn(service as any, 'validateWebhookSignature') + .mockReturnValue(undefined); + + await expect( + service.processWebhook( + { + event: 'invitee.canceled', + payload: { + event: + 'https://api.calendly.com/scheduled_events/event-1', + invitee: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }, + }, + undefined, + undefined, + ), + ).resolves.toEqual({ + processed: true, + message: 'Webhook de cancelamento processado', + }); + expect(prisma.appointment.findFirst).toHaveBeenCalledWith({ + where: { + OR: [ + { + calendly_event_uri: { + in: expect.arrayContaining([ + appointment.calendly_event_uri, + 'https://api.calendly.com/scheduled_events/event-1', + ]), + }, + }, + { + calendly_invitee_uri: { + in: expect.arrayContaining([ + appointment.calendly_invitee_uri, + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + ]), + }, + }, + ], + }, + }); + expect(prisma.appointment.update).toHaveBeenCalledWith({ + where: { id: appointment.id }, + data: { + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + calendly_last_sync_at: expect.any(Date), + calendly_sync_status: 'FAILED', + }, + }); + }); }); diff --git a/backend/src/features/appointments/calendly-integration.service.ts b/backend/src/features/appointments/calendly-integration.service.ts index f307711..e450d19 100644 --- a/backend/src/features/appointments/calendly-integration.service.ts +++ b/backend/src/features/appointments/calendly-integration.service.ts @@ -30,6 +30,7 @@ import { import { CalendlyResourceKind, CalendlyResourceReference, + getCalendlyResourceUriVariants, parseCalendlyResourceUri, } from './dto/calendly-scheduled.dto'; @@ -415,14 +416,34 @@ export class CalendlyIntegrationService { ? this.parseCalendlyResourceUri(rawInviteeUri, 'invitee') : null; this.assertSameCalendlyEvent(eventReference, inviteeReference); - const eventUri = eventReference?.canonicalUri; + const lookupEventReference = + eventReference || + (inviteeReference + ? this.parseCalendlyResourceUri( + inviteeReference.canonicalEventUri, + 'event', + ) + : null); + const eventUri = lookupEventReference?.canonicalUri; const inviteeUri = inviteeReference?.canonicalUri; const appointment = await this.prisma.appointment.findFirst({ where: { OR: [ - eventUri ? { calendly_event_uri: eventUri } : undefined, - inviteeUri ? { calendly_invitee_uri: inviteeUri } : undefined, + lookupEventReference + ? { + calendly_event_uri: { + in: getCalendlyResourceUriVariants(lookupEventReference), + }, + } + : undefined, + inviteeReference + ? { + calendly_invitee_uri: { + in: getCalendlyResourceUriVariants(inviteeReference), + }, + } + : undefined, ].filter(Boolean) as Prisma.AppointmentWhereInput[], }, }); @@ -520,6 +541,9 @@ export class CalendlyIntegrationService { await this.prisma.appointment.update({ where: { id: appointment.id }, data: { + calendly_event_uri: eventUri || appointment.calendly_event_uri, + calendly_invitee_uri: + inviteeUri || appointment.calendly_invitee_uri, calendly_last_sync_at: new Date(), calendly_sync_status: CalendlySyncStatus.FAILED, }, diff --git a/backend/src/features/appointments/dto/calendly-scheduled.dto.ts b/backend/src/features/appointments/dto/calendly-scheduled.dto.ts index 56f5cb2..8d73a8a 100644 --- a/backend/src/features/appointments/dto/calendly-scheduled.dto.ts +++ b/backend/src/features/appointments/dto/calendly-scheduled.dto.ts @@ -55,6 +55,23 @@ export function parseCalendlyResourceUri( }; } +export function getCalendlyResourceUriVariants( + reference: CalendlyResourceReference, +): string[] { + const resourcePath = reference.inviteeId + ? `scheduled_events/${reference.eventId}/invitees/${reference.inviteeId}` + : `scheduled_events/${reference.eventId}`; + + return [ + `https://api.calendly.com/${resourcePath}`, + `https://api.calendly.com:443/${resourcePath}`, + `https://api.calendly.com/api/v2/${resourcePath}`, + `https://api.calendly.com:443/api/v2/${resourcePath}`, + `https://calendly.com/api/v2/${resourcePath}`, + `https://calendly.com:443/api/v2/${resourcePath}`, + ]; +} + export function isCalendlyResourceUri( value: unknown, kind: CalendlyResourceKind, From 9a38dd0033617b2c87779ea0bc4ef5a0c6d26b4c Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 12:01:10 -0300 Subject: [PATCH 29/60] fix(processes): enforce transition gates and rejection CAS --- ...ses-rejection-concurrency.postgres.spec.ts | 307 ++++++++++++++++++ .../processes/processes.service.spec.ts | 240 +++++++++++--- .../features/processes/processes.service.ts | 136 +++++--- 3 files changed, 598 insertions(+), 85 deletions(-) create mode 100644 backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts diff --git a/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts b/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts new file mode 100644 index 0000000..d44b1b5 --- /dev/null +++ b/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts @@ -0,0 +1,307 @@ +import { BadRequestException, ConflictException } from '@nestjs/common'; +import { + PrismaClient, + ProcessStatus, + ProductCurrency, + ProductType, + UserRole, +} from '@prisma/client'; +import { randomUUID } from 'node:crypto'; +import { ProcessesService } from './processes.service'; + +type Deferred = { promise: Promise; resolve: () => void }; + +function deferred(): Deferred { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +function bindMember(target: any, property: PropertyKey): any { + const value = Reflect.get(target, property); + return typeof value === 'function' ? value.bind(target) : value; +} + +function withApplicationName(url: string, name: string): string { + const separator = url.includes('?') ? '&' : '?'; + return `${url}${separator}application_name=${encodeURIComponent(name)}&connection_limit=1&pool_timeout=3`; +} + +function pauseRejectionClaim( + client: PrismaClient, + attempted: Deferred, + release: Deferred, +) { + const wrapTransaction = (tx: any) => + new Proxy(tx, { + get(target, property) { + if (property === 'process') { + return new Proxy(target.process, { + get(processTarget, processProperty) { + if (processProperty === 'updateMany') { + return async (args: any) => { + if (args.data?.status === ProcessStatus.REJECTED) { + attempted.resolve(); + await release.promise; + } + return processTarget.updateMany(args); + }; + } + return bindMember(processTarget, processProperty); + }, + }); + } + return bindMember(target, property); + }, + }); + + return new Proxy(client, { + get(target, property) { + if (property === '$transaction') { + return (callback: (tx: any) => Promise, options?: any) => + target.$transaction((tx) => callback(wrapTransaction(tx)), options); + } + return bindMember(target, property); + }, + }); +} + +function observeScheduleLockAttempt(client: PrismaClient, attempted: Deferred) { + const wrapTransaction = (tx: any) => + new Proxy(tx, { + get(target, property) { + if (property === '$queryRaw') { + return (...args: any[]) => { + attempted.resolve(); + return target.$queryRaw(...args); + }; + } + return bindMember(target, property); + }, + }); + + return new Proxy(client, { + get(target, property) { + if (property === '$transaction') { + return (callback: (tx: any) => Promise, options?: any) => + target.$transaction((tx) => callback(wrapTransaction(tx)), options); + } + return bindMember(target, property); + }, + }); +} + +const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL; +const describeWithPostgres = databaseUrl ? describe : describe.skip; +const prismaDatabaseUrl = + databaseUrl ?? 'postgresql://unused:unused@127.0.0.1:1/unused'; + +describeWithPostgres('process rejection CAS — PostgreSQL concurrency', () => { + const suffix = randomUUID().replaceAll('-', ''); + const clientId = randomUUID(); + const specialistId = randomUUID(); + const carId = randomUUID(); + const processId = randomUUID(); + const rejectClient = new PrismaClient({ + datasources: { + db: { url: withApplicationName(prismaDatabaseUrl, `reject_a_${suffix}`) }, + }, + }); + const completionClient = new PrismaClient({ + datasources: { + db: { url: withApplicationName(prismaDatabaseUrl, `reject_b_${suffix}`) }, + }, + }); + + beforeAll(async () => { + await completionClient.user.createMany({ + data: [ + { + id: clientId, + name: 'Reject', + surname: 'Client', + email: `reject-client-${suffix}@example.test`, + rg: suffix.slice(0, 11), + role: UserRole.CUSTOMER, + password_hash: 'not-used', + }, + { + id: specialistId, + name: 'Reject', + surname: 'Specialist', + email: `reject-specialist-${suffix}@example.test`, + rg: suffix.slice(11, 22), + role: UserRole.SPECIALIST, + speciality: ProductType.CAR, + password_hash: 'not-used', + }, + ], + }); + await completionClient.car.create({ + data: { + id: carId, + specialist_id: specialistId, + marca: 'Concurrent', + modelo: 'Rejection', + identificador: `rejection-${suffix}`, + valor: 120000, + currency: ProductCurrency.USD, + estado: 'SP', + ano: 2026, + }, + }); + }); + + beforeEach(async () => { + await completionClient.processRejection.deleteMany({ + where: { process_id: processId }, + }); + await completionClient.processStatusHistory.deleteMany({ + where: { processId }, + }); + await completionClient.process.deleteMany({ where: { id: processId } }); + }); + + afterAll(async () => { + await completionClient.processRejection.deleteMany({ + where: { process_id: processId }, + }); + await completionClient.processStatusHistory.deleteMany({ + where: { processId }, + }); + await completionClient.process.deleteMany({ where: { id: processId } }); + await completionClient.car.deleteMany({ where: { id: carId } }); + await completionClient.user.deleteMany({ + where: { id: { in: [clientId, specialistId] } }, + }); + await Promise.all([ + rejectClient.$disconnect(), + completionClient.$disconnect(), + ]); + }); + + it('preserva conclusão concorrente e não grava rejeição parcial', async () => { + const initialUpdatedAt = new Date('2026-01-01T00:00:00.000Z'); + await completionClient.process.create({ + data: { + id: processId, + client_id: clientId, + specialist_id: specialistId, + status: ProcessStatus.DOCUMENTATION, + updated_at: initialUpdatedAt, + }, + }); + + const attempted = deferred(); + const release = deferred(); + const service = new ProcessesService( + pauseRejectionClaim(rejectClient, attempted, release) as any, + { sendProcessStatusChangedEmail: jest.fn() } as any, + ); + + const rejection = service.rejectProcess( + processId, + specialistId, + 'concorrente', + UserRole.SPECIALIST, + ); + await attempted.promise; + + const completion = await completionClient.process.updateMany({ + where: { + id: processId, + status: ProcessStatus.DOCUMENTATION, + updated_at: initialUpdatedAt, + }, + data: { + status: ProcessStatus.COMPLETED, + updated_at: new Date('2026-01-02T00:00:00.000Z'), + }, + }); + expect(completion.count).toBe(1); + + release.resolve(); + await expect(rejection).rejects.toBeInstanceOf(ConflictException); + + await expect( + completionClient.process.findUniqueOrThrow({ where: { id: processId } }), + ).resolves.toMatchObject({ status: ProcessStatus.COMPLETED }); + await expect( + completionClient.processRejection.count({ + where: { process_id: processId }, + }), + ).resolves.toBe(0); + await expect( + completionClient.processStatusHistory.count({ + where: { processId, status: ProcessStatus.REJECTED }, + }), + ).resolves.toBe(0); + }, 15_000); + + it('não ressuscita processo quando update perde a corrida para rejeição', async () => { + await completionClient.process.create({ + data: { + id: processId, + client_id: clientId, + specialist_id: specialistId, + product_type: ProductType.CAR, + car_id: carId, + status: ProcessStatus.NEGOTIATION, + negotiation_currency: ProductCurrency.USD, + negotiation_product_value: 120000, + }, + }); + + const rejectionClaimAttempted = deferred(); + const releaseRejection = deferred(); + const updateLockAttempted = deferred(); + const notifications = { + sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined), + } as any; + const rejectionService = new ProcessesService( + pauseRejectionClaim( + rejectClient, + rejectionClaimAttempted, + releaseRejection, + ) as any, + notifications, + ); + const updateService = new ProcessesService( + observeScheduleLockAttempt(completionClient, updateLockAttempted) as any, + notifications, + ); + + const rejection = rejectionService.rejectProcess( + processId, + specialistId, + 'concorrente', + UserRole.SPECIALIST, + ); + await rejectionClaimAttempted.promise; + + const update = updateService.update( + processId, + { status: ProcessStatus.DOCUMENTATION }, + specialistId, + UserRole.SPECIALIST, + ); + await updateLockAttempted.promise; + + releaseRejection.resolve(); + await expect(rejection).resolves.toMatchObject({ + status: ProcessStatus.REJECTED, + }); + await expect(update).rejects.toBeInstanceOf(BadRequestException); + + await expect( + completionClient.process.findUniqueOrThrow({ where: { id: processId } }), + ).resolves.toMatchObject({ status: ProcessStatus.REJECTED }); + await expect( + completionClient.processStatusHistory.count({ + where: { processId, status: ProcessStatus.DOCUMENTATION }, + }), + ).resolves.toBe(0); + }, 15_000); +}); diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts index 558b13f..b213296 100644 --- a/backend/src/features/processes/processes.service.spec.ts +++ b/backend/src/features/processes/processes.service.spec.ts @@ -671,7 +671,7 @@ describe('ProcessesService — snapshot de entrada na negociação', () => { }; } - it('grava snapshot USD na transição manual para negociação', async () => { + it('bloqueia a transição manual para negociação, reservada ao fluxo canônico', async () => { const processUpdate = jest.fn().mockImplementation(({ data }) => Promise.resolve({ ...baseProcess(), @@ -697,30 +697,21 @@ describe('ProcessesService — snapshot de entrada na negociação', () => { } as any; const service = new ProcessesService(prisma, {} as any); - await service.update( - 'process-1', - { status: ProcessStatus.NEGOTIATION, notes: 'Negociando' }, - 'admin-1', - UserRole.ADMIN, - ); + await expect( + service.update( + 'process-1', + { status: ProcessStatus.NEGOTIATION, notes: 'Negociando' }, + 'admin-1', + UserRole.ADMIN, + ), + ).rejects.toThrow(BadRequestException); - expect(processUpdateMany).toHaveBeenCalledWith( - expect.objectContaining({ - where: { - id: 'process-1', - status: ProcessStatus.SCHEDULING, - updated_at: new Date('2026-01-01T00:00:00.000Z'), - }, - data: expect.objectContaining({ - status: ProcessStatus.NEGOTIATION, - negotiation_currency: ProductCurrency.USD, - negotiation_product_value: new Prisma.Decimal('120000.00'), - }), - }), - ); + expect(processUpdateMany).not.toHaveBeenCalled(); expect(processUpdate).not.toHaveBeenCalled(); expect(tx.$queryRaw).toHaveBeenCalledTimes(1); - expect(tx.$queryRaw.mock.calls[0][1]).toBe('product-money:CAR:product-1'); + expect(tx.$queryRaw.mock.calls[0][1]).toBe( + 'appointment-schedule:specialist-1', + ); }); it('returns conflict and creates no history when the manual transition loses its CAS claim', async () => { @@ -731,10 +722,15 @@ describe('ProcessesService — snapshot de entrada na negociação', () => { updated_at: new Date('2026-01-02T00:00:00.000Z'), }); const processUpdateMany = jest.fn().mockResolvedValue({ count: 0 }); + const negotiatedProcess = baseProcess({ + status: ProcessStatus.NEGOTIATION, + negotiation_currency: ProductCurrency.USD, + negotiation_product_value: new Prisma.Decimal('120000.00'), + }); const tx = { $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), process: { - findUniqueOrThrow: jest.fn().mockResolvedValue(baseProcess()), + findUniqueOrThrow: jest.fn().mockResolvedValue(negotiatedProcess), update: processUpdate, updateMany: processUpdateMany, }, @@ -751,7 +747,7 @@ describe('ProcessesService — snapshot de entrada na negociação', () => { await expect( service.update( 'process-1', - { status: ProcessStatus.NEGOTIATION, notes: 'Negociando' }, + { status: ProcessStatus.DOCUMENTATION, notes: 'Documentação' }, 'admin-1', UserRole.ADMIN, ), @@ -761,7 +757,7 @@ describe('ProcessesService — snapshot de entrada na negociação', () => { expect.objectContaining({ where: { id: 'process-1', - status: ProcessStatus.SCHEDULING, + status: ProcessStatus.NEGOTIATION, updated_at: new Date('2026-01-01T00:00:00.000Z'), }, }), @@ -2012,25 +2008,39 @@ describe('ProcessesService — autorização centralizada de processos', () => { sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined), } as any), processUpdateMany, + tx, }; } - function rejectionService(process = protectedProcess()) { - const processUpdate = jest.fn().mockResolvedValue({ + function rejectionService(process = protectedProcess(), claimCount = 1) { + const rejectedProcess = { ...process, status: ProcessStatus.REJECTED, updated_at: new Date('2026-01-02T00:00:00.000Z'), - }); + }; + const processUpdate = jest.fn(); + const processUpdateMany = jest + .fn() + .mockResolvedValue({ count: claimCount }); + const processFindUniqueOrThrow = jest + .fn() + .mockResolvedValueOnce(process) + .mockResolvedValueOnce(process) + .mockResolvedValueOnce(rejectedProcess); + const historyCreate = jest.fn().mockResolvedValue({}); + const rejectionCreate = jest.fn().mockResolvedValue({}); const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), process: { - findUniqueOrThrow: jest.fn().mockResolvedValue(process), + findUniqueOrThrow: processFindUniqueOrThrow, update: processUpdate, + updateMany: processUpdateMany, }, processStatusHistory: { - create: jest.fn().mockResolvedValue({}), + create: historyCreate, findMany: jest.fn().mockResolvedValue([]), }, - processRejection: { create: jest.fn().mockResolvedValue({}) }, + processRejection: { create: rejectionCreate }, }; const prisma = { $transaction: jest.fn(async (callback) => callback(tx)), @@ -2040,6 +2050,11 @@ describe('ProcessesService — autorização centralizada de processos', () => { sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined), } as any), processUpdate, + processUpdateMany, + processFindUniqueOrThrow, + historyCreate, + rejectionCreate, + tx, }; } @@ -2093,7 +2108,7 @@ describe('ProcessesService — autorização centralizada de processos', () => { expect(processUpdateMany).not.toHaveBeenCalled(); }); - it('especialista atribuído pode fazer a transição adjacente SCHEDULING para NEGOTIATION', async () => { + it('especialista atribuído não pode burlar a confirmação canônica para entrar em NEGOTIATION', async () => { const { service, processUpdateMany } = updateService(); await expect( @@ -2103,12 +2118,12 @@ describe('ProcessesService — autorização centralizada de processos', () => { assignedSpecialistId, UserRole.SPECIALIST, ), - ).resolves.toBeDefined(); + ).rejects.toThrow(BadRequestException); - expect(processUpdateMany).toHaveBeenCalledTimes(1); + expect(processUpdateMany).not.toHaveBeenCalled(); }); - it('OFFICE da empresa do cliente pode fazer transição adjacente', async () => { + it('OFFICE da empresa do cliente não pode burlar a confirmação canônica', async () => { const { service, processUpdateMany } = updateService(); await expect( @@ -2119,13 +2134,130 @@ describe('ProcessesService — autorização centralizada de processos', () => { UserRole.OFFICE, clientCompanyId, ), + ).rejects.toThrow(BadRequestException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('não promove consultoria sem produto/snapshot de NEGOTIATION para DOCUMENTATION', async () => { + const { service, processUpdateMany } = updateService( + protectedProcess({ status: ProcessStatus.NEGOTIATION }), + ); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.DOCUMENTATION }, + assignedSpecialistId, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(BadRequestException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('permite apenas NEGOTIATION para DOCUMENTATION com produto e snapshot', async () => { + const process = protectedProcess({ + status: ProcessStatus.NEGOTIATION, + product_type: ProductType.CAR, + car_id: productId, + negotiation_currency: ProductCurrency.USD, + negotiation_product_value: new Prisma.Decimal('120000.00'), + car: { id: productId, marca: 'Porsche', modelo: '911' }, + }); + const { service, processUpdateMany } = updateService(process); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.DOCUMENTATION }, + assignedSpecialistId, + UserRole.SPECIALIST, + ), ).resolves.toBeDefined(); expect(processUpdateMany).toHaveBeenCalledTimes(1); }); + it('revalida a transição após adquirir o lock e reler o processo', async () => { + const negotiableProcess = protectedProcess({ + status: ProcessStatus.NEGOTIATION, + product_type: ProductType.CAR, + car_id: productId, + negotiation_currency: ProductCurrency.USD, + negotiation_product_value: new Prisma.Decimal('120000.00'), + car: { id: productId, marca: 'Porsche', modelo: '911' }, + }); + const rejectedProcess = { + ...negotiableProcess, + status: ProcessStatus.REJECTED, + }; + const { service, processUpdateMany, tx } = updateService(); + tx.process.findUniqueOrThrow + .mockResolvedValueOnce(negotiableProcess) + .mockResolvedValueOnce(rejectedProcess); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.DOCUMENTATION }, + assignedSpecialistId, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(BadRequestException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('revalida a autorização após adquirir o lock e reler o processo', async () => { + const initiallyAuthorized = protectedProcess({ + status: ProcessStatus.NEGOTIATION, + }); + const movedToOtherCompany = protectedProcess({ + status: ProcessStatus.NEGOTIATION, + client: { + ...protectedProcess().client, + company_id: otherCompanyId, + consultant: { company_id: otherCompanyId }, + }, + }); + const { service, processUpdateMany, tx } = updateService(); + tx.process.findUniqueOrThrow + .mockResolvedValueOnce(initiallyAuthorized) + .mockResolvedValueOnce(movedToOtherCompany); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.DOCUMENTATION }, + 'office-1', + UserRole.OFFICE, + clientCompanyId, + ), + ).rejects.toThrow(ForbiddenException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('não conclui DOCUMENTATION manualmente sem o webhook de contrato', async () => { + const { service, processUpdateMany } = updateService( + protectedProcess({ status: ProcessStatus.DOCUMENTATION }), + ); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.COMPLETED }, + assignedSpecialistId, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(BadRequestException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + it('outsider não pode rejeitar processo alheio', async () => { - const { service, processUpdate } = rejectionService(); + const { service, processUpdate, tx } = rejectionService(); await expect( (service.rejectProcess as any)( @@ -2138,10 +2270,12 @@ describe('ProcessesService — autorização centralizada de processos', () => { ).rejects.toThrow(ForbiddenException); expect(processUpdate).not.toHaveBeenCalled(); + expect(tx.$queryRaw).not.toHaveBeenCalled(); }); it('cliente pode rejeitar o próprio processo ativo', async () => { - const { service, processUpdate } = rejectionService(); + const { service, processUpdate, processUpdateMany, tx } = + rejectionService(); await expect( service.rejectProcess( @@ -2154,7 +2288,37 @@ describe('ProcessesService — autorização centralizada de processos', () => { expect.objectContaining({ status: ProcessStatus.REJECTED }), ); - expect(processUpdate).toHaveBeenCalledTimes(1); + expect(tx.$queryRaw).toHaveBeenCalledWith( + expect.anything(), + `appointment-schedule:${assignedSpecialistId}`, + ); + expect(processUpdateMany).toHaveBeenCalledWith({ + where: expect.objectContaining({ + id: '99999999-9999-4999-8999-999999999999', + status: ProcessStatus.SCHEDULING, + updated_at: new Date('2026-01-01T00:00:00.000Z'), + }), + data: expect.objectContaining({ status: ProcessStatus.REJECTED }), + }); + expect(processUpdate).not.toHaveBeenCalled(); + }); + + it('rejeição perde a CAS sem criar histórico nem motivo', async () => { + const { service, historyCreate, rejectionCreate, processUpdateMany } = + rejectionService(protectedProcess(), 0); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + assignedSpecialistId, + undefined, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(ConflictException); + + expect(processUpdateMany).toHaveBeenCalledTimes(1); + expect(historyCreate).not.toHaveBeenCalled(); + expect(rejectionCreate).not.toHaveBeenCalled(); }); it('não permite rejeitar processo já concluído', async () => { diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts index 750d332..e6e7715 100644 --- a/backend/src/features/processes/processes.service.ts +++ b/backend/src/features/processes/processes.service.ts @@ -18,7 +18,9 @@ import { import { QueryDto } from 'src/shared/dto/query.dto'; import { AppointmentSchedulingMethod, + Prisma, ProcessStatus, + ProductCurrency, ProductType, StatusAgendamento, UserRole, @@ -28,10 +30,7 @@ import { UpdateProcessDto } from './dto/update-process.dto'; import { ProcessWithHistory } from './entity/process-history.response'; import { NotificationService } from 'src/features/notifications/notification.service'; import { buildNegotiationSnapshotUpdate } from './negotiation-snapshot'; -import { - acquireProductMonetaryLock, - lockNegotiationProductMoney, -} from '../products/product-monetary-lock'; +import { acquireProductMonetaryLock } from '../products/product-monetary-lock'; import { validateSpecialistProductAssociation } from '../products/product-association-validator'; import { lockAndAssertNoActiveProcess } from './process-dedup-lock'; import { parseDate, isFutureDate } from 'src/shared/utils/date.utils'; @@ -67,10 +66,10 @@ const PROCESS_STATUS_TRANSITIONS: Record< ProcessStatus, readonly ProcessStatus[] > = { - [ProcessStatus.SCHEDULING]: [ProcessStatus.NEGOTIATION], + [ProcessStatus.SCHEDULING]: [], [ProcessStatus.NEGOTIATION]: [ProcessStatus.DOCUMENTATION], - [ProcessStatus.PROCESSING_CONTRACT]: [ProcessStatus.DOCUMENTATION], - [ProcessStatus.DOCUMENTATION]: [ProcessStatus.COMPLETED], + [ProcessStatus.PROCESSING_CONTRACT]: [], + [ProcessStatus.DOCUMENTATION]: [], [ProcessStatus.COMPLETED]: [], [ProcessStatus.REJECTED]: [], }; @@ -156,6 +155,30 @@ export class ProcessesService { } } + private assertManualStatusPreconditions( + process: ProcessWithProducts & { + negotiation_currency?: ProductCurrency | null; + negotiation_product_value?: Prisma.Decimal | null; + }, + nextStatus: ProcessStatus, + ): void { + if (nextStatus !== ProcessStatus.DOCUMENTATION) return; + + const hasNegotiationProduct = + !!process.product_type && + !!this.getProductId(process) && + !!this.buildProduct(process); + const hasNegotiationSnapshot = + process.negotiation_currency != null && + process.negotiation_product_value != null; + + if (!hasNegotiationProduct || !hasNegotiationSnapshot) { + throw new BadRequestException( + 'O processo precisa de produto e snapshot de negociação antes da documentação', + ); + } + } + /** * Cria um objeto "product" de acordo com o processo enviado * @@ -1256,46 +1279,17 @@ export class ProcessesService { existingProcess.status, updateProcessDto.status, ); + this.assertManualStatusPreconditions( + existingProcess, + updateProcessDto.status, + ); - if (updateProcessDto.status === ProcessStatus.NEGOTIATION) { - await lockNegotiationProductMoney(tx, existingProcess); - existingProcess = await tx.process.findUniqueOrThrow({ - where: { id: processId }, - include: { - client: { - select: { - email: true, - name: true, - surname: true, - consultant_id: true, - company_id: true, - consultant: { select: { company_id: true } }, - }, - }, - specialist: { - select: { email: true, name: true, surname: true }, - }, - car: true, - boat: true, - aircraft: true, - }, - }); - if (existingProcess.status === updateProcessDto.status) { - throw new BadRequestException(); - } - } - - const snapshotData = - updateProcessDto.status === ProcessStatus.NEGOTIATION - ? buildNegotiationSnapshotUpdate(existingProcess) - : {}; const nextUpdatedAt = new Date(); const claim = await tx.process.updateMany({ data: { status: updateProcessDto.status, notes: updateProcessDto.notes, updated_at: nextUpdatedAt, - ...snapshotData, }, where: { id: processId, @@ -1991,7 +1985,35 @@ export class ProcessesService { try { const [updatedProcess, updatedStatusHistory] = await this.prismaService.$transaction(async (tx) => { - // Verificar se o processo existe + const candidate = await tx.process.findUniqueOrThrow({ + where: { id: processId }, + select: { + id: true, + client_id: true, + specialist_id: true, + client: { + select: { + consultant_id: true, + company_id: true, + consultant: { select: { company_id: true } }, + }, + }, + }, + }); + this.assertProcessAccess( + candidate, + { + id: rejectedById ?? '', + role: requesterRole as UserRole, + companyId: requesterCompanyId, + }, + 'reject', + ); + + // Mesma ordem de cancelamento/avanço: agenda do especialista, + // releitura do processo e só então a reivindicação CAS. + await acquireSpecialistScheduleLock(tx, candidate.specialist_id); + const existingProcess = await tx.process.findUniqueOrThrow({ where: { id: processId }, include: { @@ -2035,23 +2057,43 @@ export class ProcessesService { ); } - // Atualizar status para REJECTED - const process = await tx.process.update({ + const rejectedAt = new Date(); + const claim = await tx.process.updateMany({ data: { - status: 'REJECTED', - updated_at: new Date(), + status: ProcessStatus.REJECTED, + updated_at: rejectedAt, }, where: { id: processId, + client_id: existingProcess.client_id, + specialist_id: existingProcess.specialist_id, + status: existingProcess.status, + updated_at: existingProcess.updated_at, }, }); + if (claim.count !== 1) { + throw new ConflictException({ + success: false, + error: { + code: 'PROCESS_REJECTION_CONFLICT', + message: + 'O processo foi alterado por outra operação. Recarregue e tente novamente.', + details: { process_id: processId }, + }, + }); + } + + const process = await tx.process.findUniqueOrThrow({ + where: { id: processId }, + }); // Criar registro de histórico await tx.processStatusHistory.create({ data: { processId, - status: 'REJECTED', - changed_at: process.updated_at, + status: ProcessStatus.REJECTED, + changed_by: rejectedById, + changed_at: rejectedAt, }, }); From 733ce64b94aa5889eec1cb639757062900927f9e Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 12:05:17 -0300 Subject: [PATCH 30/60] fix(processes): align status actions with transition policy --- .../components/processes/ProcessCard.test.tsx | 52 ++++- .../src/components/processes/ProcessCard.tsx | 50 +++- .../processes/UpdateProcessStatusModal.tsx | 218 ++++++++---------- 3 files changed, 189 insertions(+), 131 deletions(-) diff --git a/frontend/src/components/processes/ProcessCard.test.tsx b/frontend/src/components/processes/ProcessCard.test.tsx index 85bf47b..3bfa483 100644 --- a/frontend/src/components/processes/ProcessCard.test.tsx +++ b/frontend/src/components/processes/ProcessCard.test.tsx @@ -10,6 +10,7 @@ import { getMeetingByProcess, getProcessCompletionReason, getProcessWithActiveContract, + rejectProcess, } from "../../services/processes.service"; import { rescheduleAppointment } from "../../services/appointments.service"; import { isoToLocalDateTimeInput } from "../../lib/appointment-datetime"; @@ -21,6 +22,7 @@ vi.mock("../../services/processes.service", () => ({ getProcessCompletionReason: vi.fn(), getProcessWithActiveContract: vi.fn(), markConversationDone: vi.fn(), + rejectProcess: vi.fn(), startMeeting: vi.fn(), updateProcessStatus: vi.fn(), })); @@ -50,7 +52,11 @@ const baseProcess: Process = { function renderCard( process: Process = baseProcess, - props: { isClientView?: boolean; onStatusUpdated?: () => void } = {}, + props: { + isClientView?: boolean; + isExpanded?: boolean; + onStatusUpdated?: () => void; + } = {}, ) { return render( @@ -72,6 +78,7 @@ describe("ProcessCard appointment time actions", () => { appointment_status: "SCHEDULED", }); vi.mocked(rescheduleAppointment).mockResolvedValue({} as never); + vi.mocked(rejectProcess).mockResolvedValue({} as never); }); afterEach(() => { @@ -320,6 +327,49 @@ describe("ProcessCard appointment time actions", () => { expect(screen.queryByText("Solicitação de agendamento")).toBeNull(); }); + it("offers only the authorized manual transition from negotiation", () => { + renderCard({ ...baseProcess, status: "NEGOTIATION" }, { isExpanded: true }); + + fireEvent.click(screen.getByRole("button", { name: "Alterar Status" })); + + const statusSelect = screen.getByLabelText(/Novo Status/i); + const options = within(statusSelect).getAllByRole("option"); + expect(options.map((option) => option.textContent)).toEqual([ + "Documentação", + ]); + expect(screen.queryByRole("option", { name: "Agendamento" })).toBeNull(); + expect(screen.queryByRole("option", { name: "Negociação" })).toBeNull(); + expect(screen.queryByRole("option", { name: "Concluído" })).toBeNull(); + expect(screen.queryByRole("option", { name: "Rejeitado" })).toBeNull(); + }); + + it.each(["SCHEDULING", "PROCESSING_CONTRACT", "DOCUMENTATION", "COMPLETED", "REJECTED"] as const)( + "hides the status pencil when %s has no manual transition", + (status) => { + renderCard({ ...baseProcess, status }, { isExpanded: true }); + + expect( + screen.queryByRole("button", { name: "Alterar Status" }), + ).toBeNull(); + }, + ); + + it("keeps rejection separate from the status selector", () => { + renderCard( + { ...baseProcess, status: "DOCUMENTATION" }, + { isExpanded: true }, + ); + + expect( + screen.queryByRole("button", { name: "Alterar Status" }), + ).toBeNull(); + fireEvent.click( + screen.getByRole("button", { name: "Recusar processo" }), + ); + expect(screen.getByText("Rejeitar Processo")).toBeTruthy(); + expect(screen.queryByLabelText(/Novo Status/i)).toBeNull(); + }); + it.each(["(11) 98765-4321", "+55 11 98765-4321"])("renders safe WhatsApp and preserves the original phone %s", (phone) => { renderCard({ ...baseProcess, client: { ...baseProcess.client!, email: "cliente@example.com", phone } }); const link = screen.getByRole("link", { name: /WhatsApp/i }); diff --git a/frontend/src/components/processes/ProcessCard.tsx b/frontend/src/components/processes/ProcessCard.tsx index 7a2f109..48e1c3b 100644 --- a/frontend/src/components/processes/ProcessCard.tsx +++ b/frontend/src/components/processes/ProcessCard.tsx @@ -98,6 +98,7 @@ export default function ProcessCard({ }: ProcessCardProps) { const navigate = useNavigate(); const [showUpdateModal, setShowUpdateModal] = useState(false); + const [showRejectModal, setShowRejectModal] = useState(false); const [completionReason, setCompletionReason] = useState(null); const [activeContract, setActiveContract] = useState(null); const [isConfirming, setIsConfirming] = useState(false); @@ -124,6 +125,16 @@ export default function ProcessCard({ // Verifica se é um processo de consultoria (sem produto atribuído) const isConsultancy = !process.product_type || !process.product_id; + const canManuallyAdvanceProcess = + !isClientView && process.status === "NEGOTIATION" && !isConsultancy; + const hasPendingAppointmentRejection = + process.status === "SCHEDULING" && + process.appointment_status === "PENDING" && + !!process.appointment_id; + const canRejectProcess = + process.status !== "COMPLETED" && + process.status !== "REJECTED" && + !hasPendingAppointmentRejection; // Contraparte do processo: quem esta olhando quer o contato do outro lado. // Nao ha fallback entre os dois — se o dado da contraparte nao veio, a @@ -453,7 +464,7 @@ export default function ProcessCard({

)}
- {!isClientView && ( + {canManuallyAdvanceProcess && ( + {/* A única transição manual aceita pelo backend. */} + {canManuallyAdvanceProcess && ( + + )} + + {canRejectProcess && ( + + )} {/* Negotiation Button: Only show if status is NEGOTIATION and process has product */} {process.status === "NEGOTIATION" && !isConsultancy && ( @@ -1047,10 +1070,15 @@ export default function ProcessCard({ {/* Update Status Modal */} setShowUpdateModal(false)} + isOpen={showUpdateModal || showRejectModal} + action={showRejectModal ? "reject" : "status"} + onClose={() => { + setShowUpdateModal(false); + setShowRejectModal(false); + }} onSuccess={() => { setShowUpdateModal(false); + setShowRejectModal(false); onStatusUpdated?.(); }} process={process} diff --git a/frontend/src/components/processes/UpdateProcessStatusModal.tsx b/frontend/src/components/processes/UpdateProcessStatusModal.tsx index 3009d52..23748e4 100644 --- a/frontend/src/components/processes/UpdateProcessStatusModal.tsx +++ b/frontend/src/components/processes/UpdateProcessStatusModal.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect } from "react"; +import { useState } from "react"; import { X, AlertTriangle } from "lucide-react"; import { useForm, Controller } from "react-hook-form"; import type { Process } from "../../services/processes.service"; @@ -12,80 +12,53 @@ interface UpdateProcessStatusModalProps { onClose: () => void; onSuccess?: () => void; process: Process; + action?: "status" | "reject"; } -type ProcessStatusWithRejected = Process["status"] | "REJECTED"; - interface UpdateProcessFormData { - status: ProcessStatusWithRejected; + status: Process["status"]; notes?: string; } /** - * Modal for updating process status and notes - * Includes support for REJECTED status with optional reason + * Keeps the sole manual status transition separate from process rejection. */ export default function UpdateProcessStatusModal({ isOpen, onClose, onSuccess, process, + action = "status", }: UpdateProcessStatusModalProps) { const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); - const [showRejectModal, setShowRejectModal] = useState(false); const [rejectionReason, setRejectionReason] = useState(""); const { control, handleSubmit, reset, - watch, formState: { errors }, } = useForm({ defaultValues: { - status: process.status as ProcessStatusWithRejected, + status: "DOCUMENTATION", notes: process.notes || "", }, }); - const selectedStatus = watch("status"); - - // Mostrar modal de rejeição quando REJECTED for selecionado - useEffect(() => { - if (selectedStatus === "REJECTED" && !showRejectModal) { - setShowRejectModal(true); - } - }, [selectedStatus]); - const statusOptions: Array<{ - value: ProcessStatusWithRejected; + value: Process["status"]; label: string; - danger?: boolean; }> = [ - { value: "SCHEDULING", label: "Agendamento" }, - { value: "NEGOTIATION", label: "Negociação" }, { value: "DOCUMENTATION", label: "Documentação" }, - { value: "COMPLETED", label: "Concluído" }, - { value: "REJECTED", label: "Rejeitado", danger: true }, ]; const onSubmit = async (data: UpdateProcessFormData) => { - // Se for REJECTED, mostrar modal de confirmação - if (data.status === "REJECTED") { - setShowRejectModal(true); - return; - } - try { setIsSubmitting(true); setError(null); - await updateProcessStatus( - process.id, - data.status as Process["status"], - data.notes - ); + await updateProcessStatus(process.id, data.status, data.notes); reset(); onClose(); @@ -106,7 +79,6 @@ export default function UpdateProcessStatusModal({ await rejectProcess(process.id, rejectionReason || undefined); - setShowRejectModal(false); setRejectionReason(""); reset(); onClose(); @@ -121,27 +93,104 @@ export default function UpdateProcessStatusModal({ }; const handleRejectCancel = () => { - setShowRejectModal(false); setRejectionReason(""); - reset({ - status: process.status as ProcessStatusWithRejected, - notes: process.notes || "", - }); + setError(null); + onClose(); }; const handleClose = () => { reset(); setError(null); - setShowRejectModal(false); setRejectionReason(""); onClose(); }; if (!isOpen) return null; + if (action === "reject") { + return ( +
+
event.stopPropagation()} + > +
+ +

+ Rejeitar Processo +

+
+ +
+

+ Tem certeza que deseja rejeitar este processo? Esta ação não pode + ser desfeita. +

+
+ +