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:{" "}
+
+ {new Date(input.appointmentDatetime).toLocaleString("pt-BR", {
+ timeZone: input.timeZone,
+ dateStyle: "short",
+ timeStyle: "short",
+ })}
+ {" "}
+ ({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.
+
+
+
+
+ E-mail do especialista
+ event.currentTarget.select()}
+ className="mt-1 w-full rounded bg-transparent py-2 text-sm font-medium text-ink focus:outline-none focus:ring-2 focus:ring-focus-ring"
+ />
+
+
+ {copyState === "copied" ? : }
+ Copiar e-mail
+
+ {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.
-
-
-
-
- {busy ? : }
- Enviar e-mail
-
-
-
- Escolher data e hora
-
-
- >
- )}
-
-
-
E-mail do especialista
-
-
+
+ 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.
+
+
+ {busy ? (
+
+ ) : (
+
+ )}
+ Solicitar reunião
+
);
}
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 (
+ navigate("/catalog/car/car-2")}>
+ Ver outro produto
+
+ );
+}
+
+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.
-
navigate("/register", {
state: {
@@ -552,50 +489,38 @@ export default function ProductPage() {
},
})
}
- className="w-full"
>
Criar Conta para Agendar
-
Já tem uma conta?{" "}
navigate("/login", {
state: { from: `/catalog/${productType}/${id}` },
})
}
- className="text-blue-600 hover:underline font-medium"
>
Fazer login
- ) : 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.
-
-
setIsStartProcessModalOpen(true)}
- className="w-full"
- >
- Iniciar processo para cliente
-
-
- ) : 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.
-
-
-
setIsStartProcessModalOpen(true)}
className="w-full"
@@ -604,108 +529,85 @@ export default function ProductPage() {
) : 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}
- />
- navigate("/customer/processes")}
- >
- Acompanhar em Meus Processos
-
- >
- )}
+
+ 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}
-
- )
- )}
-
) : (
{
+ onRequest={() => {
setDateTimeError(null);
setIsDateTimeModalOpen(true);
}}
@@ -737,7 +637,6 @@ export default function ProductPage() {
)}
)}
-
{calendlyModalUrl && isCalendlyModalOpen && (
)}
-
- setDateTimeError(null)}
- onOpenChange={setIsDateTimeModalOpen}
- onSubmit={handlePlatformScheduling}
- />
-
- {/* Modal do Consultor: iniciar processo para cliente */}
- {specialist && product && productType && id && (
+ {/* Unmount the dialog before success focus; its animated exit must not retain a focus trap. */}
+ {!currentRequest && user?.role === "CUSTOMER" && (
+ setDateTimeError(null)}
+ onOpenChange={setIsDateTimeModalOpen}
+ onSubmit={handleEmailScheduling}
+ />
+ )}
+ {specialist && productType && id && (
Date: Wed, 14 Oct 2026 09:41:50 -0300
Subject: [PATCH 12/60] fix: isolate owned appointment checks by render scope
---
.../src/hooks/useCheckAppointment.test.tsx | 125 +++++++++++++++++-
frontend/src/hooks/useCheckAppointment.ts | 34 +++--
2 files changed, 144 insertions(+), 15 deletions(-)
diff --git a/frontend/src/hooks/useCheckAppointment.test.tsx b/frontend/src/hooks/useCheckAppointment.test.tsx
index 1363abb..14c5d1f 100644
--- a/frontend/src/hooks/useCheckAppointment.test.tsx
+++ b/frontend/src/hooks/useCheckAppointment.test.tsx
@@ -4,7 +4,7 @@ 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 { StrictMode, useLayoutEffect } 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 };
@@ -33,6 +33,129 @@ beforeEach(() => { useAuth.setState({ user: customer }); vi.useFakeTimers(); vi.
afterEach(() => { cleanup(); useAuth.setState({ user: null }); vi.useRealTimers(); vi.resetAllMocks(); });
describe("owned appointment check hook", () => {
+ const initialScope = { specialistId: "specialist-1", productType: "CAR" as "CAR" | "BOAT" | "AIRCRAFT", productId: "car-1" as string | undefined };
+ const scopeChanges = [
+ { name: "customer identity", user: { ...customer, id: "customer-2" }, params: initialScope, loading: true },
+ { name: "role", user: { ...customer, role: "SPECIALIST" as const }, params: initialScope, loading: false },
+ { name: "missing identity", user: null, params: initialScope, loading: false },
+ { name: "specialist", user: customer, params: { ...initialScope, specialistId: "specialist-2" }, loading: true },
+ { name: "product type", user: customer, params: { ...initialScope, productType: "BOAT" as const }, loading: true },
+ { name: "product ID", user: customer, params: { ...initialScope, productId: "car-2" }, loading: true },
+ { name: "missing product", user: customer, params: { ...initialScope, productId: undefined }, loading: false },
+ ];
+
+ describe.each([false, true])("render isolation with StrictMode=%s", (strict) => {
+ it("reports an eligible initial render as loading before effects", () => {
+ const renders: ReturnType[] = [];
+ const commits: ReturnType[] = [];
+ renderHook(() => {
+ const value = useCheckAppointment("specialist-1", "CAR", "car-1");
+ renders.push({ ...value });
+ useLayoutEffect(() => { commits.push({ ...value }); });
+ return value;
+ }, { wrapper: strict ? StrictMode : undefined });
+ const unchecked = { existingAppointment: null, isLoading: true, error: null };
+ expect(commits).toEqual(commits.map(() => unchecked));
+ expect(renders).toEqual(renders.map(() => unchecked));
+ });
+
+ it.each(scopeChanges.flatMap((change) => [
+ { ...change, previous: found, resultName: "snapshot" },
+ { ...change, previous: { exists: false } as ExistingAppointmentCheck, resultName: "verified absence" },
+ ]))("hides $resultName before effects on a change of $name", async ({ user, params, loading, previous }) => {
+ vi.mocked(checkExistingAppointment).mockResolvedValueOnce(previous);
+ const renders: ReturnType[] = [];
+ const commits: ReturnType[] = [];
+ const { result, rerender } = renderHook((scope) => {
+ const value = useCheckAppointment(scope.specialistId, scope.productType, scope.productId);
+ renders.push({ ...value });
+ // Layout effects observe the committed value before the hook's passive reset.
+ useLayoutEffect(() => { commits.push({ ...value }); });
+ return value;
+ }, { initialProps: initialScope, wrapper: strict ? StrictMode : undefined });
+ await advance();
+ expect(result.current).toEqual({ existingAppointment: previous, isLoading: false, error: null });
+ renders.length = 0;
+ commits.length = 0;
+
+ act(() => { useAuth.setState({ user }); rerender(params); });
+
+ expect(renders.length).toBeGreaterThan(0);
+ expect(commits.length).toBeGreaterThan(0);
+ const unchecked = { existingAppointment: null, isLoading: loading, error: null };
+ expect(commits).toEqual(commits.map(() => unchecked));
+ expect(renders).toEqual(renders.map(() => unchecked));
+ });
+
+ it("hides a former customer's error from the first new commit", async () => {
+ vi.mocked(checkExistingAppointment).mockRejectedValueOnce(new Error("Former customer error"));
+ const commits: ReturnType[] = [];
+ const { result } = renderHook(() => {
+ const value = useCheckAppointment("specialist-1", "CAR", "car-1");
+ useLayoutEffect(() => { commits.push({ ...value }); });
+ return value;
+ }, { wrapper: strict ? StrictMode : undefined });
+ await advance();
+ expect(result.current.error).toBe("Former customer error");
+ commits.length = 0;
+ act(() => { useAuth.setState({ user: { ...customer, id: "customer-2" } }); });
+ const unchecked = { existingAppointment: null, isLoading: true, error: null };
+ expect(commits).toEqual(commits.map(() => unchecked));
+ });
+
+ it.each([
+ { name: "snapshot", value: found },
+ { name: "verified absence", value: { exists: false } as ExistingAppointmentCheck },
+ { name: "rejection", value: null },
+ ])("discards a stale $name across an account switch in every commit", async ({ value }) => {
+ const earlier = deferred();
+ const latest = deferred();
+ vi.mocked(checkExistingAppointment).mockReturnValueOnce(earlier.promise).mockReturnValueOnce(latest.promise);
+ const renders: ReturnType[] = [];
+ const commits: ReturnType[] = [];
+ const { result } = renderHook(() => {
+ const state = useCheckAppointment("specialist-1", "CAR", "car-1");
+ renders.push({ ...state });
+ useLayoutEffect(() => { commits.push({ ...state }); });
+ return state;
+ }, { wrapper: strict ? StrictMode : undefined });
+ await advance();
+ renders.length = 0;
+ commits.length = 0;
+ act(() => { useAuth.setState({ user: { ...customer, id: "customer-2" } }); });
+ await advance();
+ await act(async () => { if (value) earlier.resolve(value); else earlier.reject(new Error("obsolete")); });
+ const unchecked = { existingAppointment: null, isLoading: true, error: null };
+ expect(commits).toEqual(commits.map(() => unchecked));
+ expect(renders).toEqual(renders.map(() => unchecked));
+ expect(result.current).toEqual(unchecked);
+ await act(async () => { latest.resolve(found); });
+ expect(result.current).toEqual({ existingAppointment: found, isLoading: false, error: null });
+ });
+
+ it.each(scopeChanges.filter((change) => !change.loading).flatMap((change) => [
+ { ...change, outcome: "resolve" as const },
+ { ...change, outcome: "reject" as const },
+ ]))("stays unchecked after $name with an obsolete request that later $outcome", async ({ user, params, outcome }) => {
+ const pending = deferred();
+ vi.mocked(checkExistingAppointment).mockReturnValueOnce(pending.promise);
+ const commits: ReturnType[] = [];
+ const { result, rerender } = renderHook((scope) => {
+ const value = useCheckAppointment(scope.specialistId, scope.productType, scope.productId);
+ useLayoutEffect(() => { commits.push({ ...value }); });
+ return value;
+ }, { initialProps: initialScope, wrapper: strict ? StrictMode : undefined });
+ await advance();
+ commits.length = 0;
+ act(() => { useAuth.setState({ user }); rerender(params); });
+ await act(async () => { if (outcome === "resolve") pending.resolve(found); else pending.reject(new Error("obsolete")); });
+ const unchecked = { existingAppointment: null, isLoading: false, error: null };
+ expect(commits).toEqual(commits.map(() => unchecked));
+ expect(result.current).toEqual(unchecked);
+ expect(checkExistingAppointment).toHaveBeenCalledTimes(1);
+ });
+ });
+
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"));
diff --git a/frontend/src/hooks/useCheckAppointment.ts b/frontend/src/hooks/useCheckAppointment.ts
index bdcc181..3f14a53 100644
--- a/frontend/src/hooks/useCheckAppointment.ts
+++ b/frontend/src/hooks/useCheckAppointment.ts
@@ -17,38 +17,44 @@ export function useCheckAppointment(
): UseCheckAppointmentResult {
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 scopeKey = JSON.stringify([userId, role, specialistId, productType, productId]);
+ const isEligible = Boolean(userId && role === "CUSTOMER" && specialistId && productType && productId);
+ const [state, setState] = useState(() => ({
+ scopeKey, existingAppointment: null, isLoading: isEligible, error: null,
+ }));
const requestToken = useRef(0);
useEffect(() => {
const token = ++requestToken.current;
- setExistingAppointment(null);
- setError(null);
if (!userId || role !== "CUSTOMER" || !specialistId || !productType || !productId) {
- setIsLoading(false);
+ setState({ scopeKey, existingAppointment: null, isLoading: false, error: null });
return () => { requestToken.current = token + 1; };
}
- setIsLoading(true);
+ setState({ scopeKey, existingAppointment: null, isLoading: true, error: null });
const timer = setTimeout(async () => {
try {
const result = await checkExistingAppointment(specialistId, productType, productId);
- if (token === requestToken.current) setExistingAppointment(result);
+ if (token === requestToken.current) {
+ setState({ scopeKey, existingAppointment: result, isLoading: false, error: null });
+ }
} catch (error) {
if (token === requestToken.current) {
- setExistingAppointment(null);
- setError(error instanceof Error ? error.message : "Erro ao verificar agendamentos");
+ setState({
+ scopeKey, existingAppointment: null, isLoading: false,
+ error: error instanceof Error ? error.message : "Erro ao verificar agendamentos",
+ });
}
- } finally {
- if (token === requestToken.current) setIsLoading(false);
}
}, 500);
return () => {
requestToken.current = token + 1;
clearTimeout(timer);
};
- }, [userId, role, specialistId, productType, productId]);
+ }, [userId, role, specialistId, productType, productId, scopeKey]);
- return { existingAppointment, isLoading, error };
+ // Scope changes must be safe during render, before passive effects reset state.
+ if (!isEligible || state.scopeKey !== scopeKey) {
+ return { existingAppointment: null, isLoading: isEligible, error: null };
+ }
+ return { existingAppointment: state.existingAppointment, isLoading: state.isLoading, error: state.error };
}
From bfa6025973f6c6e5429b1d15271861590497193d Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 10:14:12 -0300
Subject: [PATCH 13/60] feat: confirm proposed times and expose WhatsApp safely
---
.../AppointmentDateTimeModal.test.tsx | 103 ++++-
.../appointments/AppointmentDateTimeModal.tsx | 91 +++-
.../components/processes/ProcessCard.test.tsx | 163 ++++++-
.../src/components/processes/ProcessCard.tsx | 96 +++--
.../StartProcessForClientModal.test.tsx | 407 ++++++++++++------
.../processes/StartProcessForClientModal.tsx | 151 +++++--
frontend/src/components/ui/dialog.tsx | 8 +-
.../src/pages/catalog/ProductPage.test.tsx | 43 +-
frontend/src/pages/catalog/ProductPage.tsx | 17 +-
.../pages/customer/ConsultoriaPage.test.tsx | 59 +++
.../src/pages/customer/ConsultoriaPage.tsx | 22 +-
.../src/pages/profile/ProfilePage.test.tsx | 57 +++
frontend/src/pages/profile/ProfilePage.tsx | 2 +-
frontend/src/services/specialists.service.ts | 6 +-
frontend/src/services/users.service.ts | 2 +-
15 files changed, 976 insertions(+), 251 deletions(-)
create mode 100644 frontend/src/pages/customer/ConsultoriaPage.test.tsx
create mode 100644 frontend/src/pages/profile/ProfilePage.test.tsx
diff --git a/frontend/src/components/appointments/AppointmentDateTimeModal.test.tsx b/frontend/src/components/appointments/AppointmentDateTimeModal.test.tsx
index e408ea2..7d75ca6 100644
--- a/frontend/src/components/appointments/AppointmentDateTimeModal.test.tsx
+++ b/frontend/src/components/appointments/AppointmentDateTimeModal.test.tsx
@@ -2,7 +2,8 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { browserTimeZone } from "../../lib/appointment-datetime";
+import { StrictMode, useState } from "react";
+import { browserTimeZone, isoToLocalDateTimeInput } from "../../lib/appointment-datetime";
import AppointmentDateTimeModal from "./AppointmentDateTimeModal";
const defaultProps = {
@@ -18,6 +19,7 @@ describe("AppointmentDateTimeModal", () => {
afterEach(() => {
cleanup();
vi.clearAllMocks();
+ vi.restoreAllMocks();
});
it("submits the selected local datetime as ISO", async () => {
@@ -107,4 +109,103 @@ describe("AppointmentDateTimeModal", () => {
expect(onClearServerError).toHaveBeenCalledOnce();
});
+
+ it.each(["2099-09-20T14:30:45.123-03:00", "2099-11-01T06:30:00.000Z"])(
+ "prefills and preserves the exact original ISO %s when unchanged",
+ async (initialValue) => {
+ const onSubmit = vi.fn();
+ render( );
+ expect((screen.getByLabelText("Data e hora") as HTMLInputElement).value).toBe(isoToLocalDateTimeInput(initialValue));
+ fireEvent.click(screen.getByRole("button", { name: defaultProps.submitLabel }));
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(initialValue));
+ },
+ );
+
+ it("converts edited local values with the browser's chosen DST offset", async () => {
+ const onSubmit = vi.fn();
+ render( );
+ fireEvent.change(screen.getByLabelText("Data e hora"), { target: { value: "2099-11-01T01:45" } });
+ fireEvent.click(screen.getByRole("button", { name: defaultProps.submitLabel }));
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(new Date("2099-11-01T01:45").toISOString()));
+ });
+
+ it("validates an unchanged past proposal and associates its error with the field", async () => {
+ const onSubmit = vi.fn();
+ render( );
+ fireEvent.click(screen.getByRole("button", { name: defaultProps.submitLabel }));
+ const alert = await screen.findByRole("alert");
+ expect(alert.textContent).toContain("Selecione uma data e hora futuras");
+ expect(screen.getByLabelText("Data e hora").getAttribute("aria-describedby")).toContain(alert.id);
+ expect(screen.getByLabelText("Data e hora").getAttribute("aria-invalid")).toBe("true");
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("associates the backend conflict with the datetime field", () => {
+ render( );
+ const alert = screen.getByRole("alert");
+ expect(alert.id).toBeTruthy();
+ expect(screen.getByLabelText("Data e hora").getAttribute("aria-describedby")).toContain(alert.id);
+ });
+
+ it("resets edited values when reopened with the proposal and handles invalid initial ISO", () => {
+ const initialValue = "2099-09-20T17:30:00.000Z";
+ const view = render( );
+ fireEvent.change(screen.getByLabelText("Data e hora"), { target: { value: "2099-09-21T10:00" } });
+ view.rerender( );
+ view.rerender( );
+ expect((screen.getByLabelText("Data e hora") as HTMLInputElement).value).toBe(isoToLocalDateTimeInput(initialValue));
+ view.rerender( );
+ expect((screen.getByLabelText("Data e hora") as HTMLInputElement).value).toBe("");
+ });
+
+ it("guards duplicate form submits even before a busy prop arrives", async () => {
+ let resolve!: () => void;
+ const onSubmit = vi.fn(() => new Promise((done) => { resolve = done; }));
+ render( );
+ fireEvent.change(screen.getByLabelText("Data e hora"), { target: { value: "2099-09-20T14:30" } });
+ const form = screen.getByRole("button", { name: defaultProps.submitLabel }).closest("form")!;
+ fireEvent.submit(form);
+ fireEvent.submit(form);
+ expect(onSubmit).toHaveBeenCalledOnce();
+ expect((screen.getByRole("button", { name: "Cancelar" }) as HTMLButtonElement).disabled).toBe(true);
+ resolve();
+ await waitFor(() => expect((screen.getByRole("button", { name: "Cancelar" }) as HTMLButtonElement).disabled).toBe(false));
+ });
+
+ it.each(["2026-11-01T05:30:00.000Z", "2026-11-01T06:30:00.000Z"])("retains either DST instant after edit and revert: %s", async (initialValue) => {
+ vi.spyOn(Date, "now").mockReturnValue(new Date("2026-10-14T00:00:00.000Z").getTime());
+ const onSubmit = vi.fn();
+ render( );
+ fireEvent.change(screen.getByLabelText("Data e hora"), { target: { value: "2026-11-02T10:00" } });
+ fireEvent.change(screen.getByLabelText("Data e hora"), { target: { value: isoToLocalDateTimeInput(initialValue) } });
+ fireEvent.click(screen.getByRole("button", { name: defaultProps.submitLabel }));
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(initialValue));
+ });
+
+ it("validates the original seconds instead of the truncated displayed minute", async () => {
+ const initialValue = "2026-10-20T17:30:45.123Z";
+ vi.spyOn(Date, "now").mockReturnValue(new Date("2026-10-20T17:30:30.000Z").getTime());
+ const onSubmit = vi.fn();
+ render( );
+ fireEvent.click(screen.getByRole("button", { name: defaultProps.submitLabel }));
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(initialValue));
+ });
+
+ it("captures and restores the opener without an explicit ref under StrictMode", async () => {
+ function Harness() {
+ const [open, setOpen] = useState(false);
+ return <>
+ setOpen(true)}>Propor horário
+
+ >;
+ }
+ 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"
>
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
-
+
{
- if (hasValidScheduledMeetingDate && scheduledMeetingDate) {
- void handleConfirmAppointment(
- scheduledMeetingDate.toISOString(),
- );
- } else {
+ <>
+ {hasValidScheduledMeetingDate && (
+ {
+ dateTimeTriggerRef.current = event.currentTarget;
+ void handleConfirmAppointment(process.appointment_datetime!);
+ }}
+ disabled={isConfirming || isCancelling}
+ aria-busy={isConfirming}
+ className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg font-medium hover:bg-green-700 transition disabled:opacity-50"
+ >
+ {isConfirming ? : }
+ Confirmar horário
+
+ )}
+ {
+ dateTimeTriggerRef.current = event.currentTarget;
setDateTimeActionError(null);
setDateTimeAction("confirm");
- }
- }}
- disabled={isConfirming || isCancelling}
- className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg font-medium hover:bg-green-700 transition disabled:opacity-50"
- >
- {isConfirming ? (
-
- ) : (
- <>
-
- {hasValidScheduledMeetingDate
- ? "Confirmar"
- : "Definir data e hora"}
- >
- )}
-
+ }}
+ 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 && (
{
+ onClick={(event) => {
+ dateTimeTriggerRef.current = event.currentTarget;
setDateTimeActionError(null);
setDateTimeAction("reschedule");
}}
@@ -1036,10 +1058,12 @@ export default function ProcessCard({
({
- getPublicSpecialistById: vi.fn(),
-}));
+const { popupClosers } = vi.hoisted(() => ({ popupClosers: [] as Array<() => void> }));
+
+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/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("../../services/appointments.service", () => ({ getCalendlySyncStatus: vi.fn(), registerCalendlyScheduledEvent: vi.fn() }));
vi.mock("react-calendly", () => ({
+ PopupModal: ({ url, prefill, onModalClose }: { url: string; prefill: { name?: string; email?: string }; onModalClose(): void }) => {
+ popupClosers.push(onModalClose);
+ return <>Agendar no Calendly Fechar 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 }
- />
-
- ,
- );
+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({
setSelectedClient(c)}
className={`w-full text-left px-3 py-2 hover:bg-gray-50 transition-colors ${
selectedClient?.id === c.id ? "bg-blue-50" : ""
@@ -224,19 +301,24 @@ export default function StartProcessForClientModal({
)}
- {error &&
{error}
}
+ {specialistError &&
{specialistError}
}
+ {error &&
{error}
}
{calendlyMessage && (
{calendlyMessage}
)}
-
+ {
+ if (submittingRef.current) return;
+ operationGeneration.current += 1;
+ onClose();
+ }} disabled={isSubmitting}>
Cancelar
{isSubmitting ? "Criando..." : "Criar processo"}
@@ -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 = (
+
+
+
+ {title}
+
+
+
+
+
+ {children}
+
+ );
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.
+
- {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 && (
setShowUpdateModal(true)}
className="p-1 hover:bg-gray-100 rounded transition shrink-0"
@@ -966,14 +977,26 @@ export default function ProcessCard({
{/* Action Buttons */}
- {/* Update Status Button */}
-
setShowUpdateModal(true)}
- className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 md:px-4 md:py-2 border border-slate-700 text-slate-700 text-xs md:text-sm font-medium rounded-lg hover:bg-slate-50 transition-colors"
- >
-
- Alterar Status
-
+ {/* A única transição manual aceita pelo backend. */}
+ {canManuallyAdvanceProcess && (
+
setShowUpdateModal(true)}
+ className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 md:px-4 md:py-2 border border-slate-700 text-slate-700 text-xs md:text-sm font-medium rounded-lg hover:bg-slate-50 transition-colors"
+ >
+
+ Alterar Status
+
+ )}
+
+ {canRejectProcess && (
+
setShowRejectModal(true)}
+ className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 md:px-4 md:py-2 border border-red-300 text-red-700 text-xs md:text-sm font-medium rounded-lg hover:bg-red-50 transition-colors"
+ >
+
+ Recusar processo
+
+ )}
{/* 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.
+
+
+
+ Motivo da Rejeição{" "}
+ (opcional)
+
+
+
+ {error && (
+
+ )}
+
+
+
+
+ Cancelar
+
+
+ {isSubmitting ? "Rejeitando..." : "Confirmar Rejeição"}
+
+
+
+
+ );
+ }
+
return (
-
-
e.stopPropagation()}>
+
+
event.stopPropagation()}
+ >
{/* Header */}
@@ -178,7 +227,10 @@ export default function UpdateProcessStatusModal({
{/* Status Select */}
-
+
Novo Status *
(
{statusOptions.map((option) => (
-
+
{option.label}
))}
@@ -255,75 +304,6 @@ export default function UpdateProcessStatusModal({
-
- {/* Modal de Confirmação de Rejeição */}
- {showRejectModal && (
-
setShowRejectModal(false)}>
-
e.stopPropagation()}>
- {/* Header */}
-
-
-
- Rejeitar Processo
-
-
-
- {/* Content */}
-
-
- Tem certeza que deseja rejeitar este processo? Esta ação não
- pode ser desfeita.
-
-
- {/* Motivo da Rejeição */}
-
-
- Motivo da Rejeição{" "}
- (opcional)
-
-
-
- {/* Error */}
- {error && (
-
- )}
-
-
- {/* Actions */}
-
-
- Cancelar
-
-
- {isSubmitting ? "Rejeitando..." : "Confirmar Rejeição"}
-
-
-
-
- )}
);
}
From 13df78214b031a266a694eb11ab8bcd73fc36224 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:05:24 -0300
Subject: [PATCH 31/60] fix(appointments): serialize Calendly webhooks
---
.../appointments/appointments.service.spec.ts | 95 ++++++
.../appointments/appointments.service.ts | 22 ++
.../calendly-integration.service.spec.ts | 311 +++++++++++++++---
.../calendly-integration.service.ts | 155 +++++++--
4 files changed, 498 insertions(+), 85 deletions(-)
diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts
index 1b066fd..ad4dc98 100644
--- a/backend/src/features/appointments/appointments.service.spec.ts
+++ b/backend/src/features/appointments/appointments.service.spec.ts
@@ -1849,6 +1849,101 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
expect(prisma.$transaction).not.toHaveBeenCalled();
});
+ it('rejeita o mesmo evento quando já está associado a outro convidado', 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_invitee_uri:
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-old',
+ };
+ const prisma = {
+ appointment: {
+ findUnique: jest.fn().mockResolvedValue(appointment),
+ updateMany: jest.fn(),
+ },
+ $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-new',
+ }),
+ ).rejects.toThrow(ConflictException);
+ expect(prisma.appointment.updateMany).not.toHaveBeenCalled();
+ expect(
+ calendlyIntegrationService.resolveScheduledStartTime,
+ ).not.toHaveBeenCalled();
+ expect(prisma.$transaction).not.toHaveBeenCalled();
+ });
+
+ it('revalida sob lock e rejeita outro convidado gravado concorrentemente', 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: null,
+ calendly_invitee_uri: null,
+ };
+ const lockedAppointment = {
+ ...appointment,
+ calendly_event_uri:
+ 'https://api.calendly.com/scheduled_events/event-1',
+ calendly_invitee_uri:
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-old',
+ };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn().mockResolvedValue(lockedAppointment),
+ update: jest.fn(),
+ },
+ };
+ const prisma = {
+ appointment: { findUnique: jest.fn().mockResolvedValue(appointment) },
+ $transaction: jest.fn(async (callback: (client: any) => unknown) =>
+ callback(tx),
+ ),
+ } 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-new',
+ scheduled_start_time: '2099-01-01T10:00:00.000Z',
+ }),
+ ).rejects.toThrow(ConflictException);
+ expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
+ expect(tx.appointment.update).not.toHaveBeenCalled();
+ });
+
it('não ignora falha de integridade detectada na resposta do Calendly', async () => {
const appointment = {
id: 'appointment-1',
diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts
index bb8aebe..8a1ddb3 100644
--- a/backend/src/features/appointments/appointments.service.ts
+++ b/backend/src/features/appointments/appointments.service.ts
@@ -1951,6 +1951,17 @@ export class AppointmentsService {
parseCalendlyResourceUri(appointment.calendly_event_uri, 'event')
?.canonicalUri === eventUri
) {
+ if (
+ appointment.calendly_invitee_uri &&
+ parseCalendlyResourceUri(
+ appointment.calendly_invitee_uri,
+ 'invitee',
+ )?.canonicalUri !== inviteeUri
+ ) {
+ throw new ConflictException(
+ 'O evento do Calendly já está associado a outro convidado',
+ );
+ }
let canonicalized = true;
if (
appointment.calendly_event_uri !== eventUri ||
@@ -2063,6 +2074,17 @@ export class AppointmentsService {
'event',
)?.canonicalUri === eventUri
) {
+ if (
+ lockedAppointment.calendly_invitee_uri &&
+ parseCalendlyResourceUri(
+ lockedAppointment.calendly_invitee_uri,
+ 'invitee',
+ )?.canonicalUri !== inviteeUri
+ ) {
+ throw new ConflictException(
+ 'O evento do Calendly já está associado a outro convidado',
+ );
+ }
if (
lockedAppointment.calendly_event_uri !== eventUri ||
lockedAppointment.calendly_invitee_uri !== inviteeUri
diff --git a/backend/src/features/appointments/calendly-integration.service.spec.ts b/backend/src/features/appointments/calendly-integration.service.spec.ts
index 4d7fb41..92d453a 100644
--- a/backend/src/features/appointments/calendly-integration.service.spec.ts
+++ b/backend/src/features/appointments/calendly-integration.service.spec.ts
@@ -1,3 +1,4 @@
+import { ConflictException } from '@nestjs/common';
import { AppointmentSchedulingMethod } from '@prisma/client';
import { CalendlyIntegrationService } from './calendly-integration.service';
import axios from 'axios';
@@ -452,7 +453,7 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
};
const prisma = {
appointment: {
- findFirst: jest.fn().mockResolvedValue(appointment),
+ findMany: jest.fn().mockResolvedValue([appointment]),
update: jest.fn(),
},
$transaction: jest.fn(),
@@ -489,7 +490,7 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
specialist_rescheduled_at: new Date('2026-01-01T00:00:00.000Z'),
};
const prisma = {
- appointment: { findFirst: jest.fn().mockResolvedValue(appointment) },
+ appointment: { findMany: jest.fn().mockResolvedValue([appointment]) },
$transaction: jest.fn(),
};
const service = new CalendlyIntegrationService(prisma as any);
@@ -524,6 +525,8 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
'https://calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1',
calendly_sync_status: 'PENDING',
appointment_datetime: null,
+ scheduling_method: AppointmentSchedulingMethod.CALENDLY,
+ specialist_rescheduled_at: null,
};
const tx = {
$queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
@@ -535,7 +538,8 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
};
const prisma = {
appointment: {
- findFirst: jest.fn().mockResolvedValue(appointment),
+ findMany: jest.fn().mockResolvedValue([appointment]),
+ findFirst: jest.fn(),
update: jest.fn().mockResolvedValue(appointment),
},
$transaction: jest.fn(async (callback: (client: any) => unknown) =>
@@ -553,43 +557,31 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
payload: {
event:
'https://calendly.com/api/v2/scheduled_events/event-1',
- invitee:
+ uri:
'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1',
scheduled_event: {
start_time: '2099-01-01T10:00:00.000Z',
},
},
- },
+ } as any,
undefined,
undefined,
);
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
- expect(prisma.appointment.findFirst).toHaveBeenCalledWith({
+ expect(prisma.appointment.findMany).toHaveBeenCalledWith({
where: {
- OR: [
- {
- 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: {
- 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',
- ]),
- },
- },
- ],
+ 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',
+ ]),
+ },
},
+ take: 2,
});
+ expect(prisma.appointment.findFirst).not.toHaveBeenCalled();
expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
expect(tx.appointment.findUnique).toHaveBeenCalledWith({
where: { id: appointment.id },
@@ -626,11 +618,20 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
calendly_invitee_uri:
'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1',
};
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn().mockResolvedValue(appointment),
+ updateMany: jest.fn().mockResolvedValue({ count: 1 }),
+ },
+ };
const prisma = {
appointment: {
- findFirst: jest.fn().mockResolvedValue(appointment),
- update: jest.fn().mockResolvedValue(appointment),
+ findMany: jest.fn().mockResolvedValue([appointment]),
},
+ $transaction: jest.fn(async (callback: (client: any) => unknown) =>
+ callback(tx),
+ ),
};
const service = new CalendlyIntegrationService(prisma as any);
jest
@@ -644,10 +645,10 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
payload: {
event:
'https://api.calendly.com/scheduled_events/event-1',
- invitee:
+ uri:
'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
},
- },
+ } as any,
undefined,
undefined,
),
@@ -655,30 +656,24 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
processed: true,
message: 'Webhook de cancelamento processado',
});
- expect(prisma.appointment.findFirst).toHaveBeenCalledWith({
+ expect(prisma.appointment.findMany).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',
- ]),
- },
- },
- ],
+ calendly_invitee_uri: {
+ in: expect.arrayContaining([
+ appointment.calendly_invitee_uri,
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
+ ]),
+ },
},
+ take: 2,
});
- expect(prisma.appointment.update).toHaveBeenCalledWith({
- where: { id: appointment.id },
+ expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
+ expect(tx.appointment.updateMany).toHaveBeenCalledWith({
+ where: {
+ id: appointment.id,
+ calendly_event_uri: appointment.calendly_event_uri,
+ calendly_invitee_uri: appointment.calendly_invitee_uri,
+ },
data: {
calendly_event_uri:
'https://api.calendly.com/scheduled_events/event-1',
@@ -689,4 +684,216 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
},
});
});
+
+ it('falha fechado quando fallback por evento encontra dois convidados do mesmo grupo', async () => {
+ const appointments = [
+ {
+ id: 'appointment-1',
+ specialist_id: 'specialist-1',
+ calendly_event_uri:
+ 'https://api.calendly.com/scheduled_events/group-event',
+ },
+ {
+ id: 'appointment-2',
+ specialist_id: 'specialist-1',
+ calendly_event_uri:
+ 'https://calendly.com/api/v2/scheduled_events/group-event',
+ },
+ ];
+ const prisma = {
+ appointment: { findMany: jest.fn().mockResolvedValue(appointments) },
+ $transaction: jest.fn(),
+ };
+ const service = new CalendlyIntegrationService(prisma as any);
+ jest
+ .spyOn(service as any, 'validateWebhookSignature')
+ .mockReturnValue(undefined);
+
+ await expect(
+ service.processWebhook(
+ {
+ event: 'invitee.created',
+ payload: {
+ event:
+ 'https://api.calendly.com/scheduled_events/group-event',
+ },
+ },
+ undefined,
+ undefined,
+ ),
+ ).rejects.toThrow(ConflictException);
+ expect(prisma.appointment.findMany).toHaveBeenCalledWith({
+ where: {
+ calendly_event_uri: {
+ in: expect.arrayContaining([
+ 'https://api.calendly.com/scheduled_events/group-event',
+ 'https://calendly.com/api/v2/scheduled_events/group-event',
+ ]),
+ },
+ },
+ take: 2,
+ });
+ expect(prisma.$transaction).not.toHaveBeenCalled();
+ });
+
+ it('não deixa webhook created antigo sobrescrever uma nova associação', async () => {
+ const snapshot = {
+ id: 'appointment-1',
+ specialist_id: 'specialist-1',
+ scheduling_method: AppointmentSchedulingMethod.CALENDLY,
+ specialist_rescheduled_at: null,
+ calendly_event_uri:
+ 'https://api.calendly.com/scheduled_events/event-1',
+ calendly_invitee_uri:
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-old',
+ };
+ const locked = {
+ ...snapshot,
+ calendly_invitee_uri:
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-new',
+ };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn().mockResolvedValue(locked),
+ findFirst: jest.fn(),
+ update: jest.fn(),
+ },
+ };
+ const prisma = {
+ appointment: { findMany: jest.fn().mockResolvedValue([snapshot]) },
+ $transaction: jest.fn(async (callback: (client: any) => unknown) =>
+ callback(tx),
+ ),
+ };
+ const service = new CalendlyIntegrationService(prisma as any);
+ jest
+ .spyOn(service as any, 'validateWebhookSignature')
+ .mockReturnValue(undefined);
+
+ await expect(
+ service.processWebhook(
+ {
+ event: 'invitee.created',
+ payload: {
+ event:
+ 'https://api.calendly.com/scheduled_events/event-1',
+ uri: snapshot.calendly_invitee_uri,
+ scheduled_event: { start_time: '2099-01-01T10:00:00.000Z' },
+ },
+ } as any,
+ undefined,
+ undefined,
+ ),
+ ).resolves.toEqual({
+ processed: false,
+ message: 'Webhook ignorado para preservar a associação atual',
+ });
+ expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
+ expect(tx.appointment.findFirst).not.toHaveBeenCalled();
+ expect(tx.appointment.update).not.toHaveBeenCalled();
+ });
+
+ it('serializa cancelamento e não confirma processamento quando perde o CAS', async () => {
+ const appointment = {
+ id: 'appointment-1',
+ specialist_id: 'specialist-1',
+ scheduling_method: AppointmentSchedulingMethod.CALENDLY,
+ specialist_rescheduled_at: null,
+ 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',
+ };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn().mockResolvedValue(appointment),
+ updateMany: jest.fn().mockResolvedValue({ count: 0 }),
+ },
+ };
+ const prisma = {
+ appointment: { findMany: jest.fn().mockResolvedValue([appointment]) },
+ $transaction: jest.fn(async (callback: (client: any) => unknown) =>
+ callback(tx),
+ ),
+ };
+ const service = new CalendlyIntegrationService(prisma as any);
+ jest
+ .spyOn(service as any, 'validateWebhookSignature')
+ .mockReturnValue(undefined);
+
+ await expect(
+ service.processWebhook(
+ {
+ event: 'invitee.canceled',
+ payload: {
+ event: appointment.calendly_event_uri,
+ uri: appointment.calendly_invitee_uri,
+ },
+ } as any,
+ undefined,
+ undefined,
+ ),
+ ).resolves.toEqual({
+ processed: false,
+ message: 'Webhook ignorado para preservar a associação atual',
+ });
+ expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
+ expect(tx.appointment.updateMany).toHaveBeenCalledTimes(1);
+ });
+
+ it('não deixa webhook canceled antigo cancelar uma nova associação', async () => {
+ const snapshot = {
+ id: 'appointment-1',
+ specialist_id: 'specialist-1',
+ scheduling_method: AppointmentSchedulingMethod.CALENDLY,
+ specialist_rescheduled_at: null,
+ calendly_event_uri:
+ 'https://api.calendly.com/scheduled_events/event-1',
+ calendly_invitee_uri:
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-old',
+ };
+ const locked = {
+ ...snapshot,
+ calendly_invitee_uri:
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-new',
+ };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn().mockResolvedValue(locked),
+ updateMany: jest.fn(),
+ },
+ };
+ const prisma = {
+ appointment: { findMany: jest.fn().mockResolvedValue([snapshot]) },
+ $transaction: jest.fn(async (callback: (client: any) => unknown) =>
+ callback(tx),
+ ),
+ };
+ const service = new CalendlyIntegrationService(prisma as any);
+ jest
+ .spyOn(service as any, 'validateWebhookSignature')
+ .mockReturnValue(undefined);
+
+ await expect(
+ service.processWebhook(
+ {
+ event: 'invitee.canceled',
+ payload: {
+ event: snapshot.calendly_event_uri,
+ uri: snapshot.calendly_invitee_uri,
+ },
+ } as any,
+ undefined,
+ undefined,
+ ),
+ ).resolves.toEqual({
+ processed: false,
+ message: 'Webhook ignorado para preservar a associação atual',
+ });
+ expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
+ expect(tx.appointment.updateMany).not.toHaveBeenCalled();
+ });
});
diff --git a/backend/src/features/appointments/calendly-integration.service.ts b/backend/src/features/appointments/calendly-integration.service.ts
index e450d19..86cd521 100644
--- a/backend/src/features/appointments/calendly-integration.service.ts
+++ b/backend/src/features/appointments/calendly-integration.service.ts
@@ -1,5 +1,6 @@
import {
BadRequestException,
+ ConflictException,
ForbiddenException,
Injectable,
InternalServerErrorException,
@@ -9,7 +10,6 @@ import {
import {
AppointmentSchedulingMethod,
CalendlySyncStatus,
- Prisma,
UserRole,
} from '@prisma/client';
import axios from 'axios';
@@ -54,6 +54,7 @@ interface CalendlyWebhookPayload {
event?: string;
payload?: {
event?: string;
+ uri?: string;
invitee?: string | { uri?: string };
scheduled_event?: {
uri?: string;
@@ -397,10 +398,12 @@ export class CalendlyIntegrationService {
}
const rawEventUri = payload.event || payload.scheduled_event?.uri;
- const rawInviteeUri =
+ const rawOfficialInviteeUri = payload.uri;
+ const rawLegacyInviteeUri =
typeof payload.invitee === 'string'
? payload.invitee
: payload.invitee?.uri;
+ const rawInviteeUri = rawOfficialInviteeUri || rawLegacyInviteeUri;
if (!rawEventUri && !rawInviteeUri) {
return {
@@ -412,9 +415,24 @@ export class CalendlyIntegrationService {
const eventReference = rawEventUri
? this.parseCalendlyResourceUri(rawEventUri, 'event')
: null;
- const inviteeReference = rawInviteeUri
- ? this.parseCalendlyResourceUri(rawInviteeUri, 'invitee')
+ const officialInviteeReference = rawOfficialInviteeUri
+ ? this.parseCalendlyResourceUri(rawOfficialInviteeUri, 'invitee')
: null;
+ const legacyInviteeReference = rawLegacyInviteeUri
+ ? this.parseCalendlyResourceUri(rawLegacyInviteeUri, 'invitee')
+ : null;
+ if (
+ officialInviteeReference &&
+ legacyInviteeReference &&
+ officialInviteeReference.canonicalUri !==
+ legacyInviteeReference.canonicalUri
+ ) {
+ throw new BadRequestException(
+ 'URIs de convidado do Calendly são inconsistentes',
+ );
+ }
+ const inviteeReference =
+ officialInviteeReference || legacyInviteeReference;
this.assertSameCalendlyEvent(eventReference, inviteeReference);
const lookupEventReference =
eventReference ||
@@ -427,26 +445,26 @@ export class CalendlyIntegrationService {
const eventUri = lookupEventReference?.canonicalUri;
const inviteeUri = inviteeReference?.canonicalUri;
- const appointment = await this.prisma.appointment.findFirst({
- where: {
- OR: [
- lookupEventReference
- ? {
- calendly_event_uri: {
- in: getCalendlyResourceUriVariants(lookupEventReference),
- },
- }
- : undefined,
- inviteeReference
- ? {
- calendly_invitee_uri: {
- in: getCalendlyResourceUriVariants(inviteeReference),
- },
- }
- : undefined,
- ].filter(Boolean) as Prisma.AppointmentWhereInput[],
- },
+ const appointments = await this.prisma.appointment.findMany({
+ where: inviteeReference
+ ? {
+ calendly_invitee_uri: {
+ in: getCalendlyResourceUriVariants(inviteeReference),
+ },
+ }
+ : {
+ calendly_event_uri: {
+ in: getCalendlyResourceUriVariants(lookupEventReference!),
+ },
+ },
+ take: 2,
});
+ if (appointments.length > 1) {
+ throw new ConflictException(
+ 'Webhook Calendly corresponde a múltiplos agendamentos',
+ );
+ }
+ const appointment = appointments[0];
if (!appointment) {
return {
@@ -496,6 +514,15 @@ export class CalendlyIntegrationService {
) {
return false;
}
+ if (
+ !this.appointmentStillMatchesWebhook(
+ lockedAppointment,
+ lookupEventReference,
+ inviteeReference,
+ )
+ ) {
+ return false;
+ }
const targetDateTime =
parsedStartTime || lockedAppointment.appointment_datetime;
@@ -527,7 +554,7 @@ export class CalendlyIntegrationService {
if (!processed) {
return {
processed: false,
- message: 'Webhook ignorado para preservar o horário atual',
+ message: 'Webhook ignorado para preservar a associação atual',
};
}
@@ -538,17 +565,51 @@ export class CalendlyIntegrationService {
}
if (eventType === 'invitee.canceled') {
- 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,
- },
+ const processed = await this.prisma.$transaction(async (tx) => {
+ await acquireSpecialistScheduleLock(tx, appointment.specialist_id);
+ const lockedAppointment = await tx.appointment.findUnique({
+ where: { id: appointment.id },
+ });
+ if (
+ !lockedAppointment ||
+ (lockedAppointment.scheduling_method &&
+ lockedAppointment.scheduling_method !==
+ AppointmentSchedulingMethod.CALENDLY) ||
+ lockedAppointment.specialist_rescheduled_at ||
+ !this.appointmentStillMatchesWebhook(
+ lockedAppointment,
+ lookupEventReference,
+ inviteeReference,
+ )
+ ) {
+ return false;
+ }
+
+ const updated = await tx.appointment.updateMany({
+ where: {
+ id: lockedAppointment.id,
+ calendly_event_uri: lockedAppointment.calendly_event_uri,
+ calendly_invitee_uri: lockedAppointment.calendly_invitee_uri,
+ },
+ data: {
+ calendly_event_uri:
+ eventUri || lockedAppointment.calendly_event_uri,
+ calendly_invitee_uri:
+ inviteeUri || lockedAppointment.calendly_invitee_uri,
+ calendly_last_sync_at: new Date(),
+ calendly_sync_status: CalendlySyncStatus.FAILED,
+ },
+ });
+ return updated.count === 1;
});
+ if (!processed) {
+ return {
+ processed: false,
+ message: 'Webhook ignorado para preservar a associação atual',
+ };
+ }
+
return {
processed: true,
message: 'Webhook de cancelamento processado',
@@ -920,6 +981,34 @@ export class CalendlyIntegrationService {
}
}
+ private appointmentStillMatchesWebhook(
+ appointment: {
+ calendly_event_uri?: string | null;
+ calendly_invitee_uri?: string | null;
+ },
+ eventReference: CalendlyResourceReference | null,
+ inviteeReference: CalendlyResourceReference | null,
+ ): boolean {
+ if (inviteeReference) {
+ const currentInvitee = appointment.calendly_invitee_uri
+ ? parseCalendlyResourceUri(
+ appointment.calendly_invitee_uri,
+ 'invitee',
+ )
+ : null;
+ return currentInvitee?.canonicalUri === inviteeReference.canonicalUri;
+ }
+
+ if (eventReference) {
+ const currentEvent = appointment.calendly_event_uri
+ ? parseCalendlyResourceUri(appointment.calendly_event_uri, 'event')
+ : null;
+ return currentEvent?.canonicalUri === eventReference.canonicalUri;
+ }
+
+ return false;
+ }
+
private getRequiredEnv(name: string): string {
const value = process.env[name];
if (!value) {
From 32f64e130a3e732cca1c47eb74fd910c2a7be304 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:09:40 -0300
Subject: [PATCH 32/60] fix(appointments): harden Calendly trust boundary
---
README.md | 2 +-
backend/.env.example | 3 +
backend/README.md | 8 +-
.../appointments-concurrency.postgres.spec.ts | 5 +-
.../appointments/appointments.service.spec.ts | 96 ++++++++++-
.../appointments/appointments.service.ts | 44 ++---
.../calendly-integration.service.spec.ts | 153 +++++++++++++++++-
.../calendly-integration.service.ts | 95 +++++------
.../dto/calendly-scheduled.dto.spec.ts | 16 ++
.../dto/calendly-scheduled.dto.ts | 6 -
docs/docs/agendamento-sem-calendly.md | 2 +-
frontend/src/services/appointments.service.ts | 1 -
12 files changed, 332 insertions(+), 99 deletions(-)
diff --git a/README.md b/README.md
index 4bcf607..9832327 100644
--- a/README.md
+++ b/README.md
@@ -104,7 +104,7 @@ Além do `DATABASE_URL`, o projeto depende de variáveis importantes para integr
- `DOCUSIGN_INTEGRATION_KEY`, `DOCUSIGN_USER_ID`, `DOCUSIGN_ACCOUNT_ID`, `DOCUSIGN_PRIVATE_KEY`, `DOCUSIGN_ENV`, `DOCUSIGN_WEBHOOK_SECRET`
- `GOOGLE_DRIVE_API_KEY`
- `MEETING_PROVIDER`, `MEETING_DEMO_FALLBACK_ENABLED`, `JITSI_BASE_URL`
-- Calendly OAuth (quando habilitado): `CALENDLY_OAUTH_CLIENT_ID`, `CALENDLY_OAUTH_CLIENT_SECRET`, `CALENDLY_OAUTH_REDIRECT_URI`, `CALENDLY_TOKEN_ENCRYPTION_KEY`, `CALENDLY_WEBHOOK_CALLBACK_URL`, `CALENDLY_WEBHOOK_SIGNING_KEY`
+- Calendly OAuth (quando habilitado): `CALENDLY_OAUTH_CLIENT_ID`, `CALENDLY_OAUTH_CLIENT_SECRET`, `CALENDLY_OAUTH_REDIRECT_URI`, `CALENDLY_TOKEN_ENCRYPTION_KEY`; se `CALENDLY_WEBHOOK_CALLBACK_URL` for configurada, `CALENDLY_WEBHOOK_SIGNING_KEY` é obrigatória
---
diff --git a/backend/.env.example b/backend/.env.example
index 834d437..8117bee 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -52,6 +52,9 @@ BACKEND_URL=http://localhost:3000
# ===== CALENDLY INTEGRATION =====
# Token de acesso do Calendly para agendamentos (opcional)
CALENDLY_ACCESS_TOKEN=your-calendly-access-token
+# Se a URL de callback for configurada, a signing key também é obrigatória.
+CALENDLY_WEBHOOK_CALLBACK_URL=
+CALENDLY_WEBHOOK_SIGNING_KEY=
# ===== GOOGLE DRIVE IMPORT =====
# Chave de API para listar/baixar imagens de pasta pública do Google Drive
diff --git a/backend/README.md b/backend/README.md
index 0fa72cf..62f6c85 100644
--- a/backend/README.md
+++ b/backend/README.md
@@ -75,8 +75,12 @@ cp .env.example .env
- `CALENDLY_OAUTH_CLIENT_SECRET`
- `CALENDLY_OAUTH_REDIRECT_URI`
- `CALENDLY_TOKEN_ENCRYPTION_KEY`
-- `CALENDLY_WEBHOOK_CALLBACK_URL` (recomendado)
-- `CALENDLY_WEBHOOK_SIGNING_KEY` (recomendado)
+- `CALENDLY_WEBHOOK_CALLBACK_URL` (opcional; habilita callbacks)
+- `CALENDLY_WEBHOOK_SIGNING_KEY` (obrigatório quando `CALENDLY_WEBHOOK_CALLBACK_URL` estiver configurado)
+
+O backend não cria assinaturas de webhook sem `CALENDLY_WEBHOOK_SIGNING_KEY` e
+rejeita callbacks quando a chave estiver ausente. A chave enviada ao Calendly
+deve ser a mesma configurada no backend.
> Observação: `CALENDLY_ACCESS_TOKEN` pode existir como fallback simples, mas o fluxo recomendado no projeto atual é OAuth por especialista.
diff --git a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts
index 503ccf5..330d148 100644
--- a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts
+++ b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts
@@ -174,7 +174,9 @@ describeWithPostgres(
? signalScheduleLockAttempt(client, attempted)
: client) as any,
notifications as any,
- {} as any,
+ {
+ resolveScheduledStartTime: jest.fn().mockResolvedValue(proposedDate),
+ } as any,
);
}
@@ -745,7 +747,6 @@ describeWithPostgres(
{
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 ad4dc98..246d0aa 100644
--- a/backend/src/features/appointments/appointments.service.spec.ts
+++ b/backend/src/features/appointments/appointments.service.spec.ts
@@ -2035,7 +2035,16 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
},
$transaction: jest.fn(async (callback: any) => callback(tx)),
} as any;
- const service = new AppointmentsService(prisma, {} as any, {} as any);
+ const calendlyIntegrationService = {
+ resolveScheduledStartTime: jest
+ .fn()
+ .mockResolvedValue(new Date('2099-01-02T11:00:00.000Z')),
+ } as any;
+ const service = new AppointmentsService(
+ prisma,
+ {} as any,
+ calendlyIntegrationService,
+ );
await service.registerCalendlyScheduled(
appointment.id,
@@ -2049,6 +2058,13 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
} as any,
);
+ expect(
+ calendlyIntegrationService.resolveScheduledStartTime,
+ ).toHaveBeenCalledWith(
+ appointment.specialist_id,
+ 'https://api.calendly.com/scheduled_events/event-1',
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
+ );
expect(tx.$queryRaw).toHaveBeenCalledWith(
expect.anything(),
'appointment-schedule:specialist-1',
@@ -2062,11 +2078,83 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
'https://api.calendly.com/scheduled_events/event-1',
calendly_invitee_uri:
'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
+ appointment_datetime: new Date('2099-01-02T11:00:00.000Z'),
}),
}),
);
});
+ it.each([
+ ['retorna null', null],
+ ['falha', new Error('Calendly indisponível')],
+ ])(
+ 'mantém PENDING e não ocupa agenda quando a API canônica %s',
+ async (_label, apiResult) => {
+ 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,
+ calendly_invitee_uri: null,
+ calendly_sync_status: 'PENDING',
+ appointment_datetime: null,
+ };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn().mockResolvedValue(appointment),
+ findFirst: jest.fn(),
+ update: jest.fn().mockImplementation(({ data }) => ({
+ ...appointment,
+ ...data,
+ })),
+ },
+ };
+ const prisma = {
+ appointment: { findUnique: jest.fn().mockResolvedValue(appointment) },
+ $transaction: jest.fn(async (callback: any) => callback(tx)),
+ } as any;
+ const resolveScheduledStartTime =
+ apiResult instanceof Error
+ ? jest.fn().mockRejectedValue(apiResult)
+ : jest.fn().mockResolvedValue(apiResult);
+ const service = new AppointmentsService(prisma, {} as any, {
+ resolveScheduledStartTime,
+ } as any);
+
+ 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',
+ scheduled_start_time: '2099-01-01T10:00:00.000Z',
+ } as any,
+ ),
+ ).resolves.toEqual({
+ appointment_id: appointment.id,
+ calendly_sync_status: 'PENDING',
+ appointment_datetime: null,
+ });
+ expect(resolveScheduledStartTime).toHaveBeenCalledTimes(1);
+ expect(tx.appointment.findFirst).not.toHaveBeenCalled();
+ expect(tx.appointment.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ calendly_sync_status: 'PENDING',
+ appointment_datetime: null,
+ }),
+ }),
+ );
+ },
+ );
+
it('rejects a reschedule that overlaps an already SCHEDULED appointment', async () => {
const appointment = {
id: 'appointment-1',
@@ -2092,7 +2180,11 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
appointment: { findUnique: jest.fn().mockResolvedValue(appointment) },
$transaction: jest.fn(async (callback: any) => callback(tx)),
} as any;
- const service = new AppointmentsService(prisma, {} as any, {} as any);
+ const service = new AppointmentsService(prisma, {} as any, {
+ resolveScheduledStartTime: jest
+ .fn()
+ .mockResolvedValue(new Date('2099-01-01T10:00:00.000Z')),
+ } as any);
await expect(
service.registerCalendlyScheduled(appointment.id, appointment.client_id, {
diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts
index 8a1ddb3..52b3c9b 100644
--- a/backend/src/features/appointments/appointments.service.ts
+++ b/backend/src/features/appointments/appointments.service.ts
@@ -1989,36 +1989,21 @@ export class AppointmentsService {
}
}
- let scheduledStartTime = dto.scheduled_start_time
- ? parseDate(dto.scheduled_start_time)
- : null;
-
- if (dto.scheduled_start_time && !scheduledStartTime) {
- throw new BadRequestException({
- success: false,
- error: {
- code: 400,
- message: 'scheduled_start_time inválido',
- },
- });
- }
-
- if (!scheduledStartTime) {
- try {
- scheduledStartTime =
- await this.calendlyIntegrationService.resolveScheduledStartTime(
- appointment.specialist_id,
- 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}`,
+ let scheduledStartTime: Date | null = null;
+ try {
+ scheduledStartTime =
+ await this.calendlyIntegrationService.resolveScheduledStartTime(
+ appointment.specialist_id,
+ 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}`,
+ );
}
const updated = await this.prisma.$transaction(async (tx) => {
@@ -2100,8 +2085,7 @@ export class AppointmentsService {
return lockedAppointment;
}
- const targetDateTime =
- scheduledStartTime || lockedAppointment.appointment_datetime;
+ const targetDateTime = scheduledStartTime;
if (targetDateTime && !isFutureDate(targetDateTime)) {
throw new BadRequestException(
'O horário sincronizado do Calendly deve ser futuro',
diff --git a/backend/src/features/appointments/calendly-integration.service.spec.ts b/backend/src/features/appointments/calendly-integration.service.spec.ts
index 92d453a..d2464f0 100644
--- a/backend/src/features/appointments/calendly-integration.service.spec.ts
+++ b/backend/src/features/appointments/calendly-integration.service.spec.ts
@@ -1,7 +1,12 @@
-import { ConflictException } from '@nestjs/common';
+import {
+ ConflictException,
+ ForbiddenException,
+ InternalServerErrorException,
+} from '@nestjs/common';
import { AppointmentSchedulingMethod } from '@prisma/client';
import { CalendlyIntegrationService } from './calendly-integration.service';
import axios from 'axios';
+import { createHmac } from 'crypto';
jest.mock('axios');
@@ -15,6 +20,7 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
process.env.CALENDLY_TOKEN_ENCRYPTION_KEY =
'12345678901234567890123456789012';
delete process.env.CALENDLY_WEBHOOK_CALLBACK_URL;
+ delete process.env.CALENDLY_WEBHOOK_SIGNING_KEY;
});
afterAll(() => {
process.env = originalEnv;
@@ -438,7 +444,152 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
});
});
+describe('CalendlyIntegrationService webhook authentication', () => {
+ const originalEnv = { ...process.env };
+ const signingKey = 'calendly-test-signing-key';
+ const nowSeconds = 1_800_000_000;
+ const rawBody = '{"event":"invitee.created"}';
+
+ function makeService() {
+ const prisma = {
+ calendlyConnection: {
+ findUnique: jest.fn(),
+ update: jest.fn(),
+ },
+ };
+ const service = new CalendlyIntegrationService(prisma as any);
+ jest.spyOn(service as any, 'now').mockReturnValue(nowSeconds * 1000);
+ return { prisma, service };
+ }
+
+ function signature(timestamp: string) {
+ const digest = createHmac('sha256', signingKey)
+ .update(`${timestamp}.${rawBody}`)
+ .digest('hex');
+ return `t=${timestamp},v1=${digest}`;
+ }
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ process.env.CALENDLY_WEBHOOK_SIGNING_KEY = signingKey;
+ process.env.CALENDLY_WEBHOOK_CALLBACK_URL =
+ 'https://api.example.test/appointments/calendly/webhook';
+ process.env.CALENDLY_TOKEN_ENCRYPTION_KEY =
+ '12345678901234567890123456789012';
+ });
+
+ afterAll(() => {
+ process.env = originalEnv;
+ });
+
+ it('falha fechado quando a chave de assinatura não está configurada', () => {
+ delete process.env.CALENDLY_WEBHOOK_SIGNING_KEY;
+ const { service } = makeService();
+
+ expect(() =>
+ (service as any).validateWebhookSignature(
+ rawBody,
+ signature(String(nowSeconds)),
+ ),
+ ).toThrow(InternalServerErrorException);
+ });
+
+ it.each([
+ ['não numérico', 'not-a-timestamp'],
+ ['fracionário', `${nowSeconds}.5`],
+ ['antigo', String(nowSeconds - 301)],
+ ['futuro', String(nowSeconds + 301)],
+ ])('rejeita timestamp %s na assinatura', (_label, timestamp) => {
+ const { service } = makeService();
+
+ expect(() =>
+ (service as any).validateWebhookSignature(
+ rawBody,
+ signature(timestamp),
+ ),
+ ).toThrow(ForbiddenException);
+ });
+
+ it('rejeita replay da mesma assinatura dentro da janela válida', () => {
+ const { service } = makeService();
+ const header = signature(String(nowSeconds));
+
+ expect(() =>
+ (service as any).validateWebhookSignature(rawBody, header),
+ ).not.toThrow();
+ expect(() =>
+ (service as any).validateWebhookSignature(rawBody, header),
+ ).toThrow('Webhook repetido');
+ });
+
+ it('não cria assinatura de webhook sem signing key', async () => {
+ delete process.env.CALENDLY_WEBHOOK_SIGNING_KEY;
+ const { prisma, service } = makeService();
+
+ await expect(
+ (service as any).ensureWebhookSubscription('specialist-1'),
+ ).rejects.toThrow(InternalServerErrorException);
+ expect(prisma.calendlyConnection.findUnique).not.toHaveBeenCalled();
+ expect(axios.post).not.toHaveBeenCalled();
+ });
+
+ it('não refaz criação do webhook sem signing_key após rejeição do Calendly', async () => {
+ const { prisma, service } = makeService();
+ const connection = {
+ id: 'connection-1',
+ user_id: 'specialist-1',
+ calendly_user_uri: 'https://api.calendly.com/users/user-1',
+ calendly_organization_uri:
+ 'https://api.calendly.com/organizations/org-1',
+ access_token_encrypted: (service as any).encryptToken('access-token'),
+ };
+ prisma.calendlyConnection.findUnique.mockResolvedValue(connection);
+ jest.mocked(axios.post).mockRejectedValueOnce({ response: { status: 422 } });
+
+ await expect(
+ (service as any).ensureWebhookSubscription('specialist-1'),
+ ).rejects.toBeDefined();
+ expect(axios.post).toHaveBeenCalledTimes(1);
+ expect(axios.post).toHaveBeenCalledWith(
+ 'https://api.calendly.com/webhook_subscriptions',
+ expect.objectContaining({ signing_key: signingKey }),
+ expect.any(Object),
+ );
+ });
+});
+
describe('CalendlyIntegrationService webhook schedule integrity', () => {
+ it('rejeita payload.uri e payload.invitee divergentes', async () => {
+ const prisma = {
+ appointment: { findMany: jest.fn() },
+ $transaction: jest.fn(),
+ };
+ const service = new CalendlyIntegrationService(prisma as any);
+ jest
+ .spyOn(service as any, 'validateWebhookSignature')
+ .mockReturnValue(undefined);
+
+ await expect(
+ service.processWebhook(
+ {
+ event: 'invitee.created',
+ payload: {
+ event:
+ 'https://api.calendly.com/scheduled_events/event-1',
+ uri:
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-official',
+ invitee:
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-legacy',
+ },
+ },
+ undefined,
+ undefined,
+ ),
+ ).rejects.toThrow('URIs de convidado do Calendly são inconsistentes');
+ expect(prisma.appointment.findMany).not.toHaveBeenCalled();
+ expect(prisma.$transaction).not.toHaveBeenCalled();
+ });
+
it.each([
AppointmentSchedulingMethod.EMAIL,
AppointmentSchedulingMethod.PLATFORM,
diff --git a/backend/src/features/appointments/calendly-integration.service.ts b/backend/src/features/appointments/calendly-integration.service.ts
index 86cd521..e7db458 100644
--- a/backend/src/features/appointments/calendly-integration.service.ts
+++ b/backend/src/features/appointments/calendly-integration.service.ts
@@ -68,6 +68,7 @@ interface CalendlyWebhookPayload {
@Injectable()
export class CalendlyIntegrationService {
private readonly logger = new Logger(CalendlyIntegrationService.name);
+ private readonly processedWebhookSignatures = new Map();
constructor(private readonly prisma: PrismaService) {}
@@ -810,7 +811,7 @@ export class CalendlyIntegrationService {
return;
}
- const signingKey = process.env.CALENDLY_WEBHOOK_SIGNING_KEY;
+ const signingKey = this.getRequiredEnv('CALENDLY_WEBHOOK_SIGNING_KEY');
const connection = await this.prisma.calendlyConnection.findUnique({
where: { user_id: userId },
@@ -836,55 +837,20 @@ export class CalendlyIntegrationService {
scope: 'user',
};
- if (signingKey) {
- payload.signing_key = signingKey;
- }
-
- let data: any;
-
- try {
- const response = await axios.post(
- 'https://api.calendly.com/webhook_subscriptions',
- payload,
- {
- headers: {
- Authorization: `Bearer ${accessToken}`,
- 'Content-Type': 'application/json',
- },
- timeout: 20000,
- },
- );
- data = response.data;
- } catch (error: any) {
- const status = error?.response?.status;
- const shouldRetryWithoutSigningKey =
- Boolean(signingKey) && (status === 400 || status === 422);
-
- if (!shouldRetryWithoutSigningKey) {
- throw error;
- }
-
- this.logger.warn(
- 'Calendly rejeitou webhook com signing_key; tentando novamente sem signing_key',
- );
-
- const fallbackPayload = { ...payload };
- delete fallbackPayload.signing_key;
+ payload.signing_key = signingKey;
- const fallbackResponse = await axios.post(
- 'https://api.calendly.com/webhook_subscriptions',
- fallbackPayload,
- {
- headers: {
- Authorization: `Bearer ${accessToken}`,
- 'Content-Type': 'application/json',
- },
- timeout: 20000,
+ const response = await axios.post(
+ 'https://api.calendly.com/webhook_subscriptions',
+ payload,
+ {
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ 'Content-Type': 'application/json',
},
- );
-
- data = fallbackResponse.data;
- }
+ timeout: 20000,
+ },
+ );
+ const data = response.data;
const webhookResource = data?.resource;
@@ -903,11 +869,7 @@ export class CalendlyIntegrationService {
rawBody: string | undefined,
signatureHeader: string | undefined,
): void {
- const signingKey = process.env.CALENDLY_WEBHOOK_SIGNING_KEY;
-
- if (!signingKey) {
- return;
- }
+ const signingKey = this.getRequiredEnv('CALENDLY_WEBHOOK_SIGNING_KEY');
if (!rawBody || !signatureHeader) {
throw new ForbiddenException('Assinatura do webhook ausente');
@@ -918,6 +880,18 @@ export class CalendlyIntegrationService {
throw new ForbiddenException('Formato de assinatura inválido');
}
+ if (!/^\d+$/.test(parsedSignature.t)) {
+ throw new ForbiddenException('Timestamp da assinatura inválido');
+ }
+ const timestampSeconds = Number(parsedSignature.t);
+ const nowSeconds = Math.floor(this.now() / 1000);
+ if (
+ !Number.isSafeInteger(timestampSeconds) ||
+ Math.abs(nowSeconds - timestampSeconds) > 5 * 60
+ ) {
+ throw new ForbiddenException('Timestamp da assinatura expirado');
+ }
+
const signedPayload = `${parsedSignature.t}.${rawBody}`;
const expected = createHmac('sha256', signingKey)
.update(signedPayload)
@@ -932,6 +906,21 @@ export class CalendlyIntegrationService {
) {
throw new ForbiddenException('Assinatura do webhook inválida');
}
+
+ for (const [signature, expiresAt] of this.processedWebhookSignatures) {
+ if (expiresAt <= nowSeconds) {
+ this.processedWebhookSignatures.delete(signature);
+ }
+ }
+ const replayKey = `${parsedSignature.t}.${parsedSignature.v1}`;
+ if (this.processedWebhookSignatures.has(replayKey)) {
+ throw new ForbiddenException('Webhook repetido');
+ }
+ this.processedWebhookSignatures.set(replayKey, nowSeconds + 5 * 60);
+ }
+
+ private now(): number {
+ return Date.now();
}
private parseSignatureHeader(signatureHeader: 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 9568e39..c183fb8 100644
--- a/backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts
+++ b/backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts
@@ -23,6 +23,22 @@ describe('CalendlyScheduledDto — Calendly resource URIs', () => {
await expect(invalidProperties({})).resolves.toEqual([]);
});
+ it('não expõe scheduled_start_time como campo confiável do contrato', async () => {
+ const errors = await validate(
+ plainToInstance(CalendlyScheduledDto, {
+ ...validPayload,
+ scheduled_start_time: '2099-01-01T10:00:00.000Z',
+ }),
+ { whitelist: true, forbidNonWhitelisted: true },
+ );
+
+ expect(errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ property: 'scheduled_start_time' }),
+ ]),
+ );
+ });
+
it('aceita HTTPS com a porta padrão explícita', async () => {
await expect(
invalidProperties({
diff --git a/backend/src/features/appointments/dto/calendly-scheduled.dto.ts b/backend/src/features/appointments/dto/calendly-scheduled.dto.ts
index 8d73a8a..249cd37 100644
--- a/backend/src/features/appointments/dto/calendly-scheduled.dto.ts
+++ b/backend/src/features/appointments/dto/calendly-scheduled.dto.ts
@@ -130,10 +130,4 @@ export class CalendlyScheduledDto {
)
client_observed_at?: string;
- @IsOptional()
- @IsISO8601(
- {},
- { message: 'scheduled_start_time deve estar em formato ISO 8601 válido' },
- )
- scheduled_start_time?: string;
}
diff --git a/docs/docs/agendamento-sem-calendly.md b/docs/docs/agendamento-sem-calendly.md
index 53b1cc9..cb925ca 100644
--- a/docs/docs/agendamento-sem-calendly.md
+++ b/docs/docs/agendamento-sem-calendly.md
@@ -47,7 +47,7 @@ A consulta do próprio pedido retorna somente `{ exists: false }` ou `{ exists:
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.
-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.
+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: o instante é resolvido na API autenticada do Calendly e, enquanto ela não retornar um horário válido, o pedido permanece `PENDING` sem reservar agenda para que o webhook assinado possa completá-lo. Se `CALENDLY_WEBHOOK_CALLBACK_URL` for configurada, `CALENDLY_WEBHOOK_SIGNING_KEY` é obrigatória; callbacks sem assinatura válida e fresca são rejeitados. 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.
## Validação local repetível
diff --git a/frontend/src/services/appointments.service.ts b/frontend/src/services/appointments.service.ts
index b12486f..0e1e157 100644
--- a/frontend/src/services/appointments.service.ts
+++ b/frontend/src/services/appointments.service.ts
@@ -115,7 +115,6 @@ export interface RegisterCalendlyScheduledPayload {
invitee_uri: string;
client_event?: "calendly.event_scheduled";
client_observed_at?: string;
- scheduled_start_time?: string;
}
export interface CalendlySyncStatus {
From 47213b2b8d24bf679e04c5c1ce12a35461942114 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:09:50 -0300
Subject: [PATCH 33/60] fix(processes): gate safe rejection actions
---
.../components/processes/ProcessCard.test.tsx | 110 +++++++++++++++++-
.../src/components/processes/ProcessCard.tsx | 49 +++++---
.../processes/UpdateProcessStatusModal.tsx | 92 ++++++++-------
3 files changed, 187 insertions(+), 64 deletions(-)
diff --git a/frontend/src/components/processes/ProcessCard.test.tsx b/frontend/src/components/processes/ProcessCard.test.tsx
index 3bfa483..e976d45 100644
--- a/frontend/src/components/processes/ProcessCard.test.tsx
+++ b/frontend/src/components/processes/ProcessCard.test.tsx
@@ -356,7 +356,11 @@ describe("ProcessCard appointment time actions", () => {
it("keeps rejection separate from the status selector", () => {
renderCard(
- { ...baseProcess, status: "DOCUMENTATION" },
+ {
+ ...baseProcess,
+ status: "DOCUMENTATION",
+ appointment_status: "COMPLETED",
+ },
{ isExpanded: true },
);
@@ -370,6 +374,110 @@ describe("ProcessCard appointment time actions", () => {
expect(screen.queryByLabelText(/Novo Status/i)).toBeNull();
});
+ it.each(["PENDING", "SCHEDULED"] as const)(
+ "does not offer process rejection while an appointment is %s",
+ (appointment_status) => {
+ renderCard(
+ {
+ ...baseProcess,
+ appointment_status,
+ appointment_datetime: "2099-09-20T17:30:00.000Z",
+ },
+ { isExpanded: true },
+ );
+
+ expect(
+ screen.queryByRole("button", { name: "Recusar processo" }),
+ ).toBeNull();
+ if (appointment_status === "PENDING") {
+ expect(screen.getByRole("button", { name: "Recusar" })).toBeTruthy();
+ }
+ },
+ );
+
+ it("does not offer process rejection while a meeting is active", async () => {
+ vi.mocked(getMeetingByProcess).mockResolvedValue({
+ id: "meeting-active",
+ process_id: baseProcess.id,
+ meet_link: "https://meet.example/active",
+ started_at: "2026-09-16T20:00:00.000Z",
+ ended_at: null,
+ is_active: true,
+ });
+ renderCard(
+ {
+ ...baseProcess,
+ appointment_status: "COMPLETED",
+ appointment_datetime: "2099-09-20T17:30:00.000Z",
+ },
+ { isExpanded: true },
+ );
+
+ await waitFor(() => expect(getMeetingByProcess).toHaveBeenCalledOnce());
+ await waitFor(() =>
+ expect(
+ screen.queryByRole("button", { name: "Recusar processo" }),
+ ).toBeNull(),
+ );
+ });
+
+ it.each([
+ { actor: "specialist", isClientView: false },
+ { actor: "customer", isClientView: true },
+ ])("lets the $actor reject a safe process without expanding the card", ({ isClientView }) => {
+ renderCard(
+ {
+ ...baseProcess,
+ status: "DOCUMENTATION",
+ appointment_status: "COMPLETED",
+ },
+ { isClientView },
+ );
+
+ expect(
+ screen.getByRole("button", { name: "Recusar processo" }),
+ ).toBeTruthy();
+ });
+
+ it("uses the same manual-transition guard for the advance action", () => {
+ renderCard(
+ {
+ ...baseProcess,
+ status: "NEGOTIATION",
+ product_type: null,
+ product_id: null,
+ },
+ { isExpanded: true },
+ );
+
+ expect(
+ screen.queryByRole("button", { name: "Alterar Status" }),
+ ).toBeNull();
+ expect(
+ screen.queryByRole("button", { name: "Avançar processo" }),
+ ).toBeNull();
+ });
+
+ it("opens an announced rejection dialog and restores focus after Escape", async () => {
+ renderCard({
+ ...baseProcess,
+ status: "DOCUMENTATION",
+ appointment_status: "COMPLETED",
+ });
+ const trigger = screen.getByRole("button", { name: "Recusar processo" });
+ trigger.focus();
+ fireEvent.click(trigger);
+
+ const dialog = await screen.findByRole("dialog", {
+ name: "Rejeitar Processo",
+ });
+ expect(within(dialog).getByRole("alert")).toBeTruthy();
+ fireEvent.keyDown(dialog, { key: "Escape" });
+
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ await waitFor(() => expect(document.activeElement).toBe(trigger));
+ });
+
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 48e1c3b..b7fd9f4 100644
--- a/frontend/src/components/processes/ProcessCard.tsx
+++ b/frontend/src/components/processes/ProcessCard.tsx
@@ -108,6 +108,7 @@ export default function ProcessCard({
);
const [isStartingMeeting, setIsStartingMeeting] = useState(false);
const [isLoadingMeeting, setIsLoadingMeeting] = useState(false);
+ const [meetingLookupComplete, setMeetingLookupComplete] = useState(false);
const [isConversationDoneLoading, setIsConversationDoneLoading] =
useState(false);
const [showAdvanceConfirm, setShowAdvanceConfirm] = useState(false);
@@ -122,19 +123,12 @@ export default function ProcessCard({
const [isRescheduling, setIsRescheduling] = useState(false);
const confirmationInFlight = useRef(false);
const dateTimeTriggerRef = useRef(null);
+ const rejectionTriggerRef = useRef(null);
// 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
@@ -157,6 +151,19 @@ export default function ProcessCard({
// Cliente só vê botão se reunião já foi iniciada pelo especialista
const canStartOrJoinMeeting =
isAppointmentConfirmed && process.status === "SCHEDULING";
+ const hasActiveAppointment =
+ process.appointment_status === "PENDING" ||
+ process.appointment_status === "SCHEDULED";
+ const hasActiveMeeting = Boolean(
+ meetingSession && !meetingSession.ended_at && meetingSession.is_active !== false,
+ );
+ const isMeetingStatePending = canStartOrJoinMeeting && !meetingLookupComplete;
+ const canRejectProcess =
+ process.status !== "COMPLETED" &&
+ process.status !== "REJECTED" &&
+ !hasActiveAppointment &&
+ !hasActiveMeeting &&
+ !isMeetingStatePending;
const canSpecialistReschedule =
!isClientView &&
process.status === "SCHEDULING" &&
@@ -186,6 +193,7 @@ export default function ProcessCard({
const loadDetails = async () => {
try {
setIsLoadingMeeting(true);
+ setMeetingLookupComplete(false);
const [reason, processData] = await Promise.all([
getProcessCompletionReason(process.id),
getProcessWithActiveContract(process.id),
@@ -206,6 +214,7 @@ export default function ProcessCard({
console.error("Error loading process details:", error);
} finally {
setIsLoadingMeeting(false);
+ setMeetingLookupComplete(true);
}
};
@@ -473,6 +482,17 @@ export default function ProcessCard({
)}
+ {canRejectProcess && (
+ setShowRejectModal(true)}
+ className="inline-flex shrink-0 items-center gap-1 rounded px-2 py-1 text-xs font-medium text-red-700 transition hover:bg-red-50"
+ >
+
+ Recusar processo
+
+ )}
{onToggleExpand && (
)}
- {canRejectProcess && (
- setShowRejectModal(true)}
- className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 md:px-4 md:py-2 border border-red-300 text-red-700 text-xs md:text-sm font-medium rounded-lg hover:bg-red-50 transition-colors"
- >
-
- Recusar processo
-
- )}
-
{/* Negotiation Button: Only show if status is NEGOTIATION and process has product */}
{process.status === "NEGOTIATION" && !isConsultancy && (
{/* Advance process — specialist only, NEGOTIATION, low prominence */}
- {process.status === "NEGOTIATION" && !isClientView && (
+ {canManuallyAdvanceProcess && (
{!showAdvanceConfirm ? (
{
setShowUpdateModal(false);
setShowRejectModal(false);
diff --git a/frontend/src/components/processes/UpdateProcessStatusModal.tsx b/frontend/src/components/processes/UpdateProcessStatusModal.tsx
index 23748e4..e28aeec 100644
--- a/frontend/src/components/processes/UpdateProcessStatusModal.tsx
+++ b/frontend/src/components/processes/UpdateProcessStatusModal.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useState, type RefObject } from "react";
import { X, AlertTriangle } from "lucide-react";
import { useForm, Controller } from "react-hook-form";
import type { Process } from "../../services/processes.service";
@@ -6,6 +6,8 @@ import {
updateProcessStatus,
rejectProcess,
} from "../../services/processes.service";
+import { Alert } from "../ui/alert";
+import { Dialog, DialogContent } from "../ui/dialog";
interface UpdateProcessStatusModalProps {
isOpen: boolean;
@@ -13,6 +15,7 @@ interface UpdateProcessStatusModalProps {
onSuccess?: () => void;
process: Process;
action?: "status" | "reject";
+ returnFocusRef?: RefObject;
}
interface UpdateProcessFormData {
@@ -29,6 +32,7 @@ export default function UpdateProcessStatusModal({
onSuccess,
process,
action = "status",
+ returnFocusRef,
}: UpdateProcessStatusModalProps) {
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState(null);
@@ -109,26 +113,30 @@ export default function UpdateProcessStatusModal({
if (action === "reject") {
return (
- {
+ if (!nextOpen && !isSubmitting) handleRejectCancel();
+ }}
>
-
event.stopPropagation()}
+
{
+ event.preventDefault();
+ returnFocusRef?.current?.focus();
+ }}
+ className="max-w-md"
>
-
-
-
- Rejeitar Processo
-
-
-
-
-
- Tem certeza que deseja rejeitar este processo? Esta ação não pode
- ser desfeita.
-
+
+
+
+
+ Tem certeza que deseja rejeitar este processo? Esta ação não
+ pode ser desfeita.
+
+
- {error && (
-
- )}
-
+ {error &&
{error} }
-
-
- Cancelar
-
-
- {isSubmitting ? "Rejeitando..." : "Confirmar Rejeição"}
-
+
+
+ Cancelar
+
+
+ {isSubmitting ? "Rejeitando..." : "Confirmar Rejeição"}
+
+
-
-
+
+
);
}
From a3e3a83a163ef8d1d6a463fda43bfb5917db7d88 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:10:11 -0300
Subject: [PATCH 34/60] fix(processes): block rejection with active scheduling
---
.../processes/processes.service.spec.ts | 123 +++++++++++++++++-
.../features/processes/processes.service.ts | 25 ++++
2 files changed, 147 insertions(+), 1 deletion(-)
diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts
index b213296..08345af 100644
--- a/backend/src/features/processes/processes.service.spec.ts
+++ b/backend/src/features/processes/processes.service.spec.ts
@@ -1983,6 +1983,8 @@ describe('ProcessesService — autorização centralizada de processos', () => {
car: null,
boat: null,
aircraft: null,
+ appointment: null,
+ meeting_session: null,
...overrides,
};
}
@@ -2273,7 +2275,104 @@ describe('ProcessesService — autorização centralizada de processos', () => {
expect(tx.$queryRaw).not.toHaveBeenCalled();
});
- it('cliente pode rejeitar o próprio processo ativo', async () => {
+ it.each([
+ [
+ 'cliente',
+ StatusAgendamento.PENDING,
+ ownerClientId,
+ UserRole.CUSTOMER,
+ 'Cancele o agendamento pelo fluxo próprio',
+ ],
+ [
+ 'especialista',
+ StatusAgendamento.PENDING,
+ assignedSpecialistId,
+ UserRole.SPECIALIST,
+ 'Cancele o agendamento pelo fluxo próprio',
+ ],
+ [
+ 'cliente',
+ StatusAgendamento.SCHEDULED,
+ ownerClientId,
+ UserRole.CUSTOMER,
+ 'Cancele o agendamento pelo fluxo próprio',
+ ],
+ [
+ 'especialista',
+ StatusAgendamento.SCHEDULED,
+ assignedSpecialistId,
+ UserRole.SPECIALIST,
+ 'Cancele o agendamento pelo fluxo próprio',
+ ],
+ [
+ 'cliente',
+ StatusAgendamento.COMPLETED,
+ ownerClientId,
+ UserRole.CUSTOMER,
+ 'Processo com agendamento concluído',
+ ],
+ [
+ 'especialista',
+ StatusAgendamento.COMPLETED,
+ assignedSpecialistId,
+ UserRole.SPECIALIST,
+ 'Processo com agendamento concluído',
+ ],
+ ])(
+ '%s não rejeita processo com appointment %s',
+ async (_label, appointmentStatus, actorId, actorRole, expectedMessage) => {
+ const { service, processUpdateMany, historyCreate, rejectionCreate, tx } =
+ rejectionService(
+ protectedProcess({
+ appointment: { status: appointmentStatus },
+ }),
+ );
+
+ await expect(
+ service.rejectProcess(
+ '99999999-9999-4999-8999-999999999999',
+ actorId,
+ undefined,
+ actorRole,
+ ),
+ ).rejects.toThrow(expectedMessage);
+
+ expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
+ expect(processUpdateMany).not.toHaveBeenCalled();
+ expect(historyCreate).not.toHaveBeenCalled();
+ expect(rejectionCreate).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ ['cliente', ownerClientId, UserRole.CUSTOMER],
+ ['especialista', assignedSpecialistId, UserRole.SPECIALIST],
+ ])(
+ '%s não rejeita processo com reunião ativa',
+ async (_label, actorId, actorRole) => {
+ const { service, processUpdateMany, historyCreate, rejectionCreate } =
+ rejectionService(
+ protectedProcess({
+ meeting_session: { ended_at: null },
+ }),
+ );
+
+ await expect(
+ service.rejectProcess(
+ '99999999-9999-4999-8999-999999999999',
+ actorId,
+ undefined,
+ actorRole,
+ ),
+ ).rejects.toThrow(BadRequestException);
+
+ expect(processUpdateMany).not.toHaveBeenCalled();
+ expect(historyCreate).not.toHaveBeenCalled();
+ expect(rejectionCreate).not.toHaveBeenCalled();
+ },
+ );
+
+ it('cliente pode rejeitar o próprio processo sem appointment', async () => {
const { service, processUpdate, processUpdateMany, tx } =
rejectionService();
@@ -2303,6 +2402,28 @@ describe('ProcessesService — autorização centralizada de processos', () => {
expect(processUpdate).not.toHaveBeenCalled();
});
+ it('especialista pode rejeitar processo com appointment cancelado e reunião encerrada', async () => {
+ const { service, processUpdateMany } = rejectionService(
+ protectedProcess({
+ appointment: { status: StatusAgendamento.CANCELLED },
+ meeting_session: { ended_at: new Date('2026-01-01T12:00:00.000Z') },
+ }),
+ );
+
+ await expect(
+ service.rejectProcess(
+ '99999999-9999-4999-8999-999999999999',
+ assignedSpecialistId,
+ undefined,
+ UserRole.SPECIALIST,
+ ),
+ ).resolves.toEqual(
+ expect.objectContaining({ status: ProcessStatus.REJECTED }),
+ );
+
+ expect(processUpdateMany).toHaveBeenCalledTimes(1);
+ });
+
it('rejeição perde a CAS sem criar histórico nem motivo', async () => {
const { service, historyCreate, rejectionCreate, processUpdateMany } =
rejectionService(protectedProcess(), 0);
diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts
index e6e7715..ed095ac 100644
--- a/backend/src/features/processes/processes.service.ts
+++ b/backend/src/features/processes/processes.service.ts
@@ -2034,6 +2034,8 @@ export class ProcessesService {
car: true,
boat: true,
aircraft: true,
+ appointment: { select: { status: true } },
+ meeting_session: { select: { ended_at: true } },
},
});
@@ -2056,6 +2058,29 @@ export class ProcessesService {
'Processo concluído não pode ser rejeitado',
);
}
+ if (
+ existingProcess.appointment &&
+ existingProcess.appointment.status !== StatusAgendamento.CANCELLED
+ ) {
+ const appointmentCanBeCancelled =
+ existingProcess.appointment.status ===
+ StatusAgendamento.PENDING ||
+ existingProcess.appointment.status ===
+ StatusAgendamento.SCHEDULED;
+ throw new BadRequestException(
+ appointmentCanBeCancelled
+ ? 'Cancele o agendamento pelo fluxo próprio antes de rejeitar o processo'
+ : 'Processo com agendamento concluído não pode ser rejeitado por esta rota',
+ );
+ }
+ if (
+ existingProcess.meeting_session &&
+ !existingProcess.meeting_session.ended_at
+ ) {
+ throw new BadRequestException(
+ 'Encerre a reunião antes de rejeitar o processo',
+ );
+ }
const rejectedAt = new Date();
const claim = await tx.process.updateMany({
From 17b4975a1dc9a985dc92ae555cf93f75bcad78c5 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:14:55 -0300
Subject: [PATCH 35/60] fix(processes): fail closed on meeting lookup
---
.../components/processes/ProcessCard.test.tsx | 149 +++++++++++++++++-
.../src/components/processes/ProcessCard.tsx | 105 ++++++++----
.../processes/UpdateProcessStatusModal.tsx | 7 +-
3 files changed, 221 insertions(+), 40 deletions(-)
diff --git a/frontend/src/components/processes/ProcessCard.test.tsx b/frontend/src/components/processes/ProcessCard.test.tsx
index e976d45..0df3035 100644
--- a/frontend/src/components/processes/ProcessCard.test.tsx
+++ b/frontend/src/components/processes/ProcessCard.test.tsx
@@ -65,6 +65,16 @@ function renderCard(
);
}
+function deferred() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise((onResolve, onReject) => {
+ resolve = onResolve;
+ reject = onReject;
+ });
+ return { promise, resolve, reject };
+}
+
describe("ProcessCard appointment time actions", () => {
beforeEach(() => {
vi.mocked(getProcessCompletionReason).mockResolvedValue(null);
@@ -354,7 +364,7 @@ describe("ProcessCard appointment time actions", () => {
},
);
- it("keeps rejection separate from the status selector", () => {
+ it("keeps rejection separate from the status selector", async () => {
renderCard(
{
...baseProcess,
@@ -368,7 +378,7 @@ describe("ProcessCard appointment time actions", () => {
screen.queryByRole("button", { name: "Alterar Status" }),
).toBeNull();
fireEvent.click(
- screen.getByRole("button", { name: "Recusar processo" }),
+ await screen.findByRole("button", { name: "Recusar processo" }),
);
expect(screen.getByText("Rejeitar Processo")).toBeTruthy();
expect(screen.queryByLabelText(/Novo Status/i)).toBeNull();
@@ -424,7 +434,7 @@ describe("ProcessCard appointment time actions", () => {
it.each([
{ actor: "specialist", isClientView: false },
{ actor: "customer", isClientView: true },
- ])("lets the $actor reject a safe process without expanding the card", ({ isClientView }) => {
+ ])("lets the $actor reject a safe process without expanding the card", async ({ isClientView }) => {
renderCard(
{
...baseProcess,
@@ -435,7 +445,66 @@ describe("ProcessCard appointment time actions", () => {
);
expect(
- screen.getByRole("button", { name: "Recusar processo" }),
+ await screen.findByRole("button", { name: "Recusar processo" }),
+ ).toBeTruthy();
+ });
+
+ it.each([null, "CANCELLED", "COMPLETED"] as const)(
+ "keeps rejection fail-closed until meeting lookup completes for appointment %s",
+ async (appointment_status) => {
+ const lookup = deferred();
+ vi.mocked(getMeetingByProcess).mockReturnValue(lookup.promise);
+ renderCard({
+ ...baseProcess,
+ status: "DOCUMENTATION",
+ appointment_status,
+ });
+
+ expect(getMeetingByProcess).toHaveBeenCalledWith(baseProcess.id);
+ expect(
+ screen.queryByRole("button", { name: "Recusar processo" }),
+ ).toBeNull();
+
+ lookup.resolve(null);
+ expect(
+ await screen.findByRole("button", { name: "Recusar processo" }),
+ ).toBeTruthy();
+ },
+ );
+
+ it("keeps rejection fail-closed when meeting lookup fails", async () => {
+ vi.mocked(getMeetingByProcess).mockRejectedValue(
+ new Error("meeting lookup unavailable"),
+ );
+ renderCard({
+ ...baseProcess,
+ status: "DOCUMENTATION",
+ appointment_status: "COMPLETED",
+ });
+
+ await waitFor(() => expect(getMeetingByProcess).toHaveBeenCalledOnce());
+ expect(
+ screen.queryByRole("button", { name: "Recusar processo" }),
+ ).toBeNull();
+ });
+
+ it("allows rejection after the meeting is known to be ended", async () => {
+ vi.mocked(getMeetingByProcess).mockResolvedValue({
+ id: "meeting-ended",
+ process_id: baseProcess.id,
+ meet_link: "https://meet.example/ended",
+ started_at: "2026-09-16T20:00:00.000Z",
+ ended_at: "2026-09-16T21:00:00.000Z",
+ is_active: false,
+ });
+ renderCard({
+ ...baseProcess,
+ status: "DOCUMENTATION",
+ appointment_status: "COMPLETED",
+ });
+
+ expect(
+ await screen.findByRole("button", { name: "Recusar processo" }),
).toBeTruthy();
});
@@ -464,7 +533,9 @@ describe("ProcessCard appointment time actions", () => {
status: "DOCUMENTATION",
appointment_status: "COMPLETED",
});
- const trigger = screen.getByRole("button", { name: "Recusar processo" });
+ const trigger = await screen.findByRole("button", {
+ name: "Recusar processo",
+ });
trigger.focus();
fireEvent.click(trigger);
@@ -478,6 +549,74 @@ describe("ProcessCard appointment time actions", () => {
await waitFor(() => expect(document.activeElement).toBe(trigger));
});
+ it("submits the rejection reason once while busy and reports success", async () => {
+ const request = deferred>>();
+ const onStatusUpdated = vi.fn();
+ vi.mocked(rejectProcess).mockReturnValue(request.promise);
+ renderCard(
+ {
+ ...baseProcess,
+ status: "DOCUMENTATION",
+ appointment_status: "COMPLETED",
+ },
+ { onStatusUpdated },
+ );
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Recusar processo" }),
+ );
+ fireEvent.change(screen.getByLabelText(/Motivo da Rejeição/i), {
+ target: { value: "Cliente desistiu" },
+ });
+ const submit = screen.getByRole("button", {
+ name: "Confirmar Rejeição",
+ });
+ fireEvent.click(submit);
+ fireEvent.click(submit);
+
+ expect(rejectProcess).toHaveBeenCalledOnce();
+ expect(rejectProcess).toHaveBeenCalledWith(
+ baseProcess.id,
+ "Cliente desistiu",
+ );
+ expect((screen.getByLabelText(/Motivo da Rejeição/i) as HTMLTextAreaElement).disabled).toBe(true);
+ expect(onStatusUpdated).not.toHaveBeenCalled();
+
+ await act(async () => request.resolve({} as Process));
+ await waitFor(() => expect(onStatusUpdated).toHaveBeenCalledOnce());
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+
+ it("keeps a rejection error inline without reporting success", async () => {
+ const onStatusUpdated = vi.fn();
+ vi.mocked(rejectProcess).mockRejectedValue(
+ new Error("Não foi possível recusar agora."),
+ );
+ renderCard(
+ {
+ ...baseProcess,
+ status: "DOCUMENTATION",
+ appointment_status: "CANCELLED",
+ },
+ { onStatusUpdated },
+ );
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Recusar processo" }),
+ );
+ fireEvent.click(
+ screen.getByRole("button", { name: "Confirmar Rejeição" }),
+ );
+
+ expect(
+ await screen.findByText("Não foi possível recusar agora."),
+ ).toBeTruthy();
+ expect(
+ within(screen.getByRole("dialog")).getAllByRole("alert"),
+ ).toHaveLength(2);
+ expect(onStatusUpdated).not.toHaveBeenCalled();
+ });
+
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 b7fd9f4..05e0604 100644
--- a/frontend/src/components/processes/ProcessCard.tsx
+++ b/frontend/src/components/processes/ProcessCard.tsx
@@ -108,7 +108,11 @@ export default function ProcessCard({
);
const [isStartingMeeting, setIsStartingMeeting] = useState(false);
const [isLoadingMeeting, setIsLoadingMeeting] = useState(false);
- const [meetingLookupComplete, setMeetingLookupComplete] = useState(false);
+ const [meetingLookupState, setMeetingLookupState] = useState<
+ "idle" | "loading" | "ready" | "error"
+ >("idle");
+ const [meetingVerifiedProcess, setMeetingVerifiedProcess] =
+ useState(null);
const [isConversationDoneLoading, setIsConversationDoneLoading] =
useState(false);
const [showAdvanceConfirm, setShowAdvanceConfirm] = useState(false);
@@ -157,13 +161,16 @@ export default function ProcessCard({
const hasActiveMeeting = Boolean(
meetingSession && !meetingSession.ended_at && meetingSession.is_active !== false,
);
- const isMeetingStatePending = canStartOrJoinMeeting && !meetingLookupComplete;
+ const isNonTerminalProcess =
+ process.status !== "COMPLETED" && process.status !== "REJECTED";
+ const shouldLookupMeeting =
+ canStartOrJoinMeeting || (isNonTerminalProcess && !hasActiveAppointment);
const canRejectProcess =
- process.status !== "COMPLETED" &&
- process.status !== "REJECTED" &&
+ isNonTerminalProcess &&
!hasActiveAppointment &&
!hasActiveMeeting &&
- !isMeetingStatePending;
+ meetingLookupState === "ready" &&
+ meetingVerifiedProcess === process;
const canSpecialistReschedule =
!isClientView &&
process.status === "SCHEDULING" &&
@@ -188,38 +195,68 @@ export default function ProcessCard({
})
: null;
- // Load completion reason and active contract on mount and when process changes
+ // These projections are independent: a failure in one must not suppress the
+ // others (especially the meeting gate used by rejection).
useEffect(() => {
- const loadDetails = async () => {
- try {
- setIsLoadingMeeting(true);
- setMeetingLookupComplete(false);
- const [reason, processData] = await Promise.all([
- getProcessCompletionReason(process.id),
- getProcessWithActiveContract(process.id),
- ]);
- setCompletionReason(reason);
- setActiveContract(processData.activeContract);
- console.log(processData);
-
- const shouldCheckMeeting = canStartOrJoinMeeting;
-
- if (shouldCheckMeeting) {
- const meeting = await getMeetingByProcess(process.id);
- setMeetingSession(meeting);
- } else {
- setMeetingSession(null);
- }
- } catch (error) {
- console.error("Error loading process details:", error);
- } finally {
- setIsLoadingMeeting(false);
- setMeetingLookupComplete(true);
- }
+ let current = true;
+
+ void getProcessCompletionReason(process.id)
+ .then((reason) => {
+ if (current) setCompletionReason(reason);
+ })
+ .catch((error) => console.error("Error loading completion reason:", error));
+
+ void getProcessWithActiveContract(process.id)
+ .then((processData) => {
+ if (current) setActiveContract(processData.activeContract);
+ })
+ .catch((error) => console.error("Error loading active contract:", error));
+
+ return () => {
+ current = false;
};
+ }, [process]);
+
+ useEffect(() => {
+ let current = true;
- loadDetails();
- }, [process, canStartOrJoinMeeting]);
+ if (!shouldLookupMeeting) {
+ setMeetingSession(null);
+ setMeetingLookupState("idle");
+ setMeetingVerifiedProcess(null);
+ setIsLoadingMeeting(false);
+ return () => {
+ current = false;
+ };
+ }
+
+ setMeetingSession(null);
+ setMeetingLookupState("loading");
+ setMeetingVerifiedProcess(null);
+ setIsLoadingMeeting(true);
+
+ void getMeetingByProcess(process.id)
+ .then((meeting) => {
+ if (!current) return;
+ setMeetingSession(meeting);
+ setMeetingLookupState("ready");
+ setMeetingVerifiedProcess(process);
+ })
+ .catch((error) => {
+ if (!current) return;
+ setMeetingSession(null);
+ setMeetingLookupState("error");
+ setMeetingVerifiedProcess(null);
+ console.error("Error loading meeting:", error);
+ })
+ .finally(() => {
+ if (current) setIsLoadingMeeting(false);
+ });
+
+ return () => {
+ current = false;
+ };
+ }, [process, shouldLookupMeeting]);
const handleStartMeeting = async () => {
if (isStartingMeeting) return;
diff --git a/frontend/src/components/processes/UpdateProcessStatusModal.tsx b/frontend/src/components/processes/UpdateProcessStatusModal.tsx
index e28aeec..7d1c033 100644
--- a/frontend/src/components/processes/UpdateProcessStatusModal.tsx
+++ b/frontend/src/components/processes/UpdateProcessStatusModal.tsx
@@ -1,4 +1,4 @@
-import { useState, type RefObject } from "react";
+import { useRef, useState, type RefObject } from "react";
import { X, AlertTriangle } from "lucide-react";
import { useForm, Controller } from "react-hook-form";
import type { Process } from "../../services/processes.service";
@@ -37,6 +37,7 @@ export default function UpdateProcessStatusModal({
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState(null);
const [rejectionReason, setRejectionReason] = useState("");
+ const rejectionInFlight = useRef(false);
const {
control,
@@ -77,6 +78,9 @@ export default function UpdateProcessStatusModal({
};
const handleRejectConfirm = async () => {
+ if (rejectionInFlight.current) return;
+ rejectionInFlight.current = true;
+
try {
setIsSubmitting(true);
setError(null);
@@ -92,6 +96,7 @@ export default function UpdateProcessStatusModal({
err instanceof Error ? err.message : "Erro ao rejeitar processo"
);
} finally {
+ rejectionInFlight.current = false;
setIsSubmitting(false);
}
};
From d2f6b1de7140fcf94eccd4bd73877dc0843e1b30 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:15:30 -0300
Subject: [PATCH 36/60] fix(appointments): preserve Calendly retry state
---
backend/README.md | 5 +-
.../appointments/appointments.service.spec.ts | 120 ++++++++++++++++++
.../appointments/appointments.service.ts | 42 +++---
.../calendly-integration.service.spec.ts | 50 +++++++-
.../calendly-integration.service.ts | 16 +--
5 files changed, 195 insertions(+), 38 deletions(-)
diff --git a/backend/README.md b/backend/README.md
index 62f6c85..2a77adc 100644
--- a/backend/README.md
+++ b/backend/README.md
@@ -79,8 +79,9 @@ cp .env.example .env
- `CALENDLY_WEBHOOK_SIGNING_KEY` (obrigatório quando `CALENDLY_WEBHOOK_CALLBACK_URL` estiver configurado)
O backend não cria assinaturas de webhook sem `CALENDLY_WEBHOOK_SIGNING_KEY` e
-rejeita callbacks quando a chave estiver ausente. A chave enviada ao Calendly
-deve ser a mesma configurada no backend.
+rejeita callbacks quando a chave estiver ausente. A chave gerada pelo Calendly
+na criação do aplicativo OAuth deve ser copiada para o backend. Ela valida os
+callbacks localmente e não é reenviada no payload da subscription OAuth.
> Observação: `CALENDLY_ACCESS_TOKEN` pode existir como fallback simples, mas o fluxo recomendado no projeto atual é OAuth por especialista.
diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts
index 246d0aa..c11f955 100644
--- a/backend/src/features/appointments/appointments.service.spec.ts
+++ b/backend/src/features/appointments/appointments.service.spec.ts
@@ -1849,6 +1849,64 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
expect(prisma.$transaction).not.toHaveBeenCalled();
});
+ it('reconsulta o Calendly ao repetir a mesma associação ainda PENDING e promove para SYNCED', async () => {
+ const resolvedDate = new Date('2099-01-03T14:00:00.000Z');
+ 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:
+ 'https://api.calendly.com/scheduled_events/event-1',
+ calendly_invitee_uri:
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
+ calendly_sync_status: 'PENDING',
+ appointment_datetime: null,
+ };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn().mockResolvedValue(appointment),
+ findFirst: jest.fn().mockResolvedValue(null),
+ update: jest.fn().mockImplementation(({ data }) => ({
+ ...appointment,
+ ...data,
+ })),
+ },
+ };
+ const prisma = {
+ appointment: { findUnique: jest.fn().mockResolvedValue(appointment) },
+ $transaction: jest.fn(async (callback: any) => callback(tx)),
+ } as any;
+ const resolveScheduledStartTime = jest.fn().mockResolvedValue(resolvedDate);
+ const service = new AppointmentsService(prisma, {} as any, {
+ resolveScheduledStartTime,
+ } as any);
+
+ await expect(
+ service.registerCalendlyScheduled(appointment.id, appointment.client_id, {
+ event_uri: appointment.calendly_event_uri,
+ invitee_uri: appointment.calendly_invitee_uri,
+ }),
+ ).resolves.toEqual({
+ appointment_id: appointment.id,
+ calendly_sync_status: 'SYNCED',
+ appointment_datetime: resolvedDate,
+ });
+ expect(resolveScheduledStartTime).toHaveBeenCalledTimes(1);
+ expect(tx.appointment.findFirst).toHaveBeenCalledTimes(1);
+ expect(tx.appointment.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ calendly_sync_status: 'SYNCED',
+ appointment_datetime: resolvedDate,
+ }),
+ }),
+ );
+ });
+
it('rejeita o mesmo evento quando já está associado a outro convidado', async () => {
const appointment = {
id: 'appointment-1',
@@ -2155,6 +2213,68 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
},
);
+ it.each([
+ ['retorna null', null],
+ ['falha', new Error('Calendly indisponível')],
+ ])(
+ 'preserva associação e horário confiáveis quando novas URIs chegam e a API %s',
+ async (_label, apiResult) => {
+ const trustedDate = new Date('2099-01-01T10:00:00.000Z');
+ 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://api.calendly.com/scheduled_events/trusted-event',
+ calendly_invitee_uri:
+ 'https://api.calendly.com/scheduled_events/trusted-event/invitees/trusted-invitee',
+ calendly_sync_status: 'SYNCED',
+ appointment_datetime: trustedDate,
+ };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn().mockResolvedValue(appointment),
+ update: jest.fn(),
+ },
+ };
+ const prisma = {
+ appointment: { findUnique: jest.fn().mockResolvedValue(appointment) },
+ $transaction: jest.fn(async (callback: any) => callback(tx)),
+ } as any;
+ const resolveScheduledStartTime =
+ apiResult instanceof Error
+ ? jest.fn().mockRejectedValue(apiResult)
+ : jest.fn().mockResolvedValue(apiResult);
+ const service = new AppointmentsService(prisma, {} as any, {
+ resolveScheduledStartTime,
+ } as any);
+
+ await expect(
+ service.registerCalendlyScheduled(
+ appointment.id,
+ appointment.client_id,
+ {
+ event_uri:
+ 'https://api.calendly.com/scheduled_events/unverified-event',
+ invitee_uri:
+ 'https://api.calendly.com/scheduled_events/unverified-event/invitees/unverified-invitee',
+ },
+ ),
+ ).resolves.toEqual({
+ appointment_id: appointment.id,
+ calendly_sync_status: 'SYNCED',
+ appointment_datetime: trustedDate,
+ });
+ expect(resolveScheduledStartTime).toHaveBeenCalledTimes(1);
+ expect(prisma.$transaction).toHaveBeenCalledTimes(1);
+ expect(tx.appointment.update).not.toHaveBeenCalled();
+ },
+ );
+
it('rejects a reschedule that overlaps an already SCHEDULED appointment', async () => {
const appointment = {
id: 'appointment-1',
diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts
index 52b3c9b..6826acb 100644
--- a/backend/src/features/appointments/appointments.service.ts
+++ b/backend/src/features/appointments/appointments.service.ts
@@ -1981,11 +1981,13 @@ export class AppointmentsService {
canonicalized = repair.count === 1;
}
if (canonicalized) {
- return {
- appointment_id: appointment.id,
- calendly_sync_status: appointment.calendly_sync_status,
- appointment_datetime: appointment.appointment_datetime,
- };
+ if (this.hasTrustedCalendlySchedule(appointment)) {
+ return {
+ appointment_id: appointment.id,
+ calendly_sync_status: appointment.calendly_sync_status,
+ appointment_datetime: appointment.appointment_datetime,
+ };
+ }
}
}
@@ -2070,18 +2072,12 @@ export class AppointmentsService {
'O evento do Calendly já está associado a outro convidado',
);
}
- 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,
- },
- });
- }
+ }
+
+ if (
+ !scheduledStartTime &&
+ this.hasTrustedCalendlySchedule(lockedAppointment)
+ ) {
return lockedAppointment;
}
@@ -2122,6 +2118,18 @@ export class AppointmentsService {
};
}
+ private hasTrustedCalendlySchedule(appointment: {
+ status: StatusAgendamento;
+ calendly_sync_status?: CalendlySyncStatus | null;
+ appointment_datetime?: Date | null;
+ }): boolean {
+ return (
+ appointment.status === StatusAgendamento.SCHEDULED ||
+ (appointment.calendly_sync_status === CalendlySyncStatus.SYNCED &&
+ Boolean(appointment.appointment_datetime))
+ );
+ }
+
async getCalendlySyncStatus(
appointmentId: string,
userId: string,
diff --git a/backend/src/features/appointments/calendly-integration.service.spec.ts b/backend/src/features/appointments/calendly-integration.service.spec.ts
index d2464f0..1966500 100644
--- a/backend/src/features/appointments/calendly-integration.service.spec.ts
+++ b/backend/src/features/appointments/calendly-integration.service.spec.ts
@@ -108,6 +108,47 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
expect(prisma.calendlyOauthState.update).not.toHaveBeenCalled();
});
+ it('mantém a conexão OAuth explícita sem gravar subscription quando sua criação falha', async () => {
+ process.env.CALENDLY_WEBHOOK_CALLBACK_URL =
+ 'https://api.example.test/appointments/calendly/webhook';
+ process.env.CALENDLY_WEBHOOK_SIGNING_KEY = 'local-oauth-signing-key';
+ const { prisma, service } = makeCallbackService(
+ 'https://calendly.com/ana/reuniao',
+ );
+ const connection = {
+ id: 'connection-1',
+ user_id: 'specialist-1',
+ access_token_encrypted: (service as any).encryptToken('access'),
+ calendly_user_uri: 'https://api.calendly.com/users/1',
+ calendly_organization_uri:
+ 'https://api.calendly.com/organizations/1',
+ };
+ prisma.calendlyConnection.upsert.mockResolvedValue(connection);
+ Object.assign(prisma.calendlyConnection, {
+ findUnique: jest.fn().mockResolvedValue(connection),
+ update: jest.fn(),
+ });
+ jest
+ .mocked(axios.post)
+ .mockResolvedValueOnce({
+ data: {
+ access_token: 'access',
+ refresh_token: 'refresh',
+ expires_in: 3600,
+ },
+ })
+ .mockRejectedValueOnce(new Error('subscription unavailable'));
+
+ await expect(
+ service.handleOAuthCallback('code', 'state'),
+ ).resolves.toBe('specialist-1');
+ expect(prisma.user.update).toHaveBeenCalledTimes(1);
+ expect(prisma.calendlyOauthState.update).toHaveBeenCalledTimes(1);
+ expect(
+ (prisma.calendlyConnection as any).update,
+ ).not.toHaveBeenCalled();
+ });
+
it('desativa e limpa URL e URIs em uma transação', async () => {
const tx = {
calendlyConnection: {
@@ -510,7 +551,7 @@ describe('CalendlyIntegrationService webhook authentication', () => {
).toThrow(ForbiddenException);
});
- it('rejeita replay da mesma assinatura dentro da janela válida', () => {
+ it('aceita retry idêntico dentro da janela válida para permitir retentativa do Calendly', () => {
const { service } = makeService();
const header = signature(String(nowSeconds));
@@ -519,7 +560,7 @@ describe('CalendlyIntegrationService webhook authentication', () => {
).not.toThrow();
expect(() =>
(service as any).validateWebhookSignature(rawBody, header),
- ).toThrow('Webhook repetido');
+ ).not.toThrow();
});
it('não cria assinatura de webhook sem signing key', async () => {
@@ -533,7 +574,7 @@ describe('CalendlyIntegrationService webhook authentication', () => {
expect(axios.post).not.toHaveBeenCalled();
});
- it('não refaz criação do webhook sem signing_key após rejeição do Calendly', async () => {
+ it('não envia a chave local na criação de subscription OAuth nem mascara falhas', async () => {
const { prisma, service } = makeService();
const connection = {
id: 'connection-1',
@@ -552,9 +593,10 @@ describe('CalendlyIntegrationService webhook authentication', () => {
expect(axios.post).toHaveBeenCalledTimes(1);
expect(axios.post).toHaveBeenCalledWith(
'https://api.calendly.com/webhook_subscriptions',
- expect.objectContaining({ signing_key: signingKey }),
+ expect.not.objectContaining({ signing_key: expect.anything() }),
expect.any(Object),
);
+ expect(prisma.calendlyConnection.update).not.toHaveBeenCalled();
});
});
diff --git a/backend/src/features/appointments/calendly-integration.service.ts b/backend/src/features/appointments/calendly-integration.service.ts
index e7db458..32b1a29 100644
--- a/backend/src/features/appointments/calendly-integration.service.ts
+++ b/backend/src/features/appointments/calendly-integration.service.ts
@@ -68,7 +68,6 @@ interface CalendlyWebhookPayload {
@Injectable()
export class CalendlyIntegrationService {
private readonly logger = new Logger(CalendlyIntegrationService.name);
- private readonly processedWebhookSignatures = new Map();
constructor(private readonly prisma: PrismaService) {}
@@ -811,7 +810,7 @@ export class CalendlyIntegrationService {
return;
}
- const signingKey = this.getRequiredEnv('CALENDLY_WEBHOOK_SIGNING_KEY');
+ this.getRequiredEnv('CALENDLY_WEBHOOK_SIGNING_KEY');
const connection = await this.prisma.calendlyConnection.findUnique({
where: { user_id: userId },
@@ -837,8 +836,6 @@ export class CalendlyIntegrationService {
scope: 'user',
};
- payload.signing_key = signingKey;
-
const response = await axios.post(
'https://api.calendly.com/webhook_subscriptions',
payload,
@@ -906,17 +903,6 @@ export class CalendlyIntegrationService {
) {
throw new ForbiddenException('Assinatura do webhook inválida');
}
-
- for (const [signature, expiresAt] of this.processedWebhookSignatures) {
- if (expiresAt <= nowSeconds) {
- this.processedWebhookSignatures.delete(signature);
- }
- }
- const replayKey = `${parsedSignature.t}.${parsedSignature.v1}`;
- if (this.processedWebhookSignatures.has(replayKey)) {
- throw new ForbiddenException('Webhook repetido');
- }
- this.processedWebhookSignatures.set(replayKey, nowSeconds + 5 * 60);
}
private now(): number {
From 8fde09739a898dbfad6c56c10f71f75f2e0e1084 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:16:20 -0300
Subject: [PATCH 37/60] fix(meetings): serialize meeting start with rejection
---
.../meetings/meetings.service.spec.ts | 139 ++++++++-
.../src/features/meetings/meetings.service.ts | 266 +++++++++---------
...ses-rejection-concurrency.postgres.spec.ts | 180 ++++++++++++
.../processes/processes.service.spec.ts | 131 +++++++--
.../features/processes/processes.service.ts | 37 ++-
5 files changed, 583 insertions(+), 170 deletions(-)
diff --git a/backend/src/features/meetings/meetings.service.spec.ts b/backend/src/features/meetings/meetings.service.spec.ts
index 79eb365..80fecf7 100644
--- a/backend/src/features/meetings/meetings.service.spec.ts
+++ b/backend/src/features/meetings/meetings.service.spec.ts
@@ -1,9 +1,13 @@
-import { ServiceUnavailableException } from '@nestjs/common';
+import {
+ BadRequestException,
+ ServiceUnavailableException,
+} from '@nestjs/common';
import {
Prisma,
ProcessStatus,
ProductCurrency,
ProductType,
+ StatusAgendamento,
} from '@prisma/client';
import { MeetingsService } from './meetings.service';
@@ -33,27 +37,42 @@ function mkProcess(overrides: any = {}) {
}
function mkPrisma(process: any) {
+ const meetingSessionCreate = jest.fn().mockImplementation(({ data }: any) =>
+ Promise.resolve({
+ id: 'meet-1',
+ process_id: data.process_id,
+ meet_link: data.meet_link,
+ started_at: data.started_at,
+ ended_at: null,
+ }),
+ );
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ process: {
+ findUnique: jest
+ .fn()
+ .mockImplementation(({ select }: any) =>
+ Promise.resolve(
+ select
+ ? { id: process.id, specialist_id: process.specialist_id }
+ : process,
+ ),
+ ),
+ },
+ meetingSession: { create: meetingSessionCreate },
+ };
return {
process: { findUnique: jest.fn().mockResolvedValue(process) },
- meetingSession: {
- create: jest.fn().mockImplementation(({ data }: any) =>
- Promise.resolve({
- id: 'meet-1',
- process_id: data.process_id,
- meet_link: data.meet_link,
- started_at: data.started_at,
- ended_at: null,
- }),
- ),
- },
+ meetingSession: { create: meetingSessionCreate },
+ $transaction: jest.fn(async (callback) => callback(tx)),
} as any;
}
-function mkConfig(accessType = 'OPEN') {
+function mkConfig(accessType = 'OPEN', provider = 'GOOGLE') {
return {
get: jest.fn((key: string, def?: string) => {
if (key === 'GOOGLE_MEET_ACCESS_TYPE') return accessType;
- if (key === 'MEETING_PROVIDER') return 'GOOGLE';
+ if (key === 'MEETING_PROVIDER') return provider;
if (key === 'MEETING_DEMO_FALLBACK_ENABLED') return 'false';
return def;
}),
@@ -149,6 +168,98 @@ describe('MeetingsService — criação via Meet REST API', () => {
});
});
+describe('MeetingsService.startMeetingForProcess — serialização canônica', () => {
+ it('adquire o lock, relê e não cria reunião para processo rejeitado', async () => {
+ const initialProcess = mkProcess();
+ const rejectedProcess = mkProcess({ status: ProcessStatus.REJECTED });
+ const rootMeetingCreate = jest.fn().mockResolvedValue({});
+ const txMeetingCreate = jest.fn().mockResolvedValue({});
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ process: {
+ findUnique: jest
+ .fn()
+ .mockResolvedValueOnce({
+ id: initialProcess.id,
+ specialist_id: initialProcess.specialist_id,
+ })
+ .mockResolvedValueOnce(rejectedProcess),
+ },
+ meetingSession: { create: txMeetingCreate },
+ };
+ const prisma = {
+ process: { findUnique: jest.fn().mockResolvedValue(initialProcess) },
+ meetingSession: { create: rootMeetingCreate },
+ $transaction: jest.fn(async (callback) => callback(tx)),
+ } as any;
+ const localNotification = {
+ sendMeetingStartedEmail: jest.fn().mockResolvedValue({}),
+ sendMeetingAdvancedEmail: jest.fn().mockResolvedValue({}),
+ } as any;
+ const service = new MeetingsService(
+ prisma,
+ mkConfig('OPEN', 'JITSI'),
+ localNotification,
+ {} as any,
+ );
+
+ await expect(
+ service.startMeetingForProcess(initialProcess.id, 'spec-1'),
+ ).rejects.toBeInstanceOf(BadRequestException);
+
+ expect(tx.$queryRaw).toHaveBeenCalledWith(
+ expect.anything(),
+ 'appointment-schedule:spec-1',
+ );
+ expect(rootMeetingCreate).not.toHaveBeenCalled();
+ expect(txMeetingCreate).not.toHaveBeenCalled();
+ expect(localNotification.sendMeetingStartedEmail).not.toHaveBeenCalled();
+ });
+
+ it('falha fechado quando o appointment relido diverge do processo', async () => {
+ const process = mkProcess({
+ appointment_id: 'appointment-1',
+ appointment: {
+ id: 'appointment-1',
+ client_id: 'other-client',
+ specialist_id: 'spec-1',
+ status: StatusAgendamento.COMPLETED,
+ },
+ });
+ const txMeetingCreate = jest.fn();
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ process: {
+ findUnique: jest
+ .fn()
+ .mockResolvedValueOnce({
+ id: process.id,
+ specialist_id: process.specialist_id,
+ })
+ .mockResolvedValueOnce(process),
+ },
+ meetingSession: { create: txMeetingCreate },
+ };
+ const prisma = {
+ process: { findUnique: jest.fn().mockResolvedValue(process) },
+ meetingSession: { create: jest.fn().mockResolvedValue({}) },
+ $transaction: jest.fn(async (callback) => callback(tx)),
+ } as any;
+ const service = new MeetingsService(
+ prisma,
+ mkConfig('OPEN', 'JITSI'),
+ notification,
+ {} as any,
+ );
+
+ await expect(
+ service.startMeetingForProcess(process.id, 'spec-1'),
+ ).rejects.toThrow('Agendamento não corresponde aos participantes');
+
+ expect(txMeetingCreate).not.toHaveBeenCalled();
+ });
+});
+
describe('MeetingsService.markConversationDone — snapshot da negociação', () => {
it('grava snapshot USD, status e histórico na mesma transação', async () => {
const product = {
diff --git a/backend/src/features/meetings/meetings.service.ts b/backend/src/features/meetings/meetings.service.ts
index b1d208b..8a36b0e 100644
--- a/backend/src/features/meetings/meetings.service.ts
+++ b/backend/src/features/meetings/meetings.service.ts
@@ -14,6 +14,7 @@ import { ProcessStatus, StatusAgendamento } from '@prisma/client';
import { GoogleMeetOAuthService } from './google-meet-oauth.service';
import { buildNegotiationSnapshotUpdate } from 'src/features/processes/negotiation-snapshot';
import { lockNegotiationProductMoney } from 'src/features/products/product-monetary-lock';
+import { acquireSpecialistScheduleLock } from 'src/features/appointments/appointment-schedule-lock';
@Injectable()
export class MeetingsService {
@@ -374,10 +375,7 @@ export class MeetingsService {
userId: string,
isAdvanced?: boolean,
) {
- const { process, isSpecialist } = await this.getAuthorizedProcess(
- processId,
- userId,
- );
+ const { isSpecialist } = await this.getAuthorizedProcess(processId, userId);
if (!isSpecialist) {
throw new ForbiddenException(
@@ -385,144 +383,152 @@ export class MeetingsService {
);
}
- const consultant = process.client.consultant;
- const consultantEmail = consultant?.email;
- const consultantName = consultant
- ? `${consultant.name} ${consultant.surname || ''}`.trim()
- : undefined;
-
- if (
- process.status !== 'SCHEDULING' &&
- process.status !== 'NEGOTIATION' &&
- process.status !== 'PROCESSING_CONTRACT'
- ) {
- throw new BadRequestException(
- 'Processo não está em etapa válida para iniciar reunião',
- );
- }
-
- if (process.meeting_session) {
- return this.buildMeetingResponse(process.meeting_session);
- }
-
- if (this.meetingProvider === 'JITSI') {
- const jitsiLink = this.buildDemoMeetingLink(process.id);
- const meeting = await this.prismaService.meetingSession.create({
- data: {
- process_id: process.id,
- started_by_id: userId,
- calendar_event_id: `jitsi-${randomUUID()}`,
- meet_link: jitsiLink,
- started_at: new Date(),
- },
- });
-
- this.logger.log(
- `[meetings] Reunião criada com provedor JITSI para processId=${process.id}`,
- );
-
- setImmediate(() => {
- const emailData = {
- clientEmail: process.client.email,
- clientName:
- `${process.client.name} ${process.client.surname || ''}`.trim(),
- specialistName:
- `${process.specialist.name} ${process.specialist.surname || ''}`.trim(),
- processId: process.id,
- platformMeetingUrl: `${this.frontendUrl}/processes/${process.id}/meeting`,
- meetingLink: jitsiLink,
- consultantEmail,
- consultantName,
- };
- const emailMethod = isAdvanced
- ? this.notificationService.sendMeetingAdvancedEmail(emailData)
- : this.notificationService.sendMeetingStartedEmail(emailData);
- emailMethod.catch((err) => {
- this.logger.error('Falha ao enviar e-mail de reunião iniciada', {
- processId: process.id,
- error: err.message,
- });
+ const result = await this.prismaService.$transaction(
+ async (tx) => {
+ const candidate = await tx.process.findUnique({
+ where: { id: processId },
+ select: { id: true, specialist_id: true },
});
- });
-
- return {
- ...this.buildMeetingResponse(meeting),
- };
- }
-
- const specialistName =
- `${process.specialist.name} ${process.specialist.surname || ''}`.trim();
- const clientName =
- `${process.client.name} ${process.client.surname || ''}`.trim();
-
- let meetLink: string;
- let spaceName: string;
- try {
- const space = await this.createMeetSpace();
- meetLink = space.meetingUri;
- spaceName = space.spaceName;
- } catch (error) {
- if (this.demoMeetingFallbackEnabled) {
- const demoLink = this.buildDemoMeetingLink(process.id);
- const meeting = await this.prismaService.meetingSession.create({
+ if (!candidate) {
+ throw new NotFoundException('Processo não encontrado');
+ }
+ if (candidate.specialist_id !== userId) {
+ throw new ForbiddenException(
+ 'Apenas o especialista pode iniciar a reunião',
+ );
+ }
+
+ await acquireSpecialistScheduleLock(tx, candidate.specialist_id);
+
+ const process = await tx.process.findUnique({
+ where: { id: processId },
+ include: {
+ appointment: true,
+ client: {
+ select: {
+ id: true,
+ email: true,
+ name: true,
+ surname: true,
+ consultant_id: true,
+ consultant: {
+ select: { id: true, email: true, name: true, surname: true },
+ },
+ },
+ },
+ specialist: {
+ select: { id: true, email: true, name: true, surname: true },
+ },
+ meeting_session: true,
+ },
+ });
+ if (!process) {
+ throw new NotFoundException('Processo não encontrado');
+ }
+ if (process.specialist_id !== userId) {
+ throw new ForbiddenException(
+ 'Apenas o especialista pode iniciar a reunião',
+ );
+ }
+ if (
+ Boolean(process.appointment) !== Boolean(process.appointment_id) ||
+ (process.appointment &&
+ (process.appointment.id !== process.appointment_id ||
+ process.appointment.client_id !== process.client_id ||
+ process.appointment.specialist_id !== process.specialist_id))
+ ) {
+ throw new BadRequestException(
+ 'Agendamento não corresponde aos participantes do processo',
+ );
+ }
+ if (
+ process.status !== ProcessStatus.SCHEDULING &&
+ process.status !== ProcessStatus.NEGOTIATION &&
+ process.status !== ProcessStatus.PROCESSING_CONTRACT
+ ) {
+ throw new BadRequestException(
+ 'Processo não está em etapa válida para iniciar reunião',
+ );
+ }
+ if (process.meeting_session) {
+ return {
+ process,
+ meeting: process.meeting_session,
+ created: false,
+ provider: 'EXISTING' as const,
+ };
+ }
+
+ let meetLink: string;
+ let calendarEventId: string;
+ let provider: 'JITSI' | 'GOOGLE' | 'DEMO';
+ if (this.meetingProvider === 'JITSI') {
+ meetLink = this.buildDemoMeetingLink(process.id);
+ calendarEventId = `jitsi-${randomUUID()}`;
+ provider = 'JITSI';
+ } else {
+ try {
+ const space = await this.createMeetSpace();
+ meetLink = space.meetingUri;
+ calendarEventId = space.spaceName;
+ provider = 'GOOGLE';
+ } catch (error) {
+ if (!this.demoMeetingFallbackEnabled) {
+ this.logger.error('Falha ao criar sala no Google Meet', {
+ processId: process.id,
+ error:
+ error instanceof Error ? error.message : 'erro desconhecido',
+ });
+ throw new ServiceUnavailableException(
+ 'Não foi possível criar a reunião no Google Meet. Verifique a conta conectada nas configurações.',
+ );
+ }
+
+ meetLink = this.buildDemoMeetingLink(process.id);
+ calendarEventId = `demo-${randomUUID()}`;
+ provider = 'DEMO';
+ }
+ }
+
+ const meeting = await tx.meetingSession.create({
data: {
process_id: process.id,
started_by_id: userId,
- calendar_event_id: `demo-${randomUUID()}`,
- meet_link: demoLink,
+ calendar_event_id: calendarEventId,
+ meet_link: meetLink,
started_at: new Date(),
},
});
- this.logger.warn(
- `[meetings] Fallback DEMO ativado após falha no Google Meet. processId=${process.id}`,
- );
-
- setImmediate(() => {
- const emailData = {
- clientEmail: process.client.email,
- clientName,
- specialistName,
- processId: process.id,
- platformMeetingUrl: `${this.frontendUrl}/processes/${process.id}/meeting`,
- meetingLink: demoLink,
- consultantEmail,
- consultantName,
- };
- const emailMethod = isAdvanced
- ? this.notificationService.sendMeetingAdvancedEmail(emailData)
- : this.notificationService.sendMeetingStartedEmail(emailData);
- emailMethod.catch((err) => {
- this.logger.error('Falha ao enviar e-mail de reunião iniciada', {
- processId: process.id,
- error: err.message,
- });
- });
- });
+ return { process, meeting, created: true, provider };
+ },
+ { maxWait: 10_000, timeout: 30_000 },
+ );
- return {
- ...this.buildMeetingResponse(meeting),
- };
- }
+ if (!result.created) {
+ return this.buildMeetingResponse(result.meeting);
+ }
- this.logger.error('Falha ao criar sala no Google Meet', {
- processId: process.id,
- error: error instanceof Error ? error.message : 'erro desconhecido',
- });
- throw new ServiceUnavailableException(
- 'Não foi possível criar a reunião no Google Meet. Verifique a conta conectada nas configurações.',
+ const { process, meeting, provider } = result;
+ if (provider === 'JITSI') {
+ this.logger.log(
+ `[meetings] Reunião criada com provedor JITSI para processId=${process.id}`,
+ );
+ } else if (provider === 'DEMO') {
+ this.logger.warn(
+ `[meetings] Fallback DEMO ativado após falha no Google Meet. processId=${process.id}`,
);
}
- const meeting = await this.prismaService.meetingSession.create({
- data: {
- process_id: process.id,
- started_by_id: userId,
- calendar_event_id: spaceName,
- meet_link: meetLink,
- started_at: new Date(),
- },
- });
+ const consultant = process.client.consultant;
+ const consultantEmail = consultant?.email;
+ const consultantName = consultant
+ ? `${consultant.name} ${consultant.surname || ''}`.trim()
+ : undefined;
+ const specialistName =
+ `${process.specialist.name} ${process.specialist.surname || ''}`.trim();
+ const clientName =
+ `${process.client.name} ${process.client.surname || ''}`.trim();
setImmediate(() => {
const emailData = {
@@ -531,7 +537,7 @@ export class MeetingsService {
specialistName,
processId: process.id,
platformMeetingUrl: `${this.frontendUrl}/processes/${process.id}/meeting`,
- meetingLink: meetLink,
+ meetingLink: meeting.meet_link,
consultantEmail,
consultantName,
};
diff --git a/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts b/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts
index d44b1b5..c857f89 100644
--- a/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts
+++ b/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts
@@ -7,6 +7,7 @@ import {
UserRole,
} from '@prisma/client';
import { randomUUID } from 'node:crypto';
+import { MeetingsService } from '../meetings/meetings.service';
import { ProcessesService } from './processes.service';
type Deferred = { promise: Promise; resolve: () => void };
@@ -93,6 +94,61 @@ function observeScheduleLockAttempt(client: PrismaClient, attempted: Deferred) {
});
}
+function pauseMeetingCreate(
+ client: PrismaClient,
+ attempted: Deferred,
+ release: Deferred,
+) {
+ const wrapTransaction = (tx: any) =>
+ new Proxy(tx, {
+ get(target, property) {
+ if (property === 'meetingSession') {
+ return new Proxy(target.meetingSession, {
+ get(meetingTarget, meetingProperty) {
+ if (meetingProperty === 'create') {
+ return async (args: any) => {
+ attempted.resolve();
+ await release.promise;
+ return meetingTarget.create(args);
+ };
+ }
+ return bindMember(meetingTarget, meetingProperty);
+ },
+ });
+ }
+ 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 meetingConfig() {
+ return {
+ get: jest.fn((key: string, fallback?: string) => {
+ if (key === 'MEETING_PROVIDER') return 'JITSI';
+ if (key === 'MEETING_DEMO_FALLBACK_ENABLED') return 'false';
+ return fallback;
+ }),
+ } as any;
+}
+
+function meetingNotifications() {
+ return {
+ sendMeetingStartedEmail: jest.fn().mockResolvedValue({}),
+ sendMeetingAdvancedEmail: jest.fn().mockResolvedValue({}),
+ sendProcessStatusChangedEmail: jest.fn().mockResolvedValue({}),
+ } as any;
+}
+
const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL;
const describeWithPostgres = databaseUrl ? describe : describe.skip;
const prismaDatabaseUrl =
@@ -304,4 +360,128 @@ describeWithPostgres('process rejection CAS — PostgreSQL concurrency', () => {
}),
).resolves.toBe(0);
}, 15_000);
+
+ it('não cria reunião nem envia e-mail quando a rejeição ganha o lock', async () => {
+ await completionClient.process.create({
+ data: {
+ id: processId,
+ client_id: clientId,
+ specialist_id: specialistId,
+ status: ProcessStatus.SCHEDULING,
+ },
+ });
+
+ const rejectionClaimAttempted = deferred();
+ const releaseRejection = deferred();
+ const meetingLockAttempted = deferred();
+ const notifications = meetingNotifications();
+ const rejectionService = new ProcessesService(
+ pauseRejectionClaim(
+ rejectClient,
+ rejectionClaimAttempted,
+ releaseRejection,
+ ) as any,
+ notifications,
+ );
+ const meetingsService = new MeetingsService(
+ observeScheduleLockAttempt(completionClient, meetingLockAttempted) as any,
+ meetingConfig(),
+ notifications,
+ {} as any,
+ );
+
+ const rejection = rejectionService.rejectProcess(
+ processId,
+ specialistId,
+ 'concorrente',
+ UserRole.SPECIALIST,
+ );
+ await rejectionClaimAttempted.promise;
+
+ const meeting = meetingsService.startMeetingForProcess(
+ processId,
+ specialistId,
+ );
+ await meetingLockAttempted.promise;
+
+ releaseRejection.resolve();
+ await expect(rejection).resolves.toMatchObject({
+ status: ProcessStatus.REJECTED,
+ });
+ await expect(meeting).rejects.toBeInstanceOf(BadRequestException);
+ await new Promise((resolve) => setImmediate(resolve));
+
+ await expect(
+ completionClient.meetingSession.count({
+ where: { process_id: processId },
+ }),
+ ).resolves.toBe(0);
+ expect(notifications.sendMeetingStartedEmail).not.toHaveBeenCalled();
+ expect(notifications.sendMeetingAdvancedEmail).not.toHaveBeenCalled();
+ }, 15_000);
+
+ it('mantém reunião e recusa rejeição quando o início ganha o lock', async () => {
+ await completionClient.process.create({
+ data: {
+ id: processId,
+ client_id: clientId,
+ specialist_id: specialistId,
+ status: ProcessStatus.SCHEDULING,
+ },
+ });
+
+ const meetingCreateAttempted = deferred();
+ const releaseMeeting = deferred();
+ const rejectionLockAttempted = deferred();
+ const notifications = meetingNotifications();
+ const meetingsService = new MeetingsService(
+ pauseMeetingCreate(
+ completionClient,
+ meetingCreateAttempted,
+ releaseMeeting,
+ ) as any,
+ meetingConfig(),
+ notifications,
+ {} as any,
+ );
+ const rejectionService = new ProcessesService(
+ observeScheduleLockAttempt(rejectClient, rejectionLockAttempted) as any,
+ notifications,
+ );
+
+ const meeting = meetingsService.startMeetingForProcess(
+ processId,
+ specialistId,
+ );
+ await meetingCreateAttempted.promise;
+
+ const rejection = rejectionService.rejectProcess(
+ processId,
+ specialistId,
+ 'concorrente',
+ UserRole.SPECIALIST,
+ );
+ await rejectionLockAttempted.promise;
+
+ releaseMeeting.resolve();
+ await expect(meeting).resolves.toMatchObject({ is_active: true });
+ await expect(rejection).rejects.toBeInstanceOf(BadRequestException);
+ await new Promise((resolve) => setImmediate(resolve));
+
+ await expect(
+ completionClient.process.findUniqueOrThrow({ where: { id: processId } }),
+ ).resolves.toMatchObject({ status: ProcessStatus.SCHEDULING });
+ await expect(
+ completionClient.meetingSession.count({
+ where: { process_id: processId },
+ }),
+ ).resolves.toBe(1);
+ await expect(
+ completionClient.processRejection.count({
+ where: { process_id: processId },
+ }),
+ ).resolves.toBe(0);
+ expect(notifications.sendMeetingStartedEmail).toHaveBeenCalledTimes(1);
+ expect(notifications.sendMeetingAdvancedEmail).not.toHaveBeenCalled();
+ }, 15_000);
});
diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts
index 08345af..af216e4 100644
--- a/backend/src/features/processes/processes.service.spec.ts
+++ b/backend/src/features/processes/processes.service.spec.ts
@@ -1960,6 +1960,7 @@ describe('ProcessesService — autorização centralizada de processos', () => {
client_id: ownerClientId,
specialist_id: assignedSpecialistId,
status: ProcessStatus.SCHEDULING,
+ appointment_id: null,
updated_at: new Date('2026-01-01T00:00:00.000Z'),
notes: null,
product_type: null,
@@ -2304,27 +2305,19 @@ describe('ProcessesService — autorização centralizada de processos', () => {
UserRole.SPECIALIST,
'Cancele o agendamento pelo fluxo próprio',
],
- [
- 'cliente',
- StatusAgendamento.COMPLETED,
- ownerClientId,
- UserRole.CUSTOMER,
- 'Processo com agendamento concluído',
- ],
- [
- 'especialista',
- StatusAgendamento.COMPLETED,
- assignedSpecialistId,
- UserRole.SPECIALIST,
- 'Processo com agendamento concluído',
- ],
])(
'%s não rejeita processo com appointment %s',
async (_label, appointmentStatus, actorId, actorRole, expectedMessage) => {
const { service, processUpdateMany, historyCreate, rejectionCreate, tx } =
rejectionService(
protectedProcess({
- appointment: { status: appointmentStatus },
+ appointment_id: 'abababab-abab-4bab-8bab-abababababab',
+ appointment: {
+ id: 'abababab-abab-4bab-8bab-abababababab',
+ client_id: ownerClientId,
+ specialist_id: assignedSpecialistId,
+ status: appointmentStatus,
+ },
}),
);
@@ -2403,9 +2396,16 @@ describe('ProcessesService — autorização centralizada de processos', () => {
});
it('especialista pode rejeitar processo com appointment cancelado e reunião encerrada', async () => {
+ const appointmentId = 'abababab-abab-4bab-8bab-abababababab';
const { service, processUpdateMany } = rejectionService(
protectedProcess({
- appointment: { status: StatusAgendamento.CANCELLED },
+ appointment_id: appointmentId,
+ appointment: {
+ id: appointmentId,
+ client_id: ownerClientId,
+ specialist_id: assignedSpecialistId,
+ status: StatusAgendamento.CANCELLED,
+ },
meeting_session: { ended_at: new Date('2026-01-01T12:00:00.000Z') },
}),
);
@@ -2424,6 +2424,105 @@ describe('ProcessesService — autorização centralizada de processos', () => {
expect(processUpdateMany).toHaveBeenCalledTimes(1);
});
+ it.each([
+ ['cliente', ownerClientId, UserRole.CUSTOMER, null],
+ [
+ 'especialista',
+ assignedSpecialistId,
+ UserRole.SPECIALIST,
+ { ended_at: new Date('2026-01-01T12:00:00.000Z') },
+ ],
+ ])(
+ '%s pode rejeitar processo pós-reunião com appointment concluído',
+ async (_label, actorId, actorRole, meetingSession) => {
+ const appointmentId = 'abababab-abab-4bab-8bab-abababababab';
+ const { service, processUpdateMany } = rejectionService(
+ protectedProcess({
+ status: ProcessStatus.NEGOTIATION,
+ appointment_id: appointmentId,
+ appointment: {
+ id: appointmentId,
+ client_id: ownerClientId,
+ specialist_id: assignedSpecialistId,
+ status: StatusAgendamento.COMPLETED,
+ },
+ meeting_session: meetingSession,
+ }),
+ );
+
+ await expect(
+ service.rejectProcess(
+ '99999999-9999-4999-8999-999999999999',
+ actorId,
+ undefined,
+ actorRole,
+ ),
+ ).resolves.toEqual(
+ expect.objectContaining({ status: ProcessStatus.REJECTED }),
+ );
+
+ expect(processUpdateMany).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it.each([
+ [
+ 'id',
+ {
+ appointment_id: 'abababab-abab-4bab-8bab-abababababab',
+ appointment: {
+ id: 'cdcdcdcd-cdcd-4dcd-8dcd-cdcdcdcdcdcd',
+ client_id: ownerClientId,
+ specialist_id: assignedSpecialistId,
+ status: StatusAgendamento.CANCELLED,
+ },
+ },
+ ],
+ [
+ 'cliente',
+ {
+ appointment_id: 'abababab-abab-4bab-8bab-abababababab',
+ appointment: {
+ id: 'abababab-abab-4bab-8bab-abababababab',
+ client_id: outsiderId,
+ specialist_id: assignedSpecialistId,
+ status: StatusAgendamento.CANCELLED,
+ },
+ },
+ ],
+ [
+ 'especialista',
+ {
+ appointment_id: 'abababab-abab-4bab-8bab-abababababab',
+ appointment: {
+ id: 'abababab-abab-4bab-8bab-abababababab',
+ client_id: ownerClientId,
+ specialist_id: outsiderId,
+ status: StatusAgendamento.CANCELLED,
+ },
+ },
+ ],
+ ])(
+ 'não rejeita quando o %s do appointment diverge do processo',
+ async (_field, overrides) => {
+ const { service, processUpdateMany, historyCreate, rejectionCreate } =
+ rejectionService(protectedProcess(overrides));
+
+ await expect(
+ service.rejectProcess(
+ '99999999-9999-4999-8999-999999999999',
+ assignedSpecialistId,
+ undefined,
+ UserRole.SPECIALIST,
+ ),
+ ).rejects.toThrow('Agendamento não corresponde aos participantes');
+
+ expect(processUpdateMany).not.toHaveBeenCalled();
+ expect(historyCreate).not.toHaveBeenCalled();
+ expect(rejectionCreate).not.toHaveBeenCalled();
+ },
+ );
+
it('rejeição perde a CAS sem criar histórico nem motivo', async () => {
const { service, historyCreate, rejectionCreate, processUpdateMany } =
rejectionService(protectedProcess(), 0);
diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts
index ed095ac..3d8199c 100644
--- a/backend/src/features/processes/processes.service.ts
+++ b/backend/src/features/processes/processes.service.ts
@@ -2034,7 +2034,14 @@ export class ProcessesService {
car: true,
boat: true,
aircraft: true,
- appointment: { select: { status: true } },
+ appointment: {
+ select: {
+ id: true,
+ client_id: true,
+ specialist_id: true,
+ status: true,
+ },
+ },
meeting_session: { select: { ended_at: true } },
},
});
@@ -2059,18 +2066,28 @@ export class ProcessesService {
);
}
if (
- existingProcess.appointment &&
- existingProcess.appointment.status !== StatusAgendamento.CANCELLED
+ Boolean(existingProcess.appointment) !==
+ Boolean(existingProcess.appointment_id) ||
+ (existingProcess.appointment &&
+ (existingProcess.appointment.id !==
+ existingProcess.appointment_id ||
+ existingProcess.appointment.client_id !==
+ existingProcess.client_id ||
+ existingProcess.appointment.specialist_id !==
+ existingProcess.specialist_id))
) {
- const appointmentCanBeCancelled =
- existingProcess.appointment.status ===
- StatusAgendamento.PENDING ||
+ throw new BadRequestException(
+ 'Agendamento não corresponde aos participantes do processo',
+ );
+ }
+ if (
+ existingProcess.appointment &&
+ (existingProcess.appointment.status === StatusAgendamento.PENDING ||
existingProcess.appointment.status ===
- StatusAgendamento.SCHEDULED;
+ StatusAgendamento.SCHEDULED)
+ ) {
throw new BadRequestException(
- appointmentCanBeCancelled
- ? 'Cancele o agendamento pelo fluxo próprio antes de rejeitar o processo'
- : 'Processo com agendamento concluído não pode ser rejeitado por esta rota',
+ 'Cancele o agendamento pelo fluxo próprio antes de rejeitar o processo',
);
}
if (
From 3ee49974ebdfbb45ce5f2fa6684288a366d82c9b Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:22:48 -0300
Subject: [PATCH 38/60] fix(meetings): move provider calls outside transactions
---
.../meetings/meetings.service.spec.ts | 241 ++++++++-
.../src/features/meetings/meetings.service.ts | 457 +++++++++++++++---
...ses-rejection-concurrency.postgres.spec.ts | 80 +++
3 files changed, 690 insertions(+), 88 deletions(-)
diff --git a/backend/src/features/meetings/meetings.service.spec.ts b/backend/src/features/meetings/meetings.service.spec.ts
index 80fecf7..f65ea9e 100644
--- a/backend/src/features/meetings/meetings.service.spec.ts
+++ b/backend/src/features/meetings/meetings.service.spec.ts
@@ -1,5 +1,6 @@
import {
BadRequestException,
+ ConflictException,
ServiceUnavailableException,
} from '@nestjs/common';
import {
@@ -37,15 +38,48 @@ function mkProcess(overrides: any = {}) {
}
function mkPrisma(process: any) {
- const meetingSessionCreate = jest.fn().mockImplementation(({ data }: any) =>
- Promise.resolve({
+ let storedMeeting = process.meeting_session;
+ const meetingSessionCreate = jest.fn().mockImplementation(({ data }: any) => {
+ storedMeeting = {
id: 'meet-1',
process_id: data.process_id,
+ calendar_event_id: data.calendar_event_id,
meet_link: data.meet_link,
started_at: data.started_at,
ended_at: null,
- }),
- );
+ };
+ return Promise.resolve(storedMeeting);
+ });
+ const meetingSessionUpdateMany = jest
+ .fn()
+ .mockImplementation(({ where, data }: any) => {
+ if (
+ storedMeeting &&
+ (!where.id || where.id === storedMeeting.id) &&
+ (!where.process_id || where.process_id === storedMeeting.process_id) &&
+ (!where.calendar_event_id ||
+ where.calendar_event_id === storedMeeting.calendar_event_id) &&
+ (where.meet_link === undefined ||
+ where.meet_link === storedMeeting.meet_link)
+ ) {
+ storedMeeting = { ...storedMeeting, ...data };
+ return Promise.resolve({ count: 1 });
+ }
+ return Promise.resolve({ count: 0 });
+ });
+ const meetingSessionDeleteMany = jest.fn().mockImplementation(({ where }) => {
+ if (
+ storedMeeting &&
+ (!where.id || where.id === storedMeeting.id) &&
+ (!where.process_id || where.process_id === storedMeeting.process_id) &&
+ (!where.calendar_event_id ||
+ where.calendar_event_id === storedMeeting.calendar_event_id)
+ ) {
+ storedMeeting = null;
+ return Promise.resolve({ count: 1 });
+ }
+ return Promise.resolve({ count: 0 });
+ });
const tx = {
$queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
process: {
@@ -55,15 +89,30 @@ function mkPrisma(process: any) {
Promise.resolve(
select
? { id: process.id, specialist_id: process.specialist_id }
- : process,
+ : { ...process, meeting_session: storedMeeting },
),
),
},
- meetingSession: { create: meetingSessionCreate },
+ meetingSession: {
+ create: meetingSessionCreate,
+ updateMany: meetingSessionUpdateMany,
+ deleteMany: meetingSessionDeleteMany,
+ findUnique: jest.fn().mockImplementation(() => storedMeeting),
+ },
};
return {
- process: { findUnique: jest.fn().mockResolvedValue(process) },
- meetingSession: { create: meetingSessionCreate },
+ process: {
+ findUnique: jest
+ .fn()
+ .mockImplementation(() =>
+ Promise.resolve({ ...process, meeting_session: storedMeeting }),
+ ),
+ },
+ meetingSession: {
+ create: meetingSessionCreate,
+ updateMany: meetingSessionUpdateMany,
+ deleteMany: meetingSessionDeleteMany,
+ },
$transaction: jest.fn(async (callback) => callback(tx)),
} as any;
}
@@ -91,8 +140,23 @@ describe('MeetingsService — criação via Meet REST API', () => {
it('cria sala Meet com accessType OPEN e grava meet_link + spaceName', async () => {
const process = mkProcess();
const prisma = mkPrisma(process);
+ let transactionActive = false;
+ const runTransaction = prisma.$transaction.getMockImplementation();
+ prisma.$transaction.mockImplementation(
+ async (callback: (tx: any) => Promise, options?: any) => {
+ transactionActive = true;
+ try {
+ return await runTransaction(callback, options);
+ } finally {
+ transactionActive = false;
+ }
+ },
+ );
const oauth = {
- getAccessToken: jest.fn().mockResolvedValue('access-token'),
+ getAccessToken: jest.fn().mockImplementation(async () => {
+ expect(transactionActive).toBe(false);
+ return 'access-token';
+ }),
} as any;
const fetchMock = jest.fn().mockResolvedValue({
@@ -120,11 +184,10 @@ describe('MeetingsService — criação via Meet REST API', () => {
);
expect(result.meet_link).toBe('https://meet.google.com/abc-defg-hij');
- expect(prisma.meetingSession.create).toHaveBeenCalledWith(
+ expect(prisma.meetingSession.updateMany).toHaveBeenLastCalledWith(
expect.objectContaining({
data: expect.objectContaining({
calendar_event_id: 'spaces/abc123',
- meet_link: 'https://meet.google.com/abc-defg-hij',
}),
}),
);
@@ -148,6 +211,126 @@ describe('MeetingsService — criação via Meet REST API', () => {
await expect(
svc.startMeetingForProcess('proc-1', 'spec-1'),
).rejects.toThrow(ServiceUnavailableException);
+ expect(prisma.meetingSession.deleteMany).toHaveBeenCalledWith({
+ where: expect.objectContaining({
+ process_id: 'proc-1',
+ calendar_event_id: expect.stringMatching(/^meeting-init:/),
+ }),
+ });
+ });
+
+ it('aborta provider travado por timeout e libera o claim', async () => {
+ jest.useFakeTimers();
+ try {
+ const process = mkProcess();
+ const prisma = mkPrisma(process);
+ const oauth = {
+ getAccessToken: jest.fn().mockResolvedValue('access-token'),
+ } as any;
+ const fetchMock = jest.fn().mockImplementation((_url, options) => {
+ return new Promise((_resolve, reject) => {
+ options.signal.addEventListener('abort', () => {
+ reject(new Error('provider abortado'));
+ });
+ });
+ });
+ global.fetch = fetchMock as any;
+ const svc = new MeetingsService(
+ prisma,
+ mkConfig('OPEN'),
+ notification,
+ oauth,
+ );
+
+ const start = svc.startMeetingForProcess('proc-1', 'spec-1');
+ const rejection = expect(start).rejects.toBeInstanceOf(
+ ServiceUnavailableException,
+ );
+ for (
+ let attempt = 0;
+ attempt < 10 && !fetchMock.mock.calls.length;
+ attempt += 1
+ ) {
+ await Promise.resolve();
+ }
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ await jest.advanceTimersByTimeAsync(10_000);
+
+ await rejection;
+ expect(fetchMock.mock.calls[0][1].signal.aborted).toBe(true);
+ expect(prisma.meetingSession.deleteMany).toHaveBeenCalled();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('recupera claim pronto sem chamar o provedor nem duplicar notificação', async () => {
+ const process = mkProcess({
+ meeting_session: {
+ id: 'meet-1',
+ process_id: 'proc-1',
+ calendar_event_id: 'meeting-ready:claim-1:GOOGLE:spaces%2Frecovered',
+ meet_link: 'https://meet.google.com/recovered',
+ started_at: new Date(),
+ ended_at: null,
+ },
+ });
+ const prisma = mkPrisma(process);
+ const oauth = { getAccessToken: jest.fn() } as any;
+ const localNotification = {
+ sendMeetingStartedEmail: jest.fn().mockResolvedValue({}),
+ sendMeetingAdvancedEmail: jest.fn().mockResolvedValue({}),
+ } as any;
+ const svc = new MeetingsService(
+ prisma,
+ mkConfig('OPEN'),
+ localNotification,
+ oauth,
+ );
+
+ await expect(
+ svc.startMeetingForProcess('proc-1', 'spec-1'),
+ ).resolves.toMatchObject({
+ meet_link: 'https://meet.google.com/recovered',
+ is_active: true,
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(oauth.getAccessToken).not.toHaveBeenCalled();
+ expect(prisma.meetingSession.updateMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: { calendar_event_id: 'spaces/recovered' },
+ }),
+ );
+ expect(localNotification.sendMeetingStartedEmail).toHaveBeenCalledTimes(1);
+ });
+
+ it('recusa start duplicado enquanto um claim recente está inicializando', async () => {
+ const process = mkProcess({
+ meeting_session: {
+ id: 'meet-1',
+ process_id: 'proc-1',
+ calendar_event_id: 'meeting-init:claim-1',
+ meet_link: '',
+ started_at: new Date(),
+ ended_at: null,
+ },
+ });
+ const prisma = mkPrisma(process);
+ const oauth = { getAccessToken: jest.fn() } as any;
+ const svc = new MeetingsService(
+ prisma,
+ mkConfig('OPEN'),
+ notification,
+ oauth,
+ );
+
+ await expect(
+ svc.startMeetingForProcess('proc-1', 'spec-1'),
+ ).rejects.toBeInstanceOf(ConflictException);
+
+ expect(oauth.getAccessToken).not.toHaveBeenCalled();
+ expect(prisma.meetingSession.create).not.toHaveBeenCalled();
});
it('só o especialista pode iniciar a reunião', async () => {
@@ -169,6 +352,42 @@ describe('MeetingsService — criação via Meet REST API', () => {
});
describe('MeetingsService.startMeetingForProcess — serialização canônica', () => {
+ it('remove o claim se a revalidação final encontrar processo terminal', async () => {
+ const process = mkProcess();
+ const prisma = mkPrisma(process);
+ const runTransaction = prisma.$transaction.getMockImplementation();
+ let transactionCount = 0;
+ prisma.$transaction.mockImplementation(async (callback, options) => {
+ transactionCount += 1;
+ if (transactionCount === 2) {
+ process.status = ProcessStatus.REJECTED;
+ }
+ return runTransaction(callback, options);
+ });
+ const localNotification = {
+ sendMeetingStartedEmail: jest.fn().mockResolvedValue({}),
+ sendMeetingAdvancedEmail: jest.fn().mockResolvedValue({}),
+ } as any;
+ const service = new MeetingsService(
+ prisma,
+ mkConfig('OPEN', 'JITSI'),
+ localNotification,
+ {} as any,
+ );
+
+ await expect(
+ service.startMeetingForProcess(process.id, 'spec-1'),
+ ).rejects.toBeInstanceOf(BadRequestException);
+
+ expect(prisma.meetingSession.deleteMany).toHaveBeenCalledWith({
+ where: expect.objectContaining({
+ id: 'meet-1',
+ calendar_event_id: expect.stringMatching(/^meeting-ready:/),
+ }),
+ });
+ expect(localNotification.sendMeetingStartedEmail).not.toHaveBeenCalled();
+ });
+
it('adquire o lock, relê e não cria reunião para processo rejeitado', async () => {
const initialProcess = mkProcess();
const rejectedProcess = mkProcess({ status: ProcessStatus.REJECTED });
diff --git a/backend/src/features/meetings/meetings.service.ts b/backend/src/features/meetings/meetings.service.ts
index 8a36b0e..896ef4f 100644
--- a/backend/src/features/meetings/meetings.service.ts
+++ b/backend/src/features/meetings/meetings.service.ts
@@ -1,5 +1,6 @@
import {
BadRequestException,
+ ConflictException,
ForbiddenException,
Injectable,
Logger,
@@ -16,6 +17,11 @@ import { buildNegotiationSnapshotUpdate } from 'src/features/processes/negotiati
import { lockNegotiationProductMoney } from 'src/features/products/product-monetary-lock';
import { acquireSpecialistScheduleLock } from 'src/features/appointments/appointment-schedule-lock';
+const MEETING_INITIALIZATION_PREFIX = 'meeting-init:';
+const MEETING_READY_PREFIX = 'meeting-ready:';
+const MEETING_INITIALIZATION_TTL_MS = 2 * 60 * 1000;
+const MEETING_PROVIDER_TIMEOUT_MS = 10_000;
+
@Injectable()
export class MeetingsService {
private readonly logger = new Logger(MeetingsService.name);
@@ -75,16 +81,27 @@ export class MeetingsService {
}> {
const accessToken = await this.googleMeetOAuthService.getAccessToken();
- const response = await fetch('https://meet.googleapis.com/v2/spaces', {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${accessToken}`,
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- config: { accessType: this.meetAccessType },
- }),
- });
+ const controller = new AbortController();
+ const timeout = setTimeout(
+ () => controller.abort(),
+ MEETING_PROVIDER_TIMEOUT_MS,
+ );
+ let response: Response;
+ try {
+ response = await fetch('https://meet.googleapis.com/v2/spaces', {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ config: { accessType: this.meetAccessType },
+ }),
+ signal: controller.signal,
+ });
+ } finally {
+ clearTimeout(timeout);
+ }
if (!response.ok) {
const detail = await response.text();
@@ -103,6 +120,90 @@ export class MeetingsService {
return { spaceName: data.name, meetingUri: data.meetingUri };
}
+ private isInitializationClaim(meeting: any): boolean {
+ return Boolean(
+ meeting?.calendar_event_id?.startsWith(MEETING_INITIALIZATION_PREFIX),
+ );
+ }
+
+ private parseReadyClaim(meeting: any): {
+ claimId: string;
+ provider: 'JITSI' | 'GOOGLE' | 'DEMO';
+ calendarEventId: string;
+ } | null {
+ const value = meeting?.calendar_event_id;
+ if (typeof value !== 'string' || !value.startsWith(MEETING_READY_PREFIX)) {
+ return null;
+ }
+ const [claimId, provider, encodedCalendarEventId] = value
+ .slice(MEETING_READY_PREFIX.length)
+ .split(':', 3);
+ if (
+ !claimId ||
+ !encodedCalendarEventId ||
+ !['JITSI', 'GOOGLE', 'DEMO'].includes(provider)
+ ) {
+ return null;
+ }
+ return {
+ claimId,
+ provider: provider as 'JITSI' | 'GOOGLE' | 'DEMO',
+ calendarEventId: decodeURIComponent(encodedCalendarEventId),
+ };
+ }
+
+ private buildReadyClaim(
+ claimId: string,
+ provider: 'JITSI' | 'GOOGLE' | 'DEMO',
+ calendarEventId: string,
+ ): string {
+ return `${MEETING_READY_PREFIX}${claimId}:${provider}:${encodeURIComponent(calendarEventId)}`;
+ }
+
+ private assertMeetingCanStart(process: any, userId: string): void {
+ if (process.specialist_id !== userId) {
+ throw new ForbiddenException(
+ 'Apenas o especialista pode iniciar a reunião',
+ );
+ }
+ if (
+ Boolean(process.appointment) !== Boolean(process.appointment_id) ||
+ (process.appointment &&
+ (process.appointment.id !== process.appointment_id ||
+ process.appointment.client_id !== process.client_id ||
+ process.appointment.specialist_id !== process.specialist_id))
+ ) {
+ throw new BadRequestException(
+ 'Agendamento não corresponde aos participantes do processo',
+ );
+ }
+ if (
+ process.status !== ProcessStatus.SCHEDULING &&
+ process.status !== ProcessStatus.NEGOTIATION &&
+ process.status !== ProcessStatus.PROCESSING_CONTRACT
+ ) {
+ throw new BadRequestException(
+ 'Processo não está em etapa válida para iniciar reunião',
+ );
+ }
+ }
+
+ private async removeInitializationClaim(
+ processId: string,
+ specialistId: string,
+ calendarEventId: string,
+ ): Promise {
+ await this.prismaService.$transaction(async (tx) => {
+ await acquireSpecialistScheduleLock(tx, specialistId);
+ await tx.meetingSession.deleteMany({
+ where: {
+ process_id: processId,
+ calendar_event_id: calendarEventId,
+ },
+ });
+ });
+ }
+
private async getAuthorizedProcess(processId: string, userId: string) {
const process = await this.prismaService.process.findUnique({
where: { id: processId },
@@ -365,7 +466,9 @@ export class MeetingsService {
async getMeetingByProcess(processId: string, userId: string) {
const { process } = await this.getAuthorizedProcess(processId, userId);
- return process.meeting_session
+ return process.meeting_session &&
+ !this.isInitializationClaim(process.meeting_session) &&
+ !this.parseReadyClaim(process.meeting_session)
? this.buildMeetingResponse(process.meeting_session)
: null;
}
@@ -383,7 +486,7 @@ export class MeetingsService {
);
}
- const result = await this.prismaService.$transaction(
+ const reservation = await this.prismaService.$transaction(
async (tx) => {
const candidate = await tx.process.findUnique({
where: { id: processId },
@@ -425,91 +528,282 @@ export class MeetingsService {
if (!process) {
throw new NotFoundException('Processo não encontrado');
}
- if (process.specialist_id !== userId) {
- throw new ForbiddenException(
- 'Apenas o especialista pode iniciar a reunião',
- );
- }
- if (
- Boolean(process.appointment) !== Boolean(process.appointment_id) ||
- (process.appointment &&
- (process.appointment.id !== process.appointment_id ||
- process.appointment.client_id !== process.client_id ||
- process.appointment.specialist_id !== process.specialist_id))
- ) {
- throw new BadRequestException(
- 'Agendamento não corresponde aos participantes do processo',
- );
- }
- if (
- process.status !== ProcessStatus.SCHEDULING &&
- process.status !== ProcessStatus.NEGOTIATION &&
- process.status !== ProcessStatus.PROCESSING_CONTRACT
- ) {
- throw new BadRequestException(
- 'Processo não está em etapa válida para iniciar reunião',
- );
- }
+ this.assertMeetingCanStart(process, userId);
if (process.meeting_session) {
- return {
- process,
- meeting: process.meeting_session,
- created: false,
- provider: 'EXISTING' as const,
- };
- }
-
- let meetLink: string;
- let calendarEventId: string;
- let provider: 'JITSI' | 'GOOGLE' | 'DEMO';
- if (this.meetingProvider === 'JITSI') {
- meetLink = this.buildDemoMeetingLink(process.id);
- calendarEventId = `jitsi-${randomUUID()}`;
- provider = 'JITSI';
- } else {
- try {
- const space = await this.createMeetSpace();
- meetLink = space.meetingUri;
- calendarEventId = space.spaceName;
- provider = 'GOOGLE';
- } catch (error) {
- if (!this.demoMeetingFallbackEnabled) {
- this.logger.error('Falha ao criar sala no Google Meet', {
- processId: process.id,
- error:
- error instanceof Error ? error.message : 'erro desconhecido',
- });
- throw new ServiceUnavailableException(
- 'Não foi possível criar a reunião no Google Meet. Verifique a conta conectada nas configurações.',
+ const ready = this.parseReadyClaim(process.meeting_session);
+ if (ready) {
+ return {
+ process,
+ meeting: process.meeting_session,
+ ready,
+ created: false,
+ provider: ready.provider,
+ };
+ }
+ if (this.isInitializationClaim(process.meeting_session)) {
+ const claimAge =
+ Date.now() - process.meeting_session.started_at.getTime();
+ if (claimAge < MEETING_INITIALIZATION_TTL_MS) {
+ throw new ConflictException(
+ 'A reunião já está sendo iniciada. Tente novamente em instantes.',
);
}
-
- meetLink = this.buildDemoMeetingLink(process.id);
- calendarEventId = `demo-${randomUUID()}`;
- provider = 'DEMO';
+ await tx.meetingSession.deleteMany({
+ where: {
+ id: process.meeting_session.id,
+ calendar_event_id: process.meeting_session.calendar_event_id,
+ },
+ });
+ } else {
+ return {
+ process,
+ meeting: process.meeting_session,
+ ready: null,
+ created: false,
+ provider: 'EXISTING' as const,
+ };
}
}
+ const claimId = randomUUID();
+ const claimCalendarEventId = `${MEETING_INITIALIZATION_PREFIX}${claimId}`;
const meeting = await tx.meetingSession.create({
data: {
process_id: process.id,
started_by_id: userId,
- calendar_event_id: calendarEventId,
- meet_link: meetLink,
+ calendar_event_id: claimCalendarEventId,
+ meet_link: '',
started_at: new Date(),
},
});
- return { process, meeting, created: true, provider };
+ return {
+ process,
+ meeting,
+ claimId,
+ claimCalendarEventId,
+ ready: null,
+ created: true,
+ provider: null,
+ };
},
{ maxWait: 10_000, timeout: 30_000 },
);
- if (!result.created) {
- return this.buildMeetingResponse(result.meeting);
+ if (!reservation.created && !reservation.ready) {
+ return this.buildMeetingResponse(reservation.meeting);
+ }
+
+ let ready = reservation.ready;
+ if (!ready) {
+ const claimId = reservation.claimId;
+ const claimCalendarEventId = reservation.claimCalendarEventId;
+ if (!claimId || !claimCalendarEventId) {
+ throw new ConflictException('Reserva de reunião inválida');
+ }
+ let meetLink: string;
+ let calendarEventId: string;
+ let provider: 'JITSI' | 'GOOGLE' | 'DEMO';
+ if (this.meetingProvider === 'JITSI') {
+ meetLink = this.buildDemoMeetingLink(reservation.process.id);
+ calendarEventId = `jitsi-${randomUUID()}`;
+ provider = 'JITSI';
+ } else {
+ try {
+ const space = await this.createMeetSpace();
+ meetLink = space.meetingUri;
+ calendarEventId = space.spaceName;
+ provider = 'GOOGLE';
+ } catch (error) {
+ if (!this.demoMeetingFallbackEnabled) {
+ try {
+ await this.removeInitializationClaim(
+ processId,
+ userId,
+ claimCalendarEventId,
+ );
+ } catch (cleanupError) {
+ this.logger.error('Falha ao liberar reserva de reunião', {
+ processId,
+ error:
+ cleanupError instanceof Error
+ ? cleanupError.message
+ : 'erro desconhecido',
+ });
+ }
+ this.logger.error('Falha ao criar sala no Google Meet', {
+ processId: reservation.process.id,
+ error:
+ error instanceof Error ? error.message : 'erro desconhecido',
+ });
+ throw new ServiceUnavailableException(
+ 'Não foi possível criar a reunião no Google Meet. Verifique a conta conectada nas configurações.',
+ );
+ }
+
+ meetLink = this.buildDemoMeetingLink(reservation.process.id);
+ calendarEventId = `demo-${randomUUID()}`;
+ provider = 'DEMO';
+ }
+ }
+
+ const readyCalendarEventId = this.buildReadyClaim(
+ claimId,
+ provider,
+ calendarEventId,
+ );
+ const checkpoint = await this.prismaService.meetingSession.updateMany({
+ where: {
+ id: reservation.meeting.id,
+ process_id: processId,
+ calendar_event_id: claimCalendarEventId,
+ meet_link: '',
+ },
+ data: {
+ calendar_event_id: readyCalendarEventId,
+ meet_link: meetLink,
+ },
+ });
+ if (checkpoint.count !== 1) {
+ throw new ConflictException(
+ 'A reserva da reunião mudou durante a criação. Tente novamente.',
+ );
+ }
+ ready = { claimId, provider, calendarEventId };
+ reservation.meeting.calendar_event_id = readyCalendarEventId;
+ reservation.meeting.meet_link = meetLink;
+ }
+ if (!ready) {
+ throw new ConflictException('Reserva de reunião inválida');
}
+ const readyClaim = ready;
- const { process, meeting, provider } = result;
+ const finalized = await this.prismaService.$transaction(
+ async (tx) => {
+ const candidate = await tx.process.findUnique({
+ where: { id: processId },
+ select: { id: true, specialist_id: true },
+ });
+ if (!candidate) {
+ throw new NotFoundException('Processo não encontrado');
+ }
+ if (candidate.specialist_id !== userId) {
+ throw new ForbiddenException(
+ 'Apenas o especialista pode iniciar a reunião',
+ );
+ }
+ await acquireSpecialistScheduleLock(tx, candidate.specialist_id);
+ const process = await tx.process.findUnique({
+ where: { id: processId },
+ include: {
+ appointment: true,
+ client: {
+ select: {
+ id: true,
+ email: true,
+ name: true,
+ surname: true,
+ consultant_id: true,
+ consultant: {
+ select: { id: true, email: true, name: true, surname: true },
+ },
+ },
+ },
+ specialist: {
+ select: { id: true, email: true, name: true, surname: true },
+ },
+ meeting_session: true,
+ },
+ });
+ if (!process) {
+ throw new NotFoundException('Processo não encontrado');
+ }
+ try {
+ this.assertMeetingCanStart(process, userId);
+ } catch (error) {
+ const invalidReady = this.parseReadyClaim(process.meeting_session);
+ if (invalidReady?.claimId === readyClaim.claimId) {
+ await tx.meetingSession.deleteMany({
+ where: {
+ id: process.meeting_session!.id,
+ calendar_event_id: process.meeting_session!.calendar_event_id,
+ },
+ });
+ }
+ return { failure: error };
+ }
+
+ const currentMeeting = process.meeting_session;
+ const currentReady = this.parseReadyClaim(currentMeeting);
+ if (!currentReady || currentReady.claimId !== readyClaim.claimId) {
+ if (
+ currentMeeting &&
+ !this.isInitializationClaim(currentMeeting) &&
+ !currentReady
+ ) {
+ return {
+ process,
+ meeting: currentMeeting,
+ created: false,
+ provider: 'EXISTING' as const,
+ };
+ }
+ throw new ConflictException(
+ 'A reserva da reunião mudou durante a finalização. Tente novamente.',
+ );
+ }
+ if (!currentMeeting) {
+ throw new ConflictException(
+ 'A reserva da reunião não existe mais. Tente novamente.',
+ );
+ }
+
+ const update = await tx.meetingSession.updateMany({
+ where: {
+ id: currentMeeting.id,
+ calendar_event_id: currentMeeting.calendar_event_id,
+ },
+ data: { calendar_event_id: readyClaim.calendarEventId },
+ });
+ if (update.count !== 1) {
+ const current = await tx.meetingSession.findUnique({
+ where: { process_id: processId },
+ });
+ if (current && !this.parseReadyClaim(current)) {
+ return {
+ process,
+ meeting: current,
+ created: false,
+ provider: 'EXISTING' as const,
+ };
+ }
+ throw new ConflictException(
+ 'A reunião mudou durante a finalização. Tente novamente.',
+ );
+ }
+
+ return {
+ process,
+ meeting: {
+ ...currentMeeting,
+ calendar_event_id: readyClaim.calendarEventId,
+ },
+ created: true,
+ provider: readyClaim.provider,
+ };
+ },
+ { maxWait: 10_000, timeout: 30_000 },
+ );
+
+ if ('failure' in finalized) {
+ throw finalized.failure;
+ }
+
+ if (!finalized.created) {
+ return this.buildMeetingResponse(finalized.meeting);
+ }
+
+ const { process, meeting, provider } = finalized;
if (provider === 'JITSI') {
this.logger.log(
`[meetings] Reunião criada com provedor JITSI para processId=${process.id}`,
@@ -571,6 +865,15 @@ export class MeetingsService {
throw new NotFoundException('Reunião não encontrada para este processo');
}
+ if (
+ this.isInitializationClaim(process.meeting_session) ||
+ this.parseReadyClaim(process.meeting_session)
+ ) {
+ throw new ConflictException(
+ 'A reunião ainda está sendo iniciada. Tente novamente em instantes.',
+ );
+ }
+
if (process.meeting_session.ended_at) {
return {
meeting: this.buildMeetingResponse(process.meeting_session),
diff --git a/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts b/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts
index c857f89..f22ba03 100644
--- a/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts
+++ b/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts
@@ -484,4 +484,84 @@ describeWithPostgres('process rejection CAS — PostgreSQL concurrency', () => {
expect(notifications.sendMeetingStartedEmail).toHaveBeenCalledTimes(1);
expect(notifications.sendMeetingAdvancedEmail).not.toHaveBeenCalled();
}, 15_000);
+
+ it('libera pool connection_limit=1 durante provider e impede start/e-mail duplicado', async () => {
+ await completionClient.process.create({
+ data: {
+ id: processId,
+ client_id: clientId,
+ specialist_id: specialistId,
+ status: ProcessStatus.SCHEDULING,
+ },
+ });
+
+ const providerEntered = deferred();
+ const releaseProvider = deferred();
+ const notifications = meetingNotifications();
+ const oauth = {
+ getAccessToken: jest.fn().mockImplementation(async () => {
+ // Este client tem connection_limit=1. Se a transação do claim ainda
+ // estiver aberta, a própria leitura do OAuth esgota o pool.
+ await completionClient.user.count({ where: { id: specialistId } });
+ providerEntered.resolve();
+ await releaseProvider.promise;
+ return 'access-token';
+ }),
+ } as any;
+ const config = {
+ get: jest.fn((key: string, fallback?: string) => {
+ if (key === 'MEETING_PROVIDER') return 'GOOGLE';
+ if (key === 'MEETING_DEMO_FALLBACK_ENABLED') return 'false';
+ if (key === 'GOOGLE_MEET_ACCESS_TYPE') return 'OPEN';
+ return fallback;
+ }),
+ } as any;
+ const originalFetch = global.fetch;
+ const fetchMock = jest.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ name: `spaces/${suffix}`,
+ meetingUri: `https://meet.google.com/${suffix.slice(0, 10)}`,
+ }),
+ });
+ global.fetch = fetchMock as any;
+
+ try {
+ const meetingsService = new MeetingsService(
+ completionClient as any,
+ config,
+ notifications,
+ oauth,
+ );
+ const firstStart = meetingsService.startMeetingForProcess(
+ processId,
+ specialistId,
+ );
+ await providerEntered.promise;
+
+ await expect(
+ meetingsService.startMeetingForProcess(processId, specialistId),
+ ).rejects.toBeInstanceOf(ConflictException);
+
+ releaseProvider.resolve();
+ await expect(firstStart).resolves.toMatchObject({ is_active: true });
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(oauth.getAccessToken).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ await expect(
+ completionClient.meetingSession.findUniqueOrThrow({
+ where: { process_id: processId },
+ }),
+ ).resolves.toMatchObject({
+ calendar_event_id: `spaces/${suffix}`,
+ meet_link: `https://meet.google.com/${suffix.slice(0, 10)}`,
+ });
+ expect(notifications.sendMeetingStartedEmail).toHaveBeenCalledTimes(1);
+ expect(notifications.sendMeetingAdvancedEmail).not.toHaveBeenCalled();
+ } finally {
+ global.fetch = originalFetch;
+ releaseProvider.resolve();
+ }
+ }, 15_000);
});
From e2deb6176319c8575eda08365a9b193f07404b48 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:23:30 -0300
Subject: [PATCH 39/60] fix(appointments): retry pending Calendly sync
---
.../appointments/appointments.service.spec.ts | 77 +++++++-
.../appointments/appointments.service.ts | 51 ++---
.../calendly-integration.service.spec.ts | 36 ++++
.../calendly-integration.service.ts | 19 ++
.../StartProcessForClientModal.test.tsx | 71 ++++++-
.../processes/StartProcessForClientModal.tsx | 24 ++-
.../src/hooks/useCalendlyScheduling.test.tsx | 174 ++++++++++++++++++
frontend/src/hooks/useCalendlyScheduling.ts | 98 +++++-----
.../src/pages/profile/ProfilePage.test.tsx | 17 ++
frontend/src/pages/profile/ProfilePage.tsx | 10 +
frontend/src/services/appointments.service.ts | 13 +-
frontend/src/services/calendly-sync.ts | 78 ++++++++
12 files changed, 585 insertions(+), 83 deletions(-)
create mode 100644 frontend/src/hooks/useCalendlyScheduling.test.tsx
create mode 100644 frontend/src/services/calendly-sync.ts
diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts
index c11f955..841a32d 100644
--- a/backend/src/features/appointments/appointments.service.spec.ts
+++ b/backend/src/features/appointments/appointments.service.spec.ts
@@ -1799,7 +1799,8 @@ 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_invitee_uri:
+ 'https://calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1',
calendly_sync_status: 'SYNCED',
appointment_datetime: new Date('2099-01-01T10:00:00.000Z'),
};
@@ -1837,7 +1838,7 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
where: {
id: appointment.id,
calendly_event_uri: appointment.calendly_event_uri,
- calendly_invitee_uri: null,
+ calendly_invitee_uri: appointment.calendly_invitee_uri,
},
data: {
calendly_event_uri:
@@ -1849,6 +1850,78 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
expect(prisma.$transaction).not.toHaveBeenCalled();
});
+ it('não deixa invitee injetado envenenar evento confiável sem convidado e aceita o genuíno depois', async () => {
+ const trustedDate = new Date('2099-01-01T10:00:00.000Z');
+ 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://api.calendly.com/scheduled_events/group-event',
+ calendly_invitee_uri: null,
+ calendly_sync_status: 'SYNCED',
+ appointment_datetime: trustedDate,
+ };
+ let stored = { ...appointment };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn(async () => ({ ...stored })),
+ findFirst: jest.fn().mockResolvedValue(null),
+ update: jest.fn(async ({ data }) => {
+ stored = { ...stored, ...data };
+ return { ...stored };
+ }),
+ },
+ };
+ const prisma = {
+ appointment: {
+ findUnique: jest.fn(async () => ({ ...stored })),
+ updateMany: jest.fn(),
+ },
+ $transaction: jest.fn(async (callback: any) => callback(tx)),
+ } as any;
+ const resolveScheduledStartTime = jest
+ .fn()
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce(trustedDate);
+ const service = new AppointmentsService(prisma, {} as any, {
+ resolveScheduledStartTime,
+ } as any);
+
+ await expect(
+ service.registerCalendlyScheduled(appointment.id, appointment.client_id, {
+ event_uri: appointment.calendly_event_uri,
+ invitee_uri:
+ 'https://api.calendly.com/scheduled_events/group-event/invitees/poison',
+ }),
+ ).resolves.toMatchObject({
+ calendly_sync_status: 'SYNCED',
+ appointment_datetime: trustedDate,
+ });
+ expect(stored.calendly_invitee_uri).toBeNull();
+ expect(prisma.appointment.updateMany).not.toHaveBeenCalled();
+ expect(tx.appointment.update).not.toHaveBeenCalled();
+
+ await expect(
+ service.registerCalendlyScheduled(appointment.id, appointment.client_id, {
+ event_uri: appointment.calendly_event_uri,
+ invitee_uri:
+ 'https://api.calendly.com/scheduled_events/group-event/invitees/genuine',
+ }),
+ ).resolves.toMatchObject({
+ calendly_sync_status: 'SYNCED',
+ appointment_datetime: trustedDate,
+ });
+ expect(resolveScheduledStartTime).toHaveBeenCalledTimes(2);
+ expect(stored.calendly_invitee_uri).toBe(
+ 'https://api.calendly.com/scheduled_events/group-event/invitees/genuine',
+ );
+ });
+
it('reconsulta o Calendly ao repetir a mesma associação ainda PENDING e promove para SYNCED', async () => {
const resolvedDate = new Date('2099-01-03T14:00:00.000Z');
const appointment = {
diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts
index 6826acb..f768863 100644
--- a/backend/src/features/appointments/appointments.service.ts
+++ b/backend/src/features/appointments/appointments.service.ts
@@ -1951,37 +1951,40 @@ export class AppointmentsService {
parseCalendlyResourceUri(appointment.calendly_event_uri, 'event')
?.canonicalUri === eventUri
) {
+ const storedInviteeReference = appointment.calendly_invitee_uri
+ ? parseCalendlyResourceUri(
+ appointment.calendly_invitee_uri,
+ 'invitee',
+ )
+ : null;
if (
appointment.calendly_invitee_uri &&
- parseCalendlyResourceUri(
- appointment.calendly_invitee_uri,
- 'invitee',
- )?.canonicalUri !== inviteeUri
+ storedInviteeReference?.canonicalUri !== inviteeUri
) {
throw new ConflictException(
'O evento do Calendly já está associado a outro convidado',
);
}
- 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) {
- if (this.hasTrustedCalendlySchedule(appointment)) {
+ if (storedInviteeReference?.canonicalUri === inviteeUri) {
+ 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 && this.hasTrustedCalendlySchedule(appointment)) {
return {
appointment_id: appointment.id,
calendly_sync_status: appointment.calendly_sync_status,
diff --git a/backend/src/features/appointments/calendly-integration.service.spec.ts b/backend/src/features/appointments/calendly-integration.service.spec.ts
index 1966500..19d5da5 100644
--- a/backend/src/features/appointments/calendly-integration.service.spec.ts
+++ b/backend/src/features/appointments/calendly-integration.service.spec.ts
@@ -68,6 +68,31 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
return { prisma, service: new CalendlyIntegrationService(prisma as any) };
}
+ it('expõe degradação da subscription sem desconectar o OAuth', async () => {
+ const prisma = {
+ calendlyConnection: {
+ findUnique: jest.fn().mockResolvedValue({
+ is_active: true,
+ calendly_user_uri: 'https://api.calendly.com/users/1',
+ expires_at: null,
+ last_error: 'webhook_subscription_failed',
+ }),
+ },
+ };
+
+ await expect(
+ new CalendlyIntegrationService(prisma as any).getOAuthStatus(
+ 'specialist-1',
+ ),
+ ).resolves.toEqual({
+ connected: true,
+ calendly_user_uri: 'https://api.calendly.com/users/1',
+ expires_at: null,
+ is_active: true,
+ last_error: 'webhook_subscription_failed',
+ });
+ });
+
it('persiste scheduling_url validada no callback OAuth', async () => {
const { prisma, service } = makeCallbackService(
'https://calendly.com/ana/reuniao',
@@ -127,6 +152,7 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
Object.assign(prisma.calendlyConnection, {
findUnique: jest.fn().mockResolvedValue(connection),
update: jest.fn(),
+ updateMany: jest.fn().mockResolvedValue({ count: 1 }),
});
jest
.mocked(axios.post)
@@ -147,6 +173,16 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
expect(
(prisma.calendlyConnection as any).update,
).not.toHaveBeenCalled();
+ expect(
+ (prisma.calendlyConnection as any).updateMany,
+ ).toHaveBeenCalledWith({
+ where: {
+ id: connection.id,
+ access_token_encrypted: connection.access_token_encrypted,
+ is_active: true,
+ },
+ data: { last_error: 'webhook_subscription_failed' },
+ });
});
it('desativa e limpa URL e URIs em uma transação', async () => {
diff --git a/backend/src/features/appointments/calendly-integration.service.ts b/backend/src/features/appointments/calendly-integration.service.ts
index 32b1a29..27c1019 100644
--- a/backend/src/features/appointments/calendly-integration.service.ts
+++ b/backend/src/features/appointments/calendly-integration.service.ts
@@ -126,6 +126,7 @@ export class CalendlyIntegrationService {
calendly_user_uri: string | null;
expires_at: Date | null;
is_active: boolean;
+ last_error: string | null;
}> {
const connection = await this.prisma.calendlyConnection.findUnique({
where: { user_id: userId },
@@ -133,6 +134,7 @@ export class CalendlyIntegrationService {
is_active: true,
calendly_user_uri: true,
expires_at: true,
+ last_error: true,
},
});
@@ -142,6 +144,7 @@ export class CalendlyIntegrationService {
calendly_user_uri: null,
expires_at: null,
is_active: false,
+ last_error: null,
};
}
@@ -150,6 +153,7 @@ export class CalendlyIntegrationService {
calendly_user_uri: connection.calendly_user_uri,
expires_at: connection.expires_at,
is_active: connection.is_active,
+ last_error: connection.last_error,
};
}
@@ -260,6 +264,21 @@ export class CalendlyIntegrationService {
this.logger.warn(
`Falha ao criar webhook Calendly (não crítico): ${error?.message}`,
);
+ try {
+ await this.prisma.calendlyConnection.updateMany({
+ where: {
+ id: upsertedConnection.id,
+ access_token_encrypted:
+ upsertedConnection.access_token_encrypted,
+ is_active: true,
+ },
+ data: { last_error: 'webhook_subscription_failed' },
+ });
+ } catch (persistError: any) {
+ this.logger.warn(
+ `Falha ao registrar degradação do webhook Calendly: ${persistError?.message}`,
+ );
+ }
}
return stateRecord.user_id;
diff --git a/frontend/src/components/processes/StartProcessForClientModal.test.tsx b/frontend/src/components/processes/StartProcessForClientModal.test.tsx
index 546db81..3d8555e 100644
--- a/frontend/src/components/processes/StartProcessForClientModal.test.tsx
+++ b/frontend/src/components/processes/StartProcessForClientModal.test.tsx
@@ -58,7 +58,7 @@ describe("StartProcessForClientModal capability", () => {
vi.mocked(registerCalendlyScheduledEvent).mockResolvedValue({} as never);
vi.mocked(getCalendlySyncStatus).mockResolvedValue({} as never);
});
- afterEach(() => { cleanup(); vi.resetAllMocks(); });
+ afterEach(() => { cleanup(); vi.resetAllMocks(); vi.useRealTimers(); });
it.each(["CONSULTANT", "OFFICE"] as const)("ignores a stale URL when capability is false in %s mode", async (mode) => {
renderModal(mode);
@@ -250,6 +250,75 @@ describe("StartProcessForClientModal capability", () => {
expect(screen.getByTestId("location").textContent).toBe("/start");
});
+ it("retries the same Calendly registration after PENDING before redirecting", async () => {
+ vi.mocked(getPublicSpecialistById).mockResolvedValue({
+ ...specialist,
+ calendly_scheduling_available: true,
+ });
+ vi.mocked(registerCalendlyScheduledEvent)
+ .mockResolvedValueOnce({
+ appointment_id: "appointment-1",
+ calendly_sync_status: "PENDING",
+ appointment_datetime: null,
+ })
+ .mockResolvedValueOnce({
+ appointment_id: "appointment-1",
+ calendly_sync_status: "SYNCED",
+ appointment_datetime: "2099-01-01T10:00:00.000Z",
+ });
+ vi.mocked(getCalendlySyncStatus)
+ .mockResolvedValueOnce({
+ appointment_id: "appointment-1",
+ status: "PENDING",
+ calendly_sync_status: "PENDING",
+ appointment_datetime: null,
+ calendly_last_sync_at: null,
+ })
+ .mockResolvedValueOnce({
+ appointment_id: "appointment-1",
+ status: "SCHEDULED",
+ calendly_sync_status: "SYNCED",
+ appointment_datetime: "2099-01-01T10:00:00.000Z",
+ calendly_last_sync_at: "2099-01-01T09:59:00.000Z",
+ });
+ renderModal();
+ await selectAndCreate();
+ await screen.findByRole("link", { name: "Agendar no Calendly" });
+ vi.useFakeTimers();
+ const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
+ .onEventScheduled!;
+ act(() => {
+ void Promise.resolve(
+ listener({
+ data: {
+ event: "calendly.event_scheduled",
+ payload: {
+ event: { uri: "event-uri" },
+ invitee: { uri: "invitee-uri" },
+ },
+ },
+ } as Parameters[0]),
+ );
+ });
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ await Promise.resolve();
+ });
+
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(2);
+ expect(vi.mocked(registerCalendlyScheduledEvent).mock.calls[0][1]).toEqual(
+ vi.mocked(registerCalendlyScheduledEvent).mock.calls[1][1],
+ );
+ expect(screen.getByText("Processos do consultor")).toBeTruthy();
+ vi.useRealTimers();
+ });
+
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 }));
diff --git a/frontend/src/components/processes/StartProcessForClientModal.tsx b/frontend/src/components/processes/StartProcessForClientModal.tsx
index 9167eca..b83a901 100644
--- a/frontend/src/components/processes/StartProcessForClientModal.tsx
+++ b/frontend/src/components/processes/StartProcessForClientModal.tsx
@@ -4,10 +4,8 @@ import { PopupModal, useCalendlyEventListener } from "react-calendly";
import { getClients, createConsultantProcess, type Client } from "../../services/consultant.service";
import { officeService } from "../../services/office";
import { getPublicSpecialistById, type PublicSpecialistProfile } from "../../services/specialists.service";
-import {
- registerCalendlyScheduledEvent,
- getCalendlySyncStatus,
-} from "../../services/appointments.service";
+import type { RegisterCalendlyScheduledPayload } from "../../services/appointments.service";
+import { synchronizeCalendlyRegistration } from "../../services/calendly-sync";
import Button from "../../components/ui/button";
import { Loader2, Search } from "lucide-react";
@@ -79,6 +77,7 @@ function StartProcessForClientModalInner({
const submittingRef = useRef(false);
const mountedRef = useRef(false);
const operationGeneration = useRef(0);
+ const syncAbortRef = useRef(null);
const busyCallbackRef = useRef(onBusyChange);
const calendlyOpenCallbackRef = useRef(onCalendlyOpenChange);
const [pendingOperation, setPendingOperation] = useState<{
@@ -100,6 +99,7 @@ function StartProcessForClientModalInner({
return () => {
mountedRef.current = false;
operationGeneration.current += 1;
+ syncAbortRef.current?.abort();
calendlyOpenCallbackRef.current?.(false);
busyCallbackRef.current?.(false);
};
@@ -167,15 +167,20 @@ function StartProcessForClientModalInner({
try {
if (eventUri && inviteeUri) {
- await registerCalendlyScheduledEvent(pending.appointmentId, {
+ const registrationPayload: RegisterCalendlyScheduledPayload = {
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(pending.appointmentId).catch(() => null);
+ };
+ syncAbortRef.current?.abort();
+ const syncController = new AbortController();
+ syncAbortRef.current = syncController;
+ await synchronizeCalendlyRegistration(
+ pending.appointmentId,
+ registrationPayload,
+ { signal: syncController.signal },
+ );
if (!isCurrentOperation(pending.generation)) return;
}
} catch (err) {
@@ -343,6 +348,7 @@ function StartProcessForClientModalInner({
onModalClose={() => {
if (!pendingOperation || !isCurrentOperation(pendingOperation.generation)) return;
operationGeneration.current += 1;
+ syncAbortRef.current?.abort();
setCalendlyOpen(false);
setPendingOperation(null);
submittingRef.current = false;
diff --git a/frontend/src/hooks/useCalendlyScheduling.test.tsx b/frontend/src/hooks/useCalendlyScheduling.test.tsx
new file mode 100644
index 0000000..14ff1fe
--- /dev/null
+++ b/frontend/src/hooks/useCalendlyScheduling.test.tsx
@@ -0,0 +1,174 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useCalendlyEventListener } from "react-calendly";
+import {
+ getCalendlySyncStatus,
+ registerCalendlyScheduledEvent,
+} from "../services/appointments.service";
+import { useCalendlyScheduling } from "./useCalendlyScheduling";
+
+const { navigate } = vi.hoisted(() => ({ navigate: vi.fn() }));
+
+vi.mock("react-router-dom", async (importOriginal) => ({
+ ...(await importOriginal()),
+ useNavigate: () => navigate,
+}));
+vi.mock("react-calendly", () => ({ useCalendlyEventListener: vi.fn() }));
+vi.mock("../services/appointments.service", () => ({
+ cancelPendingAppointment: vi.fn(),
+ getCalendlySyncStatus: vi.fn(),
+ registerCalendlyScheduledEvent: vi.fn(),
+}));
+
+const payload = {
+ event_uri: "https://api.calendly.com/scheduled_events/event-1",
+ invitee_uri:
+ "https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1",
+};
+const pendingStatus = {
+ appointment_id: "appointment-1",
+ status: "PENDING" as const,
+ calendly_sync_status: "PENDING" as const,
+ appointment_datetime: null,
+ calendly_last_sync_at: null,
+};
+const syncedStatus = {
+ ...pendingStatus,
+ status: "SCHEDULED" as const,
+ calendly_sync_status: "SYNCED" as const,
+ appointment_datetime: "2099-01-01T10:00:00.000Z",
+};
+
+function scheduledEvent() {
+ return {
+ data: {
+ event: "calendly.event_scheduled",
+ payload: {
+ event: { uri: payload.event_uri },
+ invitee: { uri: payload.invitee_uri },
+ },
+ },
+ } as any;
+}
+
+async function flushPromises() {
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+describe("useCalendlyScheduling active registration retry", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ });
+
+ it("reenvia as mesmas URIs após PENDING e conclui quando o POST posterior sincroniza", async () => {
+ vi.mocked(registerCalendlyScheduledEvent)
+ .mockResolvedValueOnce({
+ appointment_id: "appointment-1",
+ calendly_sync_status: "PENDING",
+ appointment_datetime: null,
+ })
+ .mockResolvedValueOnce({
+ appointment_id: "appointment-1",
+ calendly_sync_status: "SYNCED",
+ appointment_datetime: syncedStatus.appointment_datetime,
+ });
+ vi.mocked(getCalendlySyncStatus)
+ .mockResolvedValueOnce(pendingStatus)
+ .mockResolvedValueOnce(syncedStatus);
+ const onSynced = vi.fn();
+ const { result } = renderHook(() =>
+ useCalendlyScheduling({
+ successRedirectMessage: "ok",
+ onSynced,
+ }),
+ );
+ act(() => result.current.openPopup("appointment-1", "https://calendly.com/a"));
+ const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
+ .onEventScheduled!;
+ act(() => {
+ void listener(scheduledEvent());
+ });
+ await flushPromises();
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ await Promise.resolve();
+ });
+
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(2);
+ expect(vi.mocked(registerCalendlyScheduledEvent).mock.calls[0][1]).toEqual(
+ vi.mocked(registerCalendlyScheduledEvent).mock.calls[1][1],
+ );
+ expect(onSynced).toHaveBeenCalledWith(syncedStatus);
+ });
+
+ it("interrompe backoff e chamadas HTTP ao desmontar", async () => {
+ vi.mocked(registerCalendlyScheduledEvent).mockResolvedValue({
+ appointment_id: "appointment-1",
+ calendly_sync_status: "PENDING",
+ appointment_datetime: null,
+ });
+ vi.mocked(getCalendlySyncStatus).mockResolvedValue(pendingStatus);
+ const { result, unmount } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ );
+ act(() => result.current.openPopup("appointment-1", "https://calendly.com/a"));
+ const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
+ .onEventScheduled!;
+ act(() => {
+ void listener(scheduledEvent());
+ });
+ await flushPromises();
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(1);
+ expect(getCalendlySyncStatus).toHaveBeenCalledTimes(1);
+
+ unmount();
+ await vi.runAllTimersAsync();
+
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(1);
+ expect(getCalendlySyncStatus).toHaveBeenCalledTimes(1);
+ expect(navigate).not.toHaveBeenCalled();
+ });
+
+ it("encerra após oito tentativas sem criar loop de retry", async () => {
+ vi.mocked(registerCalendlyScheduledEvent).mockResolvedValue({
+ appointment_id: "appointment-1",
+ calendly_sync_status: "PENDING",
+ appointment_datetime: null,
+ });
+ vi.mocked(getCalendlySyncStatus).mockResolvedValue(pendingStatus);
+ const { result } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ );
+ act(() => result.current.openPopup("appointment-1", "https://calendly.com/a"));
+ const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
+ .onEventScheduled!;
+ let synchronization!: Promise;
+ act(() => {
+ synchronization = Promise.resolve(listener(scheduledEvent()));
+ });
+
+ await act(async () => {
+ await vi.runAllTimersAsync();
+ await synchronization;
+ });
+
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(8);
+ expect(getCalendlySyncStatus).toHaveBeenCalledTimes(8);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(8);
+ });
+});
diff --git a/frontend/src/hooks/useCalendlyScheduling.ts b/frontend/src/hooks/useCalendlyScheduling.ts
index f27d467..dd7b998 100644
--- a/frontend/src/hooks/useCalendlyScheduling.ts
+++ b/frontend/src/hooks/useCalendlyScheduling.ts
@@ -1,12 +1,12 @@
-import { useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useCalendlyEventListener } from "react-calendly";
import {
cancelPendingAppointment,
- getCalendlySyncStatus,
- registerCalendlyScheduledEvent,
type CalendlySyncStatus,
+ type RegisterCalendlyScheduledPayload,
} from "../services/appointments.service";
+import { synchronizeCalendlyRegistration } from "../services/calendly-sync";
export type CalendlySyncState =
| "idle"
@@ -50,37 +50,18 @@ export function useCalendlyScheduling({
const [syncState, setSyncState] = useState("idle");
const [syncMessage, setSyncMessage] = useState("");
const confirmedRef = useRef(false);
-
- const pollCalendlySyncStatus = async (appointmentId: string) => {
- const maxAttempts = 8;
- const intervalMs = 3500;
-
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
- const status = await getCalendlySyncStatus(appointmentId);
-
- if (status.calendly_sync_status === "SYNCED" || status.appointment_datetime) {
- onSynced?.(status);
- setSyncState("done");
- setSyncMessage(
- "Agendamento recebido! Você pode acompanhar os detalhes em Meus Processos.",
- );
-
- setTimeout(() => {
- navigate("/customer/processes", {
- state: { message: successRedirectMessage },
- });
- }, 900);
- return;
- }
-
- await new Promise((resolve) => setTimeout(resolve, intervalMs));
- }
-
- setSyncState("done");
- setSyncMessage(
- "Solicitação registrada. Estamos finalizando a sincronização do horário com o calendário.",
- );
- };
+ const mountedRef = useRef(false);
+ const syncAbortRef = useRef(null);
+ const navigateTimerRef = useRef | null>(null);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ syncAbortRef.current?.abort();
+ if (navigateTimerRef.current) clearTimeout(navigateTimerRef.current);
+ };
+ }, []);
useCalendlyEventListener({
onEventScheduled: async (event) => {
@@ -107,33 +88,64 @@ export function useCalendlyScheduling({
// Calendly e a resposta do nosso backend — nesse intervalo o registro
// NÃO pode ser tratado como abandono e cancelado.
confirmedRef.current = true;
+ const registrationPayload: RegisterCalendlyScheduledPayload = {
+ event_uri: eventUri,
+ invitee_uri: inviteeUri,
+ client_event: "calendly.event_scheduled",
+ client_observed_at: new Date().toISOString(),
+ };
+ syncAbortRef.current?.abort();
+ const syncController = new AbortController();
+ syncAbortRef.current = syncController;
try {
setSyncState("syncing");
setSyncMessage("Sincronizando seu agendamento...");
- await registerCalendlyScheduledEvent(pendingAppointmentId, {
- event_uri: eventUri,
- invitee_uri: inviteeUri,
- client_event: "calendly.event_scheduled",
- client_observed_at: new Date().toISOString(),
- });
+ const status = await synchronizeCalendlyRegistration(
+ pendingAppointmentId,
+ registrationPayload,
+ { signal: syncController.signal },
+ );
+ if (!mountedRef.current || syncController.signal.aborted || !status) return;
setIsModalOpen(false);
- await pollCalendlySyncStatus(pendingAppointmentId);
+ if (
+ status.calendly_sync_status === "SYNCED" ||
+ status.appointment_datetime
+ ) {
+ onSynced?.(status);
+ setSyncState("done");
+ setSyncMessage(
+ "Agendamento recebido! Você pode acompanhar os detalhes em Meus Processos.",
+ );
+ navigateTimerRef.current = setTimeout(() => {
+ if (!mountedRef.current) return;
+ navigate("/customer/processes", {
+ state: { message: successRedirectMessage },
+ });
+ }, 900);
+ } else {
+ setSyncState("done");
+ setSyncMessage(
+ "Solicitação registrada. Estamos finalizando a sincronização do horário com o calendário.",
+ );
+ }
} catch (err) {
// O agendamento já aconteceu de verdade no Calendly (confirmedRef já
// é true) — só a nossa sincronização falhou. Não deixar o usuário
// preso num popup fechado/stale: fecha e manda pra Meus Processos,
// igual ao fluxo de sucesso, só que com aviso de que pode faltar
// atualizar a página.
+ if (!mountedRef.current || syncController.signal.aborted) return;
console.error("Erro ao sincronizar evento do Calendly:", err);
setSyncState("error");
setSyncMessage(
"Agendamento confirmado no Calendly, mas houve falha ao sincronizar com a plataforma. Redirecionando para Meus Processos...",
);
setIsModalOpen(false);
- setTimeout(() => {
+ navigateTimerRef.current = setTimeout(() => {
+ if (!mountedRef.current) return;
navigate("/customer/processes", {
state: {
message:
@@ -147,6 +159,8 @@ export function useCalendlyScheduling({
/** Seta o agendamento pendente em foco, abre o popup do Calendly. */
const openPopup = (appointmentId: string, calendlyUrl: string) => {
+ syncAbortRef.current?.abort();
+ if (navigateTimerRef.current) clearTimeout(navigateTimerRef.current);
confirmedRef.current = false;
setPendingAppointmentId(appointmentId);
setModalUrl(calendlyUrl);
diff --git a/frontend/src/pages/profile/ProfilePage.test.tsx b/frontend/src/pages/profile/ProfilePage.test.tsx
index d38a413..79fb03e 100644
--- a/frontend/src/pages/profile/ProfilePage.test.tsx
+++ b/frontend/src/pages/profile/ProfilePage.test.tsx
@@ -45,6 +45,23 @@ describe("ProfilePage Calendly payload", () => {
await waitFor(() => expect(updateUser).toHaveBeenCalledWith(profile.id, expect.objectContaining({ calendly_url: "https://calendly.com/ana/novo" })));
});
+ it("shows webhook degradation without presenting OAuth as disconnected", async () => {
+ vi.mocked(getCalendlyOAuthStatus).mockResolvedValue({
+ connected: true,
+ calendly_user_uri: "https://api.calendly.com/users/1",
+ expires_at: null,
+ is_active: true,
+ last_error: "webhook_subscription_failed",
+ });
+
+ renderPage();
+
+ expect(await screen.findByText("Status: Conectado")).toBeTruthy();
+ expect(
+ screen.getByText(/sincronização automática.*degradada/i),
+ ).toBeTruthy();
+ });
+
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" });
diff --git a/frontend/src/pages/profile/ProfilePage.tsx b/frontend/src/pages/profile/ProfilePage.tsx
index 31dfb2a..4795c7f 100644
--- a/frontend/src/pages/profile/ProfilePage.tsx
+++ b/frontend/src/pages/profile/ProfilePage.tsx
@@ -604,6 +604,16 @@ export default function CustomerProfilePage() {
? "Conectado"
: "Não conectado"}
+ {calendlyOAuthStatus?.connected &&
+ calendlyOAuthStatus.last_error && (
+
+ A sincronização automática está degradada. Reconecte o
+ Calendly para tentar restaurá-la.
+
+ )}
{
+): Promise {
const response = await api.post<
ApiResponse<{
appointment_id: string;
diff --git a/frontend/src/services/calendly-sync.ts b/frontend/src/services/calendly-sync.ts
new file mode 100644
index 0000000..20dcfd0
--- /dev/null
+++ b/frontend/src/services/calendly-sync.ts
@@ -0,0 +1,78 @@
+import {
+ getCalendlySyncStatus,
+ registerCalendlyScheduledEvent,
+ type CalendlySyncStatus,
+ type RegisterCalendlyScheduledPayload,
+} from "./appointments.service";
+
+export const CALENDLY_SYNC_MAX_ATTEMPTS = 8;
+export const CALENDLY_SYNC_BASE_DELAY_MS = 500;
+const CALENDLY_SYNC_MAX_DELAY_MS = 3500;
+
+function isSynced(status: CalendlySyncStatus): boolean {
+ return (
+ status.calendly_sync_status === "SYNCED" ||
+ Boolean(status.appointment_datetime)
+ );
+}
+
+function waitForRetry(delayMs: number, signal?: AbortSignal): Promise {
+ if (signal?.aborted) return Promise.resolve(false);
+
+ return new Promise((resolve) => {
+ let settled = false;
+ function finish(completed: boolean) {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ signal?.removeEventListener("abort", abort);
+ resolve(completed);
+ }
+ function abort() {
+ finish(false);
+ }
+ const timeout = setTimeout(() => finish(true), delayMs);
+ signal?.addEventListener("abort", abort, { once: true });
+ });
+}
+
+export async function synchronizeCalendlyRegistration(
+ appointmentId: string,
+ payload: RegisterCalendlyScheduledPayload,
+ options: {
+ signal?: AbortSignal;
+ maxAttempts?: number;
+ } = {},
+): Promise {
+ const maxAttempts = options.maxAttempts ?? CALENDLY_SYNC_MAX_ATTEMPTS;
+ let lastStatus: CalendlySyncStatus | null = null;
+ let lastError: unknown;
+
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
+ if (options.signal?.aborted) return null;
+
+ try {
+ await registerCalendlyScheduledEvent(appointmentId, payload);
+ } catch (error) {
+ lastError = error;
+ }
+ if (options.signal?.aborted) return null;
+
+ try {
+ lastStatus = await getCalendlySyncStatus(appointmentId);
+ if (isSynced(lastStatus)) return lastStatus;
+ } catch (error) {
+ lastError = error;
+ }
+
+ if (attempt === maxAttempts - 1) break;
+ const delayMs = Math.min(
+ CALENDLY_SYNC_BASE_DELAY_MS * 2 ** attempt,
+ CALENDLY_SYNC_MAX_DELAY_MS,
+ );
+ if (!(await waitForRetry(delayMs, options.signal))) return null;
+ }
+
+ if (lastStatus) return lastStatus;
+ throw lastError ?? new Error("Não foi possível sincronizar o Calendly");
+}
From eecb5d69a04358be47a8f83ac01423efa5813b5f Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:23:47 -0300
Subject: [PATCH 40/60] fix(processes): surface safe rejection errors
---
.../components/processes/ProcessCard.test.tsx | 33 +++++++++++++++++++
.../processes/UpdateProcessStatusModal.tsx | 28 ++++++++++++----
2 files changed, 55 insertions(+), 6 deletions(-)
diff --git a/frontend/src/components/processes/ProcessCard.test.tsx b/frontend/src/components/processes/ProcessCard.test.tsx
index 0df3035..019d966 100644
--- a/frontend/src/components/processes/ProcessCard.test.tsx
+++ b/frontend/src/components/processes/ProcessCard.test.tsx
@@ -617,6 +617,39 @@ describe("ProcessCard appointment time actions", () => {
expect(onStatusUpdated).not.toHaveBeenCalled();
});
+ it.each([
+ {
+ error: Object.assign(new Error("Request failed with status code 500"), {
+ friendlyMessage: "Serviço temporariamente indisponível. Tente novamente em instantes.",
+ response: { data: { message: "internal database detail" } },
+ }),
+ expected: "Serviço temporariamente indisponível. Tente novamente em instantes.",
+ },
+ {
+ error: Object.assign(new Error("Request failed with status code 409"), {
+ response: { data: { message: "Este processo já foi rejeitado." } },
+ }),
+ expected: "Este processo já foi rejeitado.",
+ },
+ ])("shows the safe rejection API message instead of the Axios transport message", async ({ error, expected }) => {
+ vi.mocked(rejectProcess).mockRejectedValue(error);
+ renderCard({
+ ...baseProcess,
+ status: "DOCUMENTATION",
+ appointment_status: "CANCELLED",
+ });
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Recusar processo" }),
+ );
+ fireEvent.click(
+ screen.getByRole("button", { name: "Confirmar Rejeição" }),
+ );
+
+ expect(await screen.findByText(expected)).toBeTruthy();
+ expect(screen.queryByText(error.message)).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/UpdateProcessStatusModal.tsx b/frontend/src/components/processes/UpdateProcessStatusModal.tsx
index 7d1c033..5106623 100644
--- a/frontend/src/components/processes/UpdateProcessStatusModal.tsx
+++ b/frontend/src/components/processes/UpdateProcessStatusModal.tsx
@@ -23,6 +23,26 @@ interface UpdateProcessFormData {
notes?: string;
}
+function getProcessActionErrorMessage(error: unknown, fallback: string): string {
+ if (typeof error !== "object" || error === null) return fallback;
+
+ const candidate = error as {
+ friendlyMessage?: unknown;
+ response?: { data?: { message?: unknown } };
+ message?: unknown;
+ };
+
+ for (const message of [
+ candidate.friendlyMessage,
+ candidate.response?.data?.message,
+ candidate.message,
+ ]) {
+ if (typeof message === "string" && message.trim()) return message;
+ }
+
+ return fallback;
+}
+
/**
* Keeps the sole manual status transition separate from process rejection.
*/
@@ -69,9 +89,7 @@ export default function UpdateProcessStatusModal({
onClose();
onSuccess?.();
} catch (err) {
- setError(
- err instanceof Error ? err.message : "Erro ao atualizar processo"
- );
+ setError(getProcessActionErrorMessage(err, "Erro ao atualizar processo"));
} finally {
setIsSubmitting(false);
}
@@ -92,9 +110,7 @@ export default function UpdateProcessStatusModal({
onClose();
onSuccess?.();
} catch (err) {
- setError(
- err instanceof Error ? err.message : "Erro ao rejeitar processo"
- );
+ setError(getProcessActionErrorMessage(err, "Erro ao rejeitar processo"));
} finally {
rejectionInFlight.current = false;
setIsSubmitting(false);
From 4a01a3bde84285ddef769218c34207e1bbe250f2 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:27:13 -0300
Subject: [PATCH 41/60] fix(meetings): bound provider deadline and recover
stale claims
---
.../meetings/meeting-initialization-claim.ts | 72 +++++++++
.../meetings/meetings.service.spec.ts | 139 +++++++++++++++-
.../src/features/meetings/meetings.service.ts | 151 ++++++++----------
...ses-rejection-concurrency.postgres.spec.ts | 41 +++++
.../processes/processes.service.spec.ts | 65 ++++++++
.../features/processes/processes.service.ts | 33 +++-
6 files changed, 409 insertions(+), 92 deletions(-)
create mode 100644 backend/src/features/meetings/meeting-initialization-claim.ts
diff --git a/backend/src/features/meetings/meeting-initialization-claim.ts b/backend/src/features/meetings/meeting-initialization-claim.ts
new file mode 100644
index 0000000..08325e3
--- /dev/null
+++ b/backend/src/features/meetings/meeting-initialization-claim.ts
@@ -0,0 +1,72 @@
+export const MEETING_INITIALIZATION_PREFIX = 'meeting-init:';
+export const MEETING_READY_PREFIX = 'meeting-ready:';
+export const MEETING_INITIALIZATION_TTL_MS = 2 * 60 * 1000;
+
+type MeetingClaim = {
+ calendar_event_id?: string | null;
+ started_at?: Date | null;
+};
+
+export type ReadyMeetingClaim = {
+ claimId: string;
+ provider: 'JITSI' | 'GOOGLE' | 'DEMO';
+ calendarEventId: string;
+};
+
+export function isMeetingInitializationClaim(
+ meeting: MeetingClaim | null | undefined,
+): boolean {
+ return Boolean(
+ meeting?.calendar_event_id?.startsWith(MEETING_INITIALIZATION_PREFIX),
+ );
+}
+
+export function isStaleMeetingInitializationClaim(
+ meeting: MeetingClaim | null | undefined,
+ now = Date.now(),
+): boolean {
+ if (!isMeetingInitializationClaim(meeting) || !meeting?.started_at) {
+ return false;
+ }
+ const startedAt = meeting.started_at.getTime();
+ return (
+ Number.isFinite(startedAt) &&
+ now - startedAt >= MEETING_INITIALIZATION_TTL_MS
+ );
+}
+
+export function parseReadyMeetingClaim(
+ meeting: MeetingClaim | null | undefined,
+): ReadyMeetingClaim | null {
+ const value = meeting?.calendar_event_id;
+ if (typeof value !== 'string' || !value.startsWith(MEETING_READY_PREFIX)) {
+ return null;
+ }
+ const [claimId, provider, encodedCalendarEventId] = value
+ .slice(MEETING_READY_PREFIX.length)
+ .split(':', 3);
+ if (
+ !claimId ||
+ !encodedCalendarEventId ||
+ !['JITSI', 'GOOGLE', 'DEMO'].includes(provider)
+ ) {
+ return null;
+ }
+ try {
+ return {
+ claimId,
+ provider: provider as ReadyMeetingClaim['provider'],
+ calendarEventId: decodeURIComponent(encodedCalendarEventId),
+ };
+ } catch {
+ return null;
+ }
+}
+
+export function buildReadyMeetingClaim(
+ claimId: string,
+ provider: ReadyMeetingClaim['provider'],
+ calendarEventId: string,
+): string {
+ return `${MEETING_READY_PREFIX}${claimId}:${provider}:${encodeURIComponent(calendarEventId)}`;
+}
diff --git a/backend/src/features/meetings/meetings.service.spec.ts b/backend/src/features/meetings/meetings.service.spec.ts
index f65ea9e..30f275c 100644
--- a/backend/src/features/meetings/meetings.service.spec.ts
+++ b/backend/src/features/meetings/meetings.service.spec.ts
@@ -248,7 +248,7 @@ describe('MeetingsService — criação via Meet REST API', () => {
);
for (
let attempt = 0;
- attempt < 10 && !fetchMock.mock.calls.length;
+ attempt < 50 && !fetchMock.mock.calls.length;
attempt += 1
) {
await Promise.resolve();
@@ -264,6 +264,117 @@ describe('MeetingsService — criação via Meet REST API', () => {
}
});
+ it('aplica a deadline enquanto o OAuth está pendente e não chama o provider', async () => {
+ jest.useFakeTimers();
+ const originalFetch = global.fetch;
+ try {
+ const process = mkProcess();
+ const prisma = mkPrisma(process);
+ let resolveOAuth!: (token: string) => void;
+ const oauth = {
+ getAccessToken: jest.fn().mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveOAuth = resolve;
+ }),
+ ),
+ } as any;
+ const fetchMock = jest.fn();
+ global.fetch = fetchMock as any;
+ const svc = new MeetingsService(
+ prisma,
+ mkConfig('OPEN'),
+ notification,
+ oauth,
+ );
+ let caught: unknown;
+ void svc
+ .startMeetingForProcess('proc-1', 'spec-1')
+ .catch((error) => (caught = error));
+
+ for (
+ let attempt = 0;
+ attempt < 10 && !oauth.getAccessToken.mock.calls.length;
+ attempt += 1
+ ) {
+ await Promise.resolve();
+ }
+ expect(oauth.getAccessToken).toHaveBeenCalledTimes(1);
+ await jest.advanceTimersByTimeAsync(10_000);
+ for (let attempt = 0; attempt < 10 && !caught; attempt += 1) {
+ await Promise.resolve();
+ }
+
+ expect(caught).toBeInstanceOf(ServiceUnavailableException);
+ resolveOAuth('access-token-atrasado');
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(prisma.meetingSession.updateMany).not.toHaveBeenCalled();
+ expect(prisma.meetingSession.deleteMany).toHaveBeenCalled();
+ } finally {
+ global.fetch = originalFetch;
+ jest.useRealTimers();
+ }
+ });
+
+ it('mantém a deadline até terminar o parse do body e não persiste sala atrasada', async () => {
+ jest.useFakeTimers();
+ const originalFetch = global.fetch;
+ try {
+ const process = mkProcess();
+ const prisma = mkPrisma(process);
+ const oauth = {
+ getAccessToken: jest.fn().mockResolvedValue('access-token'),
+ } as any;
+ let resolveJson!: (body: unknown) => void;
+ const json = jest.fn().mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveJson = resolve;
+ }),
+ );
+ const fetchMock = jest.fn().mockResolvedValue({ ok: true, json });
+ global.fetch = fetchMock as any;
+ const svc = new MeetingsService(
+ prisma,
+ mkConfig('OPEN'),
+ notification,
+ oauth,
+ );
+ let caught: unknown;
+ void svc
+ .startMeetingForProcess('proc-1', 'spec-1')
+ .catch((error) => (caught = error));
+
+ for (
+ let attempt = 0;
+ attempt < 50 && !json.mock.calls.length;
+ attempt += 1
+ ) {
+ await Promise.resolve();
+ }
+ expect(json).toHaveBeenCalledTimes(1);
+ await jest.advanceTimersByTimeAsync(10_000);
+ for (let attempt = 0; attempt < 10 && !caught; attempt += 1) {
+ await Promise.resolve();
+ }
+
+ expect(caught).toBeInstanceOf(ServiceUnavailableException);
+ resolveJson({
+ name: 'spaces/atrasada',
+ meetingUri: 'https://meet.google.com/atrasada',
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(prisma.meetingSession.updateMany).not.toHaveBeenCalled();
+ expect(prisma.meetingSession.deleteMany).toHaveBeenCalled();
+ } finally {
+ global.fetch = originalFetch;
+ jest.useRealTimers();
+ }
+ });
+
it('recupera claim pronto sem chamar o provedor nem duplicar notificação', async () => {
const process = mkProcess({
meeting_session: {
@@ -333,6 +444,32 @@ describe('MeetingsService — criação via Meet REST API', () => {
expect(prisma.meetingSession.create).not.toHaveBeenCalled();
});
+ it('não conclui conversa usando claim de inicialização vencido', async () => {
+ const process = mkProcess({
+ meeting_session: {
+ id: 'meet-1',
+ process_id: 'proc-1',
+ calendar_event_id: 'meeting-init:claim-vencido',
+ meet_link: '',
+ started_at: new Date(Date.now() - 3 * 60 * 1000),
+ ended_at: null,
+ },
+ });
+ const prisma = mkPrisma(process);
+ const svc = new MeetingsService(
+ prisma,
+ mkConfig('OPEN'),
+ notification,
+ {} as any,
+ );
+
+ await expect(
+ svc.markConversationDone('proc-1', 'spec-1'),
+ ).rejects.toBeInstanceOf(ConflictException);
+
+ expect(prisma.meetingSession.deleteMany).not.toHaveBeenCalled();
+ });
+
it('só o especialista pode iniciar a reunião', async () => {
const process = mkProcess();
const prisma = mkPrisma(process);
diff --git a/backend/src/features/meetings/meetings.service.ts b/backend/src/features/meetings/meetings.service.ts
index 896ef4f..e3e3d2b 100644
--- a/backend/src/features/meetings/meetings.service.ts
+++ b/backend/src/features/meetings/meetings.service.ts
@@ -16,10 +16,14 @@ import { GoogleMeetOAuthService } from './google-meet-oauth.service';
import { buildNegotiationSnapshotUpdate } from 'src/features/processes/negotiation-snapshot';
import { lockNegotiationProductMoney } from 'src/features/products/product-monetary-lock';
import { acquireSpecialistScheduleLock } from 'src/features/appointments/appointment-schedule-lock';
+import {
+ buildReadyMeetingClaim,
+ isMeetingInitializationClaim,
+ isStaleMeetingInitializationClaim,
+ MEETING_INITIALIZATION_PREFIX,
+ parseReadyMeetingClaim,
+} from './meeting-initialization-claim';
-const MEETING_INITIALIZATION_PREFIX = 'meeting-init:';
-const MEETING_READY_PREFIX = 'meeting-ready:';
-const MEETING_INITIALIZATION_TTL_MS = 2 * 60 * 1000;
const MEETING_PROVIDER_TIMEOUT_MS = 10_000;
@Injectable()
@@ -79,85 +83,60 @@ export class MeetingsService {
spaceName: string;
meetingUri: string;
}> {
- const accessToken = await this.googleMeetOAuthService.getAccessToken();
-
const controller = new AbortController();
- const timeout = setTimeout(
- () => controller.abort(),
- MEETING_PROVIDER_TIMEOUT_MS,
- );
- let response: Response;
- try {
- response = await fetch('https://meet.googleapis.com/v2/spaces', {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${accessToken}`,
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- config: { accessType: this.meetAccessType },
- }),
- signal: controller.signal,
- });
- } finally {
- clearTimeout(timeout);
- }
+ let timeout: ReturnType | undefined;
+ const deadline = new Promise((_resolve, reject) => {
+ timeout = setTimeout(() => {
+ controller.abort();
+ reject(
+ new Error(
+ `Tempo limite de ${MEETING_PROVIDER_TIMEOUT_MS}ms excedido ao criar sala`,
+ ),
+ );
+ }, MEETING_PROVIDER_TIMEOUT_MS);
+ });
+ const beforeDeadline = (operation: Promise): Promise =>
+ Promise.race([operation, deadline]);
- if (!response.ok) {
- const detail = await response.text();
- throw new Error(
- `Meet spaces.create falhou (${response.status}): ${detail}`,
+ try {
+ const accessToken = await beforeDeadline(
+ this.googleMeetOAuthService.getAccessToken(),
);
- }
- const data: any = await response.json();
- if (!data?.meetingUri || !data?.name) {
- throw new Error(
- 'Meet spaces.create retornou resposta sem meetingUri/name',
+ const response = await beforeDeadline(
+ fetch('https://meet.googleapis.com/v2/spaces', {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ config: { accessType: this.meetAccessType },
+ }),
+ signal: controller.signal,
+ }),
);
- }
- return { spaceName: data.name, meetingUri: data.meetingUri };
- }
+ if (!response.ok) {
+ const detail = await beforeDeadline(response.text());
+ throw new Error(
+ `Meet spaces.create falhou (${response.status}): ${detail}`,
+ );
+ }
- private isInitializationClaim(meeting: any): boolean {
- return Boolean(
- meeting?.calendar_event_id?.startsWith(MEETING_INITIALIZATION_PREFIX),
- );
- }
+ const data: any = await beforeDeadline(response.json());
+ if (!data?.meetingUri || !data?.name) {
+ throw new Error(
+ 'Meet spaces.create retornou resposta sem meetingUri/name',
+ );
+ }
- private parseReadyClaim(meeting: any): {
- claimId: string;
- provider: 'JITSI' | 'GOOGLE' | 'DEMO';
- calendarEventId: string;
- } | null {
- const value = meeting?.calendar_event_id;
- if (typeof value !== 'string' || !value.startsWith(MEETING_READY_PREFIX)) {
- return null;
- }
- const [claimId, provider, encodedCalendarEventId] = value
- .slice(MEETING_READY_PREFIX.length)
- .split(':', 3);
- if (
- !claimId ||
- !encodedCalendarEventId ||
- !['JITSI', 'GOOGLE', 'DEMO'].includes(provider)
- ) {
- return null;
+ return { spaceName: data.name, meetingUri: data.meetingUri };
+ } finally {
+ if (timeout) {
+ clearTimeout(timeout);
+ }
}
- return {
- claimId,
- provider: provider as 'JITSI' | 'GOOGLE' | 'DEMO',
- calendarEventId: decodeURIComponent(encodedCalendarEventId),
- };
- }
-
- private buildReadyClaim(
- claimId: string,
- provider: 'JITSI' | 'GOOGLE' | 'DEMO',
- calendarEventId: string,
- ): string {
- return `${MEETING_READY_PREFIX}${claimId}:${provider}:${encodeURIComponent(calendarEventId)}`;
}
private assertMeetingCanStart(process: any, userId: string): void {
@@ -467,8 +446,8 @@ export class MeetingsService {
const { process } = await this.getAuthorizedProcess(processId, userId);
return process.meeting_session &&
- !this.isInitializationClaim(process.meeting_session) &&
- !this.parseReadyClaim(process.meeting_session)
+ !isMeetingInitializationClaim(process.meeting_session) &&
+ !parseReadyMeetingClaim(process.meeting_session)
? this.buildMeetingResponse(process.meeting_session)
: null;
}
@@ -530,7 +509,7 @@ export class MeetingsService {
}
this.assertMeetingCanStart(process, userId);
if (process.meeting_session) {
- const ready = this.parseReadyClaim(process.meeting_session);
+ const ready = parseReadyMeetingClaim(process.meeting_session);
if (ready) {
return {
process,
@@ -540,10 +519,8 @@ export class MeetingsService {
provider: ready.provider,
};
}
- if (this.isInitializationClaim(process.meeting_session)) {
- const claimAge =
- Date.now() - process.meeting_session.started_at.getTime();
- if (claimAge < MEETING_INITIALIZATION_TTL_MS) {
+ if (isMeetingInitializationClaim(process.meeting_session)) {
+ if (!isStaleMeetingInitializationClaim(process.meeting_session)) {
throw new ConflictException(
'A reunião já está sendo iniciada. Tente novamente em instantes.',
);
@@ -647,7 +624,7 @@ export class MeetingsService {
}
}
- const readyCalendarEventId = this.buildReadyClaim(
+ const readyCalendarEventId = buildReadyMeetingClaim(
claimId,
provider,
calendarEventId,
@@ -721,7 +698,7 @@ export class MeetingsService {
try {
this.assertMeetingCanStart(process, userId);
} catch (error) {
- const invalidReady = this.parseReadyClaim(process.meeting_session);
+ const invalidReady = parseReadyMeetingClaim(process.meeting_session);
if (invalidReady?.claimId === readyClaim.claimId) {
await tx.meetingSession.deleteMany({
where: {
@@ -734,11 +711,11 @@ export class MeetingsService {
}
const currentMeeting = process.meeting_session;
- const currentReady = this.parseReadyClaim(currentMeeting);
+ const currentReady = parseReadyMeetingClaim(currentMeeting);
if (!currentReady || currentReady.claimId !== readyClaim.claimId) {
if (
currentMeeting &&
- !this.isInitializationClaim(currentMeeting) &&
+ !isMeetingInitializationClaim(currentMeeting) &&
!currentReady
) {
return {
@@ -769,7 +746,7 @@ export class MeetingsService {
const current = await tx.meetingSession.findUnique({
where: { process_id: processId },
});
- if (current && !this.parseReadyClaim(current)) {
+ if (current && !parseReadyMeetingClaim(current)) {
return {
process,
meeting: current,
@@ -866,8 +843,8 @@ export class MeetingsService {
}
if (
- this.isInitializationClaim(process.meeting_session) ||
- this.parseReadyClaim(process.meeting_session)
+ isMeetingInitializationClaim(process.meeting_session) ||
+ parseReadyMeetingClaim(process.meeting_session)
) {
throw new ConflictException(
'A reunião ainda está sendo iniciada. Tente novamente em instantes.',
diff --git a/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts b/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts
index f22ba03..5db5542 100644
--- a/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts
+++ b/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts
@@ -296,6 +296,47 @@ describeWithPostgres('process rejection CAS — PostgreSQL concurrency', () => {
).resolves.toBe(0);
}, 15_000);
+ it('remove meeting-init vencido sob lock e permite a rejeição', async () => {
+ await completionClient.process.create({
+ data: {
+ id: processId,
+ client_id: clientId,
+ specialist_id: specialistId,
+ status: ProcessStatus.SCHEDULING,
+ meeting_session: {
+ create: {
+ started_by_id: specialistId,
+ calendar_event_id: `meeting-init:${suffix}`,
+ meet_link: '',
+ started_at: new Date(Date.now() - 3 * 60 * 1000),
+ },
+ },
+ },
+ });
+ const service = new ProcessesService(
+ completionClient as any,
+ meetingNotifications(),
+ );
+
+ await expect(
+ service.rejectProcess(
+ processId,
+ clientId,
+ 'claim abandonado',
+ UserRole.CUSTOMER,
+ ),
+ ).resolves.toMatchObject({ status: ProcessStatus.REJECTED });
+
+ await expect(
+ completionClient.meetingSession.count({
+ where: { process_id: processId },
+ }),
+ ).resolves.toBe(0);
+ await expect(
+ completionClient.process.findUniqueOrThrow({ where: { id: processId } }),
+ ).resolves.toMatchObject({ status: ProcessStatus.REJECTED });
+ }, 15_000);
+
it('não ressuscita processo quando update perde a corrida para rejeição', async () => {
await completionClient.process.create({
data: {
diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts
index af216e4..248d785 100644
--- a/backend/src/features/processes/processes.service.spec.ts
+++ b/backend/src/features/processes/processes.service.spec.ts
@@ -2032,6 +2032,7 @@ describe('ProcessesService — autorização centralizada de processos', () => {
.mockResolvedValueOnce(rejectedProcess);
const historyCreate = jest.fn().mockResolvedValue({});
const rejectionCreate = jest.fn().mockResolvedValue({});
+ const meetingSessionDeleteMany = jest.fn().mockResolvedValue({ count: 1 });
const tx = {
$queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
process: {
@@ -2044,6 +2045,7 @@ describe('ProcessesService — autorização centralizada de processos', () => {
findMany: jest.fn().mockResolvedValue([]),
},
processRejection: { create: rejectionCreate },
+ meetingSession: { deleteMany: meetingSessionDeleteMany },
};
const prisma = {
$transaction: jest.fn(async (callback) => callback(tx)),
@@ -2057,6 +2059,7 @@ describe('ProcessesService — autorização centralizada de processos', () => {
processFindUniqueOrThrow,
historyCreate,
rejectionCreate,
+ meetingSessionDeleteMany,
tx,
};
}
@@ -2365,6 +2368,68 @@ describe('ProcessesService — autorização centralizada de processos', () => {
},
);
+ it('remove claim de inicialização vencido sob lock e permite rejeitar', async () => {
+ const { service, meetingSessionDeleteMany, processUpdateMany, tx } =
+ rejectionService(
+ protectedProcess({
+ meeting_session: {
+ id: 'dddddddd-dddd-4ddd-8ddd-dddddddddddd',
+ calendar_event_id: 'meeting-init:claim-vencido',
+ started_at: new Date(Date.now() - 3 * 60 * 1000),
+ ended_at: null,
+ },
+ }),
+ );
+
+ 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(tx.$queryRaw).toHaveBeenCalledTimes(1);
+ expect(meetingSessionDeleteMany).toHaveBeenCalledWith({
+ where: {
+ id: 'dddddddd-dddd-4ddd-8ddd-dddddddddddd',
+ calendar_event_id: 'meeting-init:claim-vencido',
+ },
+ });
+ expect(meetingSessionDeleteMany.mock.invocationCallOrder[0]).toBeLessThan(
+ processUpdateMany.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('mantém claim de inicialização recente e bloqueia rejeição', async () => {
+ const { service, meetingSessionDeleteMany, processUpdateMany } =
+ rejectionService(
+ protectedProcess({
+ meeting_session: {
+ id: 'dddddddd-dddd-4ddd-8ddd-dddddddddddd',
+ calendar_event_id: 'meeting-init:claim-recente',
+ started_at: new Date(),
+ ended_at: null,
+ },
+ }),
+ );
+
+ await expect(
+ service.rejectProcess(
+ '99999999-9999-4999-8999-999999999999',
+ ownerClientId,
+ undefined,
+ UserRole.CUSTOMER,
+ ),
+ ).rejects.toThrow(BadRequestException);
+
+ expect(meetingSessionDeleteMany).not.toHaveBeenCalled();
+ expect(processUpdateMany).not.toHaveBeenCalled();
+ });
+
it('cliente pode rejeitar o próprio processo sem appointment', async () => {
const { service, processUpdate, processUpdateMany, tx } =
rejectionService();
diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts
index 3d8199c..569ee0e 100644
--- a/backend/src/features/processes/processes.service.ts
+++ b/backend/src/features/processes/processes.service.ts
@@ -40,6 +40,7 @@ import {
acquireSpecialistScheduleLock,
assertSpecialistScheduleAvailable,
} from '../appointments/appointment-schedule-lock';
+import { isStaleMeetingInitializationClaim } from '../meetings/meeting-initialization-claim';
/**
* Quem está pedindo a operação. `companyId` só é usado por OFFICE.
@@ -2042,7 +2043,14 @@ export class ProcessesService {
status: true,
},
},
- meeting_session: { select: { ended_at: true } },
+ meeting_session: {
+ select: {
+ id: true,
+ calendar_event_id: true,
+ started_at: true,
+ ended_at: true,
+ },
+ },
},
});
@@ -2094,9 +2102,26 @@ export class ProcessesService {
existingProcess.meeting_session &&
!existingProcess.meeting_session.ended_at
) {
- throw new BadRequestException(
- 'Encerre a reunião antes de rejeitar o processo',
- );
+ if (
+ isStaleMeetingInitializationClaim(existingProcess.meeting_session)
+ ) {
+ const staleClaimCleanup = await tx.meetingSession.deleteMany({
+ where: {
+ id: existingProcess.meeting_session.id,
+ calendar_event_id:
+ existingProcess.meeting_session.calendar_event_id,
+ },
+ });
+ if (staleClaimCleanup.count !== 1) {
+ throw new ConflictException(
+ 'A inicialização da reunião mudou. Recarregue e tente novamente.',
+ );
+ }
+ } else {
+ throw new BadRequestException(
+ 'Encerre a reunião antes de rejeitar o processo',
+ );
+ }
}
const rejectedAt = new Date();
From 2efc3617ad3cab68707eb181a10d3a2079572fef Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:33:10 -0300
Subject: [PATCH 42/60] fix(appointments): close Calendly retry races
---
.../appointments/appointments.service.spec.ts | 115 ++++++++++++++++--
.../appointments/appointments.service.ts | 19 ++-
.../calendly-integration.service.spec.ts | 52 ++++++++
.../calendly-integration.service.ts | 18 +++
.../StartProcessForClientModal.test.tsx | 59 ++-------
.../processes/StartProcessForClientModal.tsx | 57 ++-------
.../src/hooks/useCalendlyScheduling.test.tsx | 108 +++++++++++++++-
frontend/src/hooks/useCalendlyScheduling.ts | 35 ++++--
frontend/src/services/calendly-sync.ts | 17 ++-
9 files changed, 358 insertions(+), 122 deletions(-)
diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts
index 841a32d..feae78a 100644
--- a/backend/src/features/appointments/appointments.service.spec.ts
+++ b/backend/src/features/appointments/appointments.service.spec.ts
@@ -1,5 +1,6 @@
import {
AppointmentSchedulingMethod,
+ CalendlySyncStatus,
Prisma,
ProcessStatus,
ProductCurrency,
@@ -1922,6 +1923,110 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
);
});
+ it('não persiste URIs controladas pelo cliente quando a API não confirma o horário', 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,
+ calendly_invitee_uri: null,
+ calendly_sync_status: CalendlySyncStatus.PENDING,
+ appointment_datetime: null,
+ };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn().mockResolvedValue(appointment),
+ findFirst: jest.fn(),
+ update: jest.fn().mockImplementation(({ data }) => ({
+ ...appointment,
+ ...data,
+ })),
+ },
+ };
+ const prisma = {
+ appointment: { findUnique: jest.fn().mockResolvedValue(appointment) },
+ $transaction: jest.fn(async (callback: any) => callback(tx)),
+ } as any;
+ const resolveScheduledStartTime = jest.fn().mockResolvedValue(null);
+ const service = new AppointmentsService(prisma, {} as any, {
+ resolveScheduledStartTime,
+ } as any);
+
+ await expect(
+ service.registerCalendlyScheduled(appointment.id, appointment.client_id, {
+ event_uri: 'https://api.calendly.com/scheduled_events/event-poison',
+ invitee_uri:
+ 'https://api.calendly.com/scheduled_events/event-poison/invitees/invitee-poison',
+ }),
+ ).resolves.toMatchObject({
+ calendly_sync_status: CalendlySyncStatus.PENDING,
+ appointment_datetime: null,
+ });
+ expect(resolveScheduledStartTime).toHaveBeenCalledTimes(1);
+ expect(tx.appointment.update).not.toHaveBeenCalled();
+ expect(tx.appointment.findFirst).not.toHaveBeenCalled();
+ });
+
+ it('não ressuscita como SYNCED um agendamento cancelado pelo webhook enquanto consultava a API', async () => {
+ const resolvedDate = new Date('2099-01-03T14:00:00.000Z');
+ 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:
+ 'https://api.calendly.com/scheduled_events/event-1',
+ calendly_invitee_uri:
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
+ calendly_sync_status: CalendlySyncStatus.PENDING,
+ appointment_datetime: null,
+ };
+ let stored = { ...appointment };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn(async () => ({ ...stored })),
+ findFirst: jest.fn().mockResolvedValue(null),
+ update: jest.fn().mockImplementation(({ data }) => ({
+ ...stored,
+ ...data,
+ })),
+ },
+ };
+ const prisma = {
+ appointment: { findUnique: jest.fn().mockResolvedValue(appointment) },
+ $transaction: jest.fn(async (callback: any) => callback(tx)),
+ } as any;
+ const resolveScheduledStartTime = jest.fn(async () => {
+ stored = {
+ ...stored,
+ calendly_sync_status: CalendlySyncStatus.FAILED,
+ };
+ return resolvedDate;
+ });
+ const service = new AppointmentsService(prisma, {} as any, {
+ resolveScheduledStartTime,
+ } as any);
+
+ await expect(
+ service.registerCalendlyScheduled(appointment.id, appointment.client_id, {
+ event_uri: appointment.calendly_event_uri,
+ invitee_uri: appointment.calendly_invitee_uri,
+ }),
+ ).resolves.toMatchObject({
+ calendly_sync_status: CalendlySyncStatus.FAILED,
+ appointment_datetime: null,
+ });
+ expect(tx.appointment.update).not.toHaveBeenCalled();
+ expect(tx.appointment.findFirst).not.toHaveBeenCalled();
+ });
+
it('reconsulta o Calendly ao repetir a mesma associação ainda PENDING e promove para SYNCED', async () => {
const resolvedDate = new Date('2099-01-03T14:00:00.000Z');
const appointment = {
@@ -2195,6 +2300,7 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
appointment.specialist_id,
'https://api.calendly.com/scheduled_events/event-1',
'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
+ appointment.client_id,
);
expect(tx.$queryRaw).toHaveBeenCalledWith(
expect.anything(),
@@ -2275,14 +2381,7 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
});
expect(resolveScheduledStartTime).toHaveBeenCalledTimes(1);
expect(tx.appointment.findFirst).not.toHaveBeenCalled();
- expect(tx.appointment.update).toHaveBeenCalledWith(
- expect.objectContaining({
- data: expect.objectContaining({
- calendly_sync_status: 'PENDING',
- appointment_datetime: null,
- }),
- }),
- );
+ expect(tx.appointment.update).not.toHaveBeenCalled();
},
);
diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts
index f768863..87cc5c5 100644
--- a/backend/src/features/appointments/appointments.service.ts
+++ b/backend/src/features/appointments/appointments.service.ts
@@ -1946,6 +1946,14 @@ export class AppointmentsService {
throw this.buildRescheduleAlreadyUsedError(appointmentId);
}
+ if (appointment.calendly_sync_status === CalendlySyncStatus.FAILED) {
+ return {
+ appointment_id: appointment.id,
+ calendly_sync_status: appointment.calendly_sync_status,
+ appointment_datetime: appointment.appointment_datetime,
+ };
+ }
+
if (
appointment.calendly_event_uri &&
parseCalendlyResourceUri(appointment.calendly_event_uri, 'event')
@@ -2001,6 +2009,7 @@ export class AppointmentsService {
appointment.specialist_id,
eventUri,
inviteeUri,
+ appointment.client_id,
);
} catch (error: any) {
if (error instanceof BadRequestException) {
@@ -2057,6 +2066,11 @@ export class AppointmentsService {
if (lockedAppointment.specialist_rescheduled_at) {
throw this.buildRescheduleAlreadyUsedError(appointmentId);
}
+ if (
+ lockedAppointment.calendly_sync_status === CalendlySyncStatus.FAILED
+ ) {
+ return lockedAppointment;
+ }
if (
lockedAppointment.calendly_event_uri &&
parseCalendlyResourceUri(
@@ -2077,10 +2091,7 @@ export class AppointmentsService {
}
}
- if (
- !scheduledStartTime &&
- this.hasTrustedCalendlySchedule(lockedAppointment)
- ) {
+ if (!scheduledStartTime) {
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 19d5da5..b7cd6d8 100644
--- a/backend/src/features/appointments/calendly-integration.service.spec.ts
+++ b/backend/src/features/appointments/calendly-integration.service.spec.ts
@@ -227,6 +227,9 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
update: jest.fn(),
updateMany: jest.fn().mockResolvedValue({ count: 1 }),
},
+ user: {
+ findUnique: jest.fn(),
+ },
};
const service = new CalendlyIntegrationService(prisma as any);
const connection = {
@@ -351,6 +354,55 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
);
});
+ it('rejeita invitee autoritativo cujo email pertence a outro cliente', async () => {
+ const { service, prisma } = makeRefreshService();
+ prisma.user.findUnique.mockResolvedValue({ email: 'cliente@example.com' });
+ jest.mocked(axios.get).mockResolvedValueOnce({
+ data: {
+ resource: {
+ email: 'outra-pessoa@example.com',
+ event: 'https://api.calendly.com/scheduled_events/event-1',
+ start_time: '2099-01-01T10:00:00.000Z',
+ },
+ },
+ });
+
+ await expect(
+ service.resolveScheduledStartTime(
+ 'specialist-1',
+ 'https://api.calendly.com/scheduled_events/event-1',
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
+ 'client-1',
+ ),
+ ).rejects.toThrow('não pertence ao cliente do agendamento');
+ expect(prisma.calendlyConnection.update).not.toHaveBeenCalled();
+ });
+
+ it('aceita email autoritativo equivalente ignorando espaços e caixa', async () => {
+ const { service, prisma } = makeRefreshService();
+ prisma.user.findUnique.mockResolvedValue({
+ email: ' Cliente@Example.com ',
+ });
+ jest.mocked(axios.get).mockResolvedValueOnce({
+ data: {
+ resource: {
+ email: 'cliente@example.COM',
+ event: 'https://api.calendly.com/scheduled_events/event-1',
+ start_time: '2099-01-01T10:00:00.000Z',
+ },
+ },
+ });
+
+ await expect(
+ service.resolveScheduledStartTime(
+ 'specialist-1',
+ 'https://api.calendly.com/scheduled_events/event-1',
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
+ 'client-1',
+ ),
+ ).resolves.toEqual(new Date('2099-01-01T10:00:00.000Z'));
+ });
+
it('rejeita URI de evento não confiável retornada pelo recurso de convidado', async () => {
const { service } = makeRefreshService();
jest.mocked(axios.get).mockResolvedValueOnce({
diff --git a/backend/src/features/appointments/calendly-integration.service.ts b/backend/src/features/appointments/calendly-integration.service.ts
index 27c1019..d2a67a8 100644
--- a/backend/src/features/appointments/calendly-integration.service.ts
+++ b/backend/src/features/appointments/calendly-integration.service.ts
@@ -308,6 +308,7 @@ export class CalendlyIntegrationService {
specialistId: string,
eventUri?: string | null,
inviteeUri?: string | null,
+ expectedClientId?: string | null,
): Promise {
if (!specialistId || (!eventUri && !inviteeUri)) {
return null;
@@ -338,6 +339,23 @@ export class CalendlyIntegrationService {
: null;
const inviteeResource = inviteeData?.resource || inviteeData;
+ if (expectedClientId) {
+ const client = await this.prisma.user.findUnique({
+ where: { id: expectedClientId },
+ select: { email: true },
+ });
+ const expectedEmail = client?.email?.trim().toLowerCase();
+ const authoritativeEmail = inviteeResource?.email?.trim().toLowerCase();
+ if (
+ !expectedEmail ||
+ !authoritativeEmail ||
+ expectedEmail !== authoritativeEmail
+ ) {
+ throw new BadRequestException(
+ 'O convidado do Calendly não pertence ao cliente do agendamento',
+ );
+ }
+ }
const inviteeEventUri =
inviteeResource?.event || inviteeResource?.scheduled_event?.uri;
const inviteeEventReference = inviteeEventUri
diff --git a/frontend/src/components/processes/StartProcessForClientModal.test.tsx b/frontend/src/components/processes/StartProcessForClientModal.test.tsx
index 3d8555e..35b0333 100644
--- a/frontend/src/components/processes/StartProcessForClientModal.test.tsx
+++ b/frontend/src/components/processes/StartProcessForClientModal.test.tsx
@@ -234,61 +234,35 @@ describe("StartProcessForClientModal capability", () => {
expect(createConsultantProcess).toHaveBeenCalledWith(expect.objectContaining({ client_id: client.id }));
});
- it("ignores Calendly sync completion after its scope changes", async () => {
- let resolve!: (value: Awaited>) => void;
+ it("ignores a Calendly event after its scope changes", async () => {
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; });
+ await act(async () => {
+ 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("retries the same Calendly registration after PENDING before redirecting", async () => {
+ it("does not register an on-behalf EMAIL appointment through the client-only Calendly endpoint", async () => {
vi.mocked(getPublicSpecialistById).mockResolvedValue({
...specialist,
calendly_scheduling_available: true,
});
- vi.mocked(registerCalendlyScheduledEvent)
- .mockResolvedValueOnce({
- appointment_id: "appointment-1",
- calendly_sync_status: "PENDING",
- appointment_datetime: null,
- })
- .mockResolvedValueOnce({
- appointment_id: "appointment-1",
- calendly_sync_status: "SYNCED",
- appointment_datetime: "2099-01-01T10:00:00.000Z",
- });
- vi.mocked(getCalendlySyncStatus)
- .mockResolvedValueOnce({
- appointment_id: "appointment-1",
- status: "PENDING",
- calendly_sync_status: "PENDING",
- appointment_datetime: null,
- calendly_last_sync_at: null,
- })
- .mockResolvedValueOnce({
- appointment_id: "appointment-1",
- status: "SCHEDULED",
- calendly_sync_status: "SYNCED",
- appointment_datetime: "2099-01-01T10:00:00.000Z",
- calendly_last_sync_at: "2099-01-01T09:59:00.000Z",
- });
renderModal();
await selectAndCreate();
await screen.findByRole("link", { name: "Agendar no Calendly" });
vi.useFakeTimers();
const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
.onEventScheduled!;
+ let completion!: Promise;
act(() => {
- void Promise.resolve(
+ completion = Promise.resolve(
listener({
data: {
event: "calendly.event_scheduled",
@@ -301,22 +275,13 @@ describe("StartProcessForClientModal capability", () => {
);
});
await act(async () => {
- await Promise.resolve();
- await Promise.resolve();
+ await vi.runAllTimersAsync();
+ await completion;
});
- expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(1);
- await act(async () => {
- await vi.advanceTimersByTimeAsync(500);
- await Promise.resolve();
- });
-
- expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(2);
- expect(vi.mocked(registerCalendlyScheduledEvent).mock.calls[0][1]).toEqual(
- vi.mocked(registerCalendlyScheduledEvent).mock.calls[1][1],
- );
+ expect(registerCalendlyScheduledEvent).not.toHaveBeenCalled();
+ expect(getCalendlySyncStatus).not.toHaveBeenCalled();
expect(screen.getByText("Processos do consultor")).toBeTruthy();
- vi.useRealTimers();
});
it("keeps the selected client when only label or callback props change", async () => {
diff --git a/frontend/src/components/processes/StartProcessForClientModal.tsx b/frontend/src/components/processes/StartProcessForClientModal.tsx
index b83a901..5e809f0 100644
--- a/frontend/src/components/processes/StartProcessForClientModal.tsx
+++ b/frontend/src/components/processes/StartProcessForClientModal.tsx
@@ -4,8 +4,6 @@ import { PopupModal, useCalendlyEventListener } from "react-calendly";
import { getClients, createConsultantProcess, type Client } from "../../services/consultant.service";
import { officeService } from "../../services/office";
import { getPublicSpecialistById, type PublicSpecialistProfile } from "../../services/specialists.service";
-import type { RegisterCalendlyScheduledPayload } from "../../services/appointments.service";
-import { synchronizeCalendlyRegistration } from "../../services/calendly-sync";
import Button from "../../components/ui/button";
import { Loader2, Search } from "lucide-react";
@@ -77,11 +75,9 @@ function StartProcessForClientModalInner({
const submittingRef = useRef(false);
const mountedRef = useRef(false);
const operationGeneration = useRef(0);
- const syncAbortRef = useRef(null);
const busyCallbackRef = useRef(onBusyChange);
const calendlyOpenCallbackRef = useRef(onCalendlyOpenChange);
const [pendingOperation, setPendingOperation] = useState<{
- appointmentId: string;
generation: number;
client: Client;
} | null>(null);
@@ -99,7 +95,6 @@ function StartProcessForClientModalInner({
return () => {
mountedRef.current = false;
operationGeneration.current += 1;
- syncAbortRef.current?.abort();
calendlyOpenCallbackRef.current?.(false);
busyCallbackRef.current?.(false);
};
@@ -155,48 +150,19 @@ function StartProcessForClientModalInner({
);
}, [clients, search]);
- // Sincroniza o horário escolhido no Calendly com o agendamento criado
+ // Este fluxo cria o processo em nome do cliente como EMAIL. O endpoint de
+ // sincronização Calendly é exclusivo do próprio cliente autenticado, então
+ // o evento do popup apenas conclui a navegação deste fluxo delegado.
useCalendlyEventListener({
- onEventScheduled: async (event) => {
+ onEventScheduled: () => {
const pending = pendingOperation;
if (!pending || !isCurrentOperation(pending.generation)) return;
-
- const payload = (event as any)?.data?.payload;
- const eventUri = payload?.event?.uri;
- const inviteeUri = payload?.invitee?.uri;
-
- try {
- if (eventUri && inviteeUri) {
- const registrationPayload: RegisterCalendlyScheduledPayload = {
- event_uri: eventUri,
- invitee_uri: inviteeUri,
- client_event: "calendly.event_scheduled",
- client_observed_at: new Date().toISOString(),
- };
- syncAbortRef.current?.abort();
- const syncController = new AbortController();
- syncAbortRef.current = syncController;
- await synchronizeCalendlyRegistration(
- pending.appointmentId,
- registrationPayload,
- { signal: syncController.signal },
- );
- if (!isCurrentOperation(pending.generation)) return;
- }
- } catch (err) {
- if (isCurrentOperation(pending.generation)) {
- console.error("Erro ao sincronizar evento do Calendly:", err);
- }
- } finally {
- if (isCurrentOperation(pending.generation)) {
- operationGeneration.current += 1;
- setCalendlyOpen(false);
- setPendingOperation(null);
- submittingRef.current = false;
- setBusy(false);
- navigate(config.redirectTo);
- }
- }
+ operationGeneration.current += 1;
+ setCalendlyOpen(false);
+ setPendingOperation(null);
+ submittingRef.current = false;
+ setBusy(false);
+ navigate(config.redirectTo);
},
});
@@ -235,7 +201,7 @@ function StartProcessForClientModalInner({
url = `https://${url}`;
}
awaitingCalendly = true;
- setPendingOperation({ appointmentId: process.appointment_id, generation, client: submittedClient });
+ setPendingOperation({ generation, client: submittedClient });
setCalendlyUrl(url);
setCalendlyOpen(true);
setCalendlyMessage(
@@ -348,7 +314,6 @@ function StartProcessForClientModalInner({
onModalClose={() => {
if (!pendingOperation || !isCurrentOperation(pendingOperation.generation)) return;
operationGeneration.current += 1;
- syncAbortRef.current?.abort();
setCalendlyOpen(false);
setPendingOperation(null);
submittingRef.current = false;
diff --git a/frontend/src/hooks/useCalendlyScheduling.test.tsx b/frontend/src/hooks/useCalendlyScheduling.test.tsx
index 14ff1fe..800f883 100644
--- a/frontend/src/hooks/useCalendlyScheduling.test.tsx
+++ b/frontend/src/hooks/useCalendlyScheduling.test.tsx
@@ -2,7 +2,10 @@
import { act, cleanup, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { useCalendlyEventListener } from "react-calendly";
+import {
+ useCalendlyEventListener,
+ type EventScheduledEvent,
+} from "react-calendly";
import {
getCalendlySyncStatus,
registerCalendlyScheduledEvent,
@@ -41,16 +44,28 @@ const syncedStatus = {
appointment_datetime: "2099-01-01T10:00:00.000Z",
};
-function scheduledEvent() {
- return {
+function scheduledEvent(
+ options: {
+ origin?: string;
+ source?: MessageEventSource | null;
+ eventUri?: string;
+ inviteeUri?: string;
+ } = {},
+): EventScheduledEvent {
+ const frame = document.querySelector(
+ ".calendly-popup-content iframe",
+ );
+ return new MessageEvent("message", {
+ origin: options.origin ?? "https://calendly.com",
+ source: options.source ?? frame?.contentWindow,
data: {
event: "calendly.event_scheduled",
payload: {
- event: { uri: payload.event_uri },
- invitee: { uri: payload.invitee_uri },
+ event: { uri: options.eventUri ?? payload.event_uri },
+ invitee: { uri: options.inviteeUri ?? payload.invitee_uri },
},
},
- } as any;
+ }) as EventScheduledEvent;
}
async function flushPromises() {
@@ -64,10 +79,15 @@ describe("useCalendlyScheduling active registration retry", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.clearAllMocks();
+ const popup = document.createElement("div");
+ popup.className = "calendly-popup-content";
+ popup.appendChild(document.createElement("iframe"));
+ document.body.appendChild(popup);
});
afterEach(() => {
cleanup();
+ document.body.innerHTML = "";
vi.clearAllTimers();
vi.useRealTimers();
});
@@ -171,4 +191,80 @@ describe("useCalendlyScheduling active registration retry", () => {
await vi.advanceTimersByTimeAsync(60_000);
expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(8);
});
+
+ it("não considera FAILED com datetime como sincronização concluída", async () => {
+ vi.mocked(registerCalendlyScheduledEvent).mockResolvedValue({
+ appointment_id: "appointment-1",
+ calendly_sync_status: "PENDING",
+ appointment_datetime: null,
+ });
+ vi.mocked(getCalendlySyncStatus).mockResolvedValue({
+ ...syncedStatus,
+ status: "CANCELLED",
+ calendly_sync_status: "FAILED",
+ });
+ const onSynced = vi.fn();
+ const { result } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok", onSynced }),
+ );
+ act(() => result.current.openPopup("appointment-1", "https://calendly.com/a"));
+ const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
+ .onEventScheduled!;
+
+ await act(async () => {
+ await listener(scheduledEvent());
+ });
+
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(1);
+ expect(getCalendlySyncStatus).toHaveBeenCalledTimes(1);
+ expect(onSynced).not.toHaveBeenCalled();
+ expect(navigate).not.toHaveBeenCalled();
+ });
+
+ it("ignora evento tardio enviado pelo iframe de uma sessão anterior A após abrir B", async () => {
+ const { result } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ );
+ act(() => result.current.openPopup("appointment-a", "https://calendly.com/a"));
+ const oldFrame = document.querySelector(
+ ".calendly-popup-content iframe",
+ )!;
+ const oldSource = oldFrame.contentWindow;
+ const replacement = document.createElement("iframe");
+ oldFrame.replaceWith(replacement);
+
+ act(() => result.current.openPopup("appointment-b", "https://calendly.com/b"));
+ const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
+ .onEventScheduled!;
+ const staleEvent = scheduledEvent({
+ source: oldSource,
+ eventUri: "https://api.calendly.com/scheduled_events/event-a",
+ inviteeUri:
+ "https://api.calendly.com/scheduled_events/event-a/invitees/invitee-a",
+ });
+
+ await act(async () => {
+ await listener(staleEvent);
+ });
+
+ expect(registerCalendlyScheduledEvent).not.toHaveBeenCalled();
+ expect(getCalendlySyncStatus).not.toHaveBeenCalled();
+ });
+
+ it("ignora mensagem de origem diferente da URL Calendly aberta", async () => {
+ const { result } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ );
+ act(() => result.current.openPopup("appointment-1", "https://calendly.com/a"));
+ const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
+ .onEventScheduled!;
+ const forgedEvent = scheduledEvent({ origin: "https://evil.test" });
+
+ await act(async () => {
+ await listener(forgedEvent);
+ });
+
+ expect(registerCalendlyScheduledEvent).not.toHaveBeenCalled();
+ expect(getCalendlySyncStatus).not.toHaveBeenCalled();
+ });
});
diff --git a/frontend/src/hooks/useCalendlyScheduling.ts b/frontend/src/hooks/useCalendlyScheduling.ts
index dd7b998..cd713f9 100644
--- a/frontend/src/hooks/useCalendlyScheduling.ts
+++ b/frontend/src/hooks/useCalendlyScheduling.ts
@@ -6,7 +6,10 @@ import {
type CalendlySyncStatus,
type RegisterCalendlyScheduledPayload,
} from "../services/appointments.service";
-import { synchronizeCalendlyRegistration } from "../services/calendly-sync";
+import {
+ isCalendlySyncComplete,
+ synchronizeCalendlyRegistration,
+} from "../services/calendly-sync";
export type CalendlySyncState =
| "idle"
@@ -69,7 +72,25 @@ export function useCalendlyScheduling({
return;
}
- const payload = (event as any)?.data?.payload;
+ let expectedOrigin: string | null = null;
+ try {
+ expectedOrigin = modalUrl ? new URL(modalUrl).origin : null;
+ } catch {
+ return;
+ }
+ const currentFrame = document.querySelector(
+ ".calendly-popup-content iframe",
+ );
+ if (
+ !expectedOrigin ||
+ event.origin !== expectedOrigin ||
+ !currentFrame?.contentWindow ||
+ event.source !== currentFrame.contentWindow
+ ) {
+ return;
+ }
+
+ const payload = event.data?.payload;
const eventUri = payload?.event?.uri;
const inviteeUri = payload?.invitee?.uri;
@@ -110,10 +131,7 @@ export function useCalendlyScheduling({
if (!mountedRef.current || syncController.signal.aborted || !status) return;
setIsModalOpen(false);
- if (
- status.calendly_sync_status === "SYNCED" ||
- status.appointment_datetime
- ) {
+ if (isCalendlySyncComplete(status)) {
onSynced?.(status);
setSyncState("done");
setSyncMessage(
@@ -161,9 +179,12 @@ export function useCalendlyScheduling({
const openPopup = (appointmentId: string, calendlyUrl: string) => {
syncAbortRef.current?.abort();
if (navigateTimerRef.current) clearTimeout(navigateTimerRef.current);
+ const normalizedUrl = /^https?:\/\//i.test(calendlyUrl)
+ ? calendlyUrl
+ : `https://${calendlyUrl}`;
confirmedRef.current = false;
setPendingAppointmentId(appointmentId);
- setModalUrl(calendlyUrl);
+ setModalUrl(normalizedUrl);
setSyncState("waiting_event");
setSyncMessage(
"Conclua seu agendamento no Calendly para sincronizar automaticamente com a plataforma.",
diff --git a/frontend/src/services/calendly-sync.ts b/frontend/src/services/calendly-sync.ts
index 20dcfd0..50e5283 100644
--- a/frontend/src/services/calendly-sync.ts
+++ b/frontend/src/services/calendly-sync.ts
@@ -9,10 +9,17 @@ export const CALENDLY_SYNC_MAX_ATTEMPTS = 8;
export const CALENDLY_SYNC_BASE_DELAY_MS = 500;
const CALENDLY_SYNC_MAX_DELAY_MS = 3500;
-function isSynced(status: CalendlySyncStatus): boolean {
+export function isCalendlySyncComplete(status: CalendlySyncStatus): boolean {
return (
- status.calendly_sync_status === "SYNCED" ||
- Boolean(status.appointment_datetime)
+ status.calendly_sync_status === "SYNCED" &&
+ Boolean(status.appointment_datetime) &&
+ status.status !== "CANCELLED"
+ );
+}
+
+function isTerminal(status: CalendlySyncStatus): boolean {
+ return (
+ status.calendly_sync_status === "FAILED" || status.status === "CANCELLED"
);
}
@@ -60,7 +67,9 @@ export async function synchronizeCalendlyRegistration(
try {
lastStatus = await getCalendlySyncStatus(appointmentId);
- if (isSynced(lastStatus)) return lastStatus;
+ if (isCalendlySyncComplete(lastStatus) || isTerminal(lastStatus)) {
+ return lastStatus;
+ }
} catch (error) {
lastError = error;
}
From 1f1b8e2e9ac7b04e4f20865bee4e747330ee839d Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:37:59 -0300
Subject: [PATCH 43/60] fix(frontend): harden Calendly completion states
---
.../src/hooks/useCalendlyScheduling.test.tsx | 86 +++++++++++++++----
frontend/src/hooks/useCalendlyScheduling.ts | 23 +++--
frontend/src/lib/calendly-origin.ts | 18 ++++
.../ProductPage.calendly.integration.test.tsx | 17 ++--
.../pages/customer/ConsultoriaPage.test.tsx | 35 +++++++-
frontend/src/services/calendly-sync.ts | 9 +-
6 files changed, 150 insertions(+), 38 deletions(-)
create mode 100644 frontend/src/lib/calendly-origin.ts
diff --git a/frontend/src/hooks/useCalendlyScheduling.test.tsx b/frontend/src/hooks/useCalendlyScheduling.test.tsx
index 800f883..a6caf37 100644
--- a/frontend/src/hooks/useCalendlyScheduling.test.tsx
+++ b/frontend/src/hooks/useCalendlyScheduling.test.tsx
@@ -190,35 +190,86 @@ describe("useCalendlyScheduling active registration retry", () => {
expect(getCalendlySyncStatus).toHaveBeenCalledTimes(8);
await vi.advanceTimersByTimeAsync(60_000);
expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(8);
+ expect(result.current.syncState).toBe("pending");
+ expect(result.current.syncMessage).toContain("finalizando a sincronização");
});
- it("não considera FAILED com datetime como sincronização concluída", async () => {
+ it.each([
+ {
+ label: "FAILED",
+ terminalStatus: {
+ ...pendingStatus,
+ calendly_sync_status: "FAILED" as const,
+ },
+ expectedMessage: "confirmar",
+ },
+ {
+ label: "CANCELLED",
+ terminalStatus: {
+ ...syncedStatus,
+ status: "CANCELLED" as const,
+ },
+ expectedMessage: "cancelado",
+ },
+ ])(
+ "não considera $label com datetime/status incoerente como sincronização concluída",
+ async ({ terminalStatus, expectedMessage }) => {
+ vi.mocked(registerCalendlyScheduledEvent).mockResolvedValue({
+ appointment_id: "appointment-1",
+ calendly_sync_status: "PENDING",
+ appointment_datetime: null,
+ });
+ vi.mocked(getCalendlySyncStatus).mockResolvedValue(terminalStatus);
+ const onSynced = vi.fn();
+ const { result } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok", onSynced }),
+ );
+ act(() =>
+ result.current.openPopup(
+ "appointment-1",
+ "https://calendly.com/a",
+ ),
+ );
+ const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
+ .onEventScheduled!;
+
+ await act(async () => {
+ await listener(scheduledEvent());
+ });
+
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(1);
+ expect(getCalendlySyncStatus).toHaveBeenCalledTimes(1);
+ expect(onSynced).not.toHaveBeenCalled();
+ expect(navigate).not.toHaveBeenCalled();
+ expect(result.current.syncState).toBe("error");
+ expect(result.current.syncMessage).toContain(expectedMessage);
+ },
+ );
+
+ it("aceita redirect oficial de www.calendly.com para calendly.com no mesmo iframe", async () => {
vi.mocked(registerCalendlyScheduledEvent).mockResolvedValue({
appointment_id: "appointment-1",
- calendly_sync_status: "PENDING",
- appointment_datetime: null,
- });
- vi.mocked(getCalendlySyncStatus).mockResolvedValue({
- ...syncedStatus,
- status: "CANCELLED",
- calendly_sync_status: "FAILED",
+ calendly_sync_status: "SYNCED",
+ appointment_datetime: syncedStatus.appointment_datetime,
});
+ vi.mocked(getCalendlySyncStatus).mockResolvedValue(syncedStatus);
const onSynced = vi.fn();
const { result } = renderHook(() =>
useCalendlyScheduling({ successRedirectMessage: "ok", onSynced }),
);
- act(() => result.current.openPopup("appointment-1", "https://calendly.com/a"));
+ act(() =>
+ result.current.openPopup("appointment-1", "https://www.calendly.com/a"),
+ );
const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
.onEventScheduled!;
await act(async () => {
- await listener(scheduledEvent());
+ await listener(scheduledEvent({ origin: "https://calendly.com" }));
});
expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(1);
- expect(getCalendlySyncStatus).toHaveBeenCalledTimes(1);
- expect(onSynced).not.toHaveBeenCalled();
- expect(navigate).not.toHaveBeenCalled();
+ expect(onSynced).toHaveBeenCalledWith(syncedStatus);
+ expect(result.current.syncState).toBe("done");
});
it("ignora evento tardio enviado pelo iframe de uma sessão anterior A após abrir B", async () => {
@@ -251,14 +302,19 @@ describe("useCalendlyScheduling active registration retry", () => {
expect(getCalendlySyncStatus).not.toHaveBeenCalled();
});
- it("ignora mensagem de origem diferente da URL Calendly aberta", async () => {
+ it.each([
+ "https://evilcalendly.com",
+ "https://calendly.com.evil.test",
+ "http://calendly.com",
+ "https://calendly.com:444",
+ ])("ignora mensagem de origem Calendly maliciosa ou insegura: %s", async (origin) => {
const { result } = renderHook(() =>
useCalendlyScheduling({ successRedirectMessage: "ok" }),
);
act(() => result.current.openPopup("appointment-1", "https://calendly.com/a"));
const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
.onEventScheduled!;
- const forgedEvent = scheduledEvent({ origin: "https://evil.test" });
+ const forgedEvent = scheduledEvent({ origin });
await act(async () => {
await listener(forgedEvent);
diff --git a/frontend/src/hooks/useCalendlyScheduling.ts b/frontend/src/hooks/useCalendlyScheduling.ts
index cd713f9..b54051f 100644
--- a/frontend/src/hooks/useCalendlyScheduling.ts
+++ b/frontend/src/hooks/useCalendlyScheduling.ts
@@ -8,13 +8,16 @@ import {
} from "../services/appointments.service";
import {
isCalendlySyncComplete,
+ isCalendlySyncTerminalFailure,
synchronizeCalendlyRegistration,
} from "../services/calendly-sync";
+import { isTrustedCalendlyOrigin } from "../lib/calendly-origin";
export type CalendlySyncState =
| "idle"
| "waiting_event"
| "syncing"
+ | "pending"
| "done"
| "error";
@@ -72,18 +75,13 @@ export function useCalendlyScheduling({
return;
}
- let expectedOrigin: string | null = null;
- try {
- expectedOrigin = modalUrl ? new URL(modalUrl).origin : null;
- } catch {
- return;
- }
const currentFrame = document.querySelector(
".calendly-popup-content iframe",
);
if (
- !expectedOrigin ||
- event.origin !== expectedOrigin ||
+ !modalUrl ||
+ !isTrustedCalendlyOrigin(modalUrl) ||
+ !isTrustedCalendlyOrigin(event.origin) ||
!currentFrame?.contentWindow ||
event.source !== currentFrame.contentWindow
) {
@@ -143,8 +141,15 @@ export function useCalendlyScheduling({
state: { message: successRedirectMessage },
});
}, 900);
+ } else if (isCalendlySyncTerminalFailure(status)) {
+ setSyncState("error");
+ setSyncMessage(
+ status.status === "CANCELLED"
+ ? "O agendamento foi cancelado no Calendly. Verifique Meus Processos antes de tentar novamente."
+ : "Não foi possível confirmar o horário no Calendly. Verifique Meus Processos ou tente novamente.",
+ );
} else {
- setSyncState("done");
+ setSyncState("pending");
setSyncMessage(
"Solicitação registrada. Estamos finalizando a sincronização do horário com o calendário.",
);
diff --git a/frontend/src/lib/calendly-origin.ts b/frontend/src/lib/calendly-origin.ts
new file mode 100644
index 0000000..6934e66
--- /dev/null
+++ b/frontend/src/lib/calendly-origin.ts
@@ -0,0 +1,18 @@
+/**
+ * Accepts only Calendly's HTTPS origin family. Hostname boundary checks avoid
+ * lookalikes such as `evilcalendly.com` and `calendly.com.evil.test`.
+ */
+export function isTrustedCalendlyOrigin(value: string): boolean {
+ try {
+ const url = new URL(value);
+ const hostname = url.hostname.toLowerCase();
+
+ return (
+ url.protocol === "https:" &&
+ url.port === "" &&
+ (hostname === "calendly.com" || hostname.endsWith(".calendly.com"))
+ );
+ } catch {
+ return false;
+ }
+}
diff --git a/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx b/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx
index 7bb0ae5..74daafe 100644
--- a/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx
+++ b/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx
@@ -187,7 +187,7 @@ describe("delegated Calendly with the real Radix dialog and PopupModal", () => {
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
});
- it.each(["CONSULTANT", "OFFICE"])("synchronizes a real Calendly event before redirecting in %s mode", async (role) => {
+ it.each(["CONSULTANT", "OFFICE"])("does not call the client-only Calendly sync endpoint for delegated EMAIL flow in %s mode", async (role) => {
authState.user.role = role;
page();
await openCalendly();
@@ -196,24 +196,21 @@ describe("delegated Calendly with the real Radix dialog and PopupModal", () => {
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");
+ expect(registerCalendlyScheduledEvent).not.toHaveBeenCalled();
+ expect(getCalendlySyncStatus).not.toHaveBeenCalled();
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; }));
+ it("ignores a delegated Calendly event after the real popup is closed without attempting client-only sync", async () => {
page();
const { user, iframe } = await openCalendly();
+ await user.click(iframe.closest(".calendly-overlay")!.querySelector(".calendly-popup-close")!);
+ expect(await screen.findByRole("heading", { name: "Processos do consultor" })).toBeTruthy();
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(registerCalendlyScheduledEvent).not.toHaveBeenCalled();
expect(getCalendlySyncStatus).not.toHaveBeenCalled();
expect(screen.queryByTitle("Calendly Scheduling Page")).toBeNull();
});
diff --git a/frontend/src/pages/customer/ConsultoriaPage.test.tsx b/frontend/src/pages/customer/ConsultoriaPage.test.tsx
index f737215..dc883e2 100644
--- a/frontend/src/pages/customer/ConsultoriaPage.test.tsx
+++ b/frontend/src/pages/customer/ConsultoriaPage.test.tsx
@@ -8,10 +8,15 @@ 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() }));
+const { openPopup, useCalendlySchedulingMock } = vi.hoisted(() => ({
+ openPopup: vi.fn(),
+ useCalendlySchedulingMock: 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() }) }));
+vi.mock("../../hooks/useCalendlyScheduling", () => ({
+ useCalendlyScheduling: useCalendlySchedulingMock,
+}));
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) {
@@ -27,6 +32,14 @@ function renderPage() {
describe("ConsultoriaPage capability", () => {
beforeEach(() => {
+ useCalendlySchedulingMock.mockReturnValue({
+ isModalOpen: false,
+ modalUrl: null,
+ syncState: "idle",
+ syncMessage: null,
+ openPopup,
+ closePopup: vi.fn(),
+ });
mockSpecialist(specialist);
vi.mocked(createConsultancyAppointment).mockResolvedValue({ id: "appointment-1" } as never);
});
@@ -56,4 +69,22 @@ describe("ConsultoriaPage capability", () => {
expect(createConsultancyAppointment).not.toHaveBeenCalled();
expect(openPopup).not.toHaveBeenCalled();
});
+
+ it("renders a terminal Calendly synchronization failure as a danger alert", async () => {
+ useCalendlySchedulingMock.mockReturnValue({
+ isModalOpen: false,
+ modalUrl: null,
+ syncState: "error",
+ syncMessage: "O agendamento foi cancelado no Calendly.",
+ openPopup,
+ closePopup: vi.fn(),
+ });
+
+ renderPage();
+
+ const alert = await screen.findByRole("alert");
+ expect(alert.textContent).toContain("cancelado");
+ expect(alert.className).toContain("bg-status-bad-wash");
+ expect(alert.className).not.toContain("bg-status-ok-wash");
+ });
});
diff --git a/frontend/src/services/calendly-sync.ts b/frontend/src/services/calendly-sync.ts
index 50e5283..31b4dcf 100644
--- a/frontend/src/services/calendly-sync.ts
+++ b/frontend/src/services/calendly-sync.ts
@@ -17,7 +17,9 @@ export function isCalendlySyncComplete(status: CalendlySyncStatus): boolean {
);
}
-function isTerminal(status: CalendlySyncStatus): boolean {
+export function isCalendlySyncTerminalFailure(
+ status: CalendlySyncStatus,
+): boolean {
return (
status.calendly_sync_status === "FAILED" || status.status === "CANCELLED"
);
@@ -67,7 +69,10 @@ export async function synchronizeCalendlyRegistration(
try {
lastStatus = await getCalendlySyncStatus(appointmentId);
- if (isCalendlySyncComplete(lastStatus) || isTerminal(lastStatus)) {
+ if (
+ isCalendlySyncComplete(lastStatus) ||
+ isCalendlySyncTerminalFailure(lastStatus)
+ ) {
return lastStatus;
}
} catch (error) {
From 1c446b70e462115ad740ecc6a7132828e59ac233 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:54:46 -0300
Subject: [PATCH 44/60] fix(calendly): enforce event ownership and terminal
states
---
.../calendly-integration.service.spec.ts | 462 +++++++++++++-----
.../calendly-integration.service.ts | 99 ++--
.../appointments/calendly.controller.spec.ts | 64 +++
.../appointments/calendly.controller.ts | 6 +-
.../meetings/meetings.service.spec.ts | 30 ++
.../src/features/meetings/meetings.service.ts | 18 +-
...ses-rejection-concurrency.postgres.spec.ts | 29 ++
7 files changed, 558 insertions(+), 150 deletions(-)
create mode 100644 backend/src/features/appointments/calendly.controller.spec.ts
diff --git a/backend/src/features/appointments/calendly-integration.service.spec.ts b/backend/src/features/appointments/calendly-integration.service.spec.ts
index b7cd6d8..ff8ea84 100644
--- a/backend/src/features/appointments/calendly-integration.service.spec.ts
+++ b/backend/src/features/appointments/calendly-integration.service.spec.ts
@@ -1,9 +1,14 @@
import {
+ BadRequestException,
ConflictException,
ForbiddenException,
InternalServerErrorException,
} from '@nestjs/common';
-import { AppointmentSchedulingMethod } from '@prisma/client';
+import {
+ AppointmentSchedulingMethod,
+ CalendlySyncStatus,
+ StatusAgendamento,
+} from '@prisma/client';
import { CalendlyIntegrationService } from './calendly-integration.service';
import axios from 'axios';
import { createHmac } from 'crypto';
@@ -13,7 +18,7 @@ jest.mock('axios');
describe('CalendlyIntegrationService connection lifecycle', () => {
const originalEnv = { ...process.env };
beforeEach(() => {
- jest.clearAllMocks();
+ jest.resetAllMocks();
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';
@@ -29,15 +34,13 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
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' },
- }),
+ 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: {
@@ -45,26 +48,22 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
},
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,
- },
+ 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) };
}
@@ -145,8 +144,7 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
user_id: 'specialist-1',
access_token_encrypted: (service as any).encryptToken('access'),
calendly_user_uri: 'https://api.calendly.com/users/1',
- calendly_organization_uri:
- 'https://api.calendly.com/organizations/1',
+ calendly_organization_uri: 'https://api.calendly.com/organizations/1',
};
prisma.calendlyConnection.upsert.mockResolvedValue(connection);
Object.assign(prisma.calendlyConnection, {
@@ -165,17 +163,13 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
})
.mockRejectedValueOnce(new Error('subscription unavailable'));
- await expect(
- service.handleOAuthCallback('code', 'state'),
- ).resolves.toBe('specialist-1');
+ await expect(service.handleOAuthCallback('code', 'state')).resolves.toBe(
+ 'specialist-1',
+ );
expect(prisma.user.update).toHaveBeenCalledTimes(1);
expect(prisma.calendlyOauthState.update).toHaveBeenCalledTimes(1);
- expect(
- (prisma.calendlyConnection as any).update,
- ).not.toHaveBeenCalled();
- expect(
- (prisma.calendlyConnection as any).updateMany,
- ).toHaveBeenCalledWith({
+ expect((prisma.calendlyConnection as any).update).not.toHaveBeenCalled();
+ expect((prisma.calendlyConnection as any).updateMany).toHaveBeenCalledWith({
where: {
id: connection.id,
access_token_encrypted: connection.access_token_encrypted,
@@ -236,6 +230,7 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
id: 'connection-1',
user_id: 'specialist-1',
is_active: true,
+ calendly_user_uri: 'https://api.calendly.com/users/1',
expires_at: new Date(0),
access_token_encrypted: (service as any).encryptToken('expired-access'),
refresh_token_encrypted: (service as any).encryptToken('valid-refresh'),
@@ -293,20 +288,28 @@ 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' } },
- });
+ ])(
+ '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',
+ event_memberships: [{ user: 'https://api.calendly.com/users/1' }],
+ },
+ },
+ });
- 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 }),
- );
- });
+ 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();
@@ -331,15 +334,24 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
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',
+ 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',
+ },
},
- },
- });
+ })
+ .mockResolvedValueOnce({
+ data: {
+ resource: {
+ start_time: '2099-01-01T10:00:00.000Z',
+ event_memberships: [{ user: 'https://api.calendly.com/users/1' }],
+ },
+ },
+ });
await expect(
service.resolveScheduledStartTime(
@@ -383,15 +395,60 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
prisma.user.findUnique.mockResolvedValue({
email: ' Cliente@Example.com ',
});
- jest.mocked(axios.get).mockResolvedValueOnce({
- data: {
- resource: {
- email: 'cliente@example.COM',
- event: 'https://api.calendly.com/scheduled_events/event-1',
- start_time: '2099-01-01T10:00:00.000Z',
+ jest
+ .mocked(axios.get)
+ .mockResolvedValueOnce({
+ data: {
+ resource: {
+ email: 'cliente@example.COM',
+ event: 'https://api.calendly.com/scheduled_events/event-1',
+ start_time: '2099-01-01T10:00:00.000Z',
+ },
},
- },
- });
+ })
+ .mockResolvedValueOnce({
+ data: {
+ resource: {
+ start_time: '2099-01-01T10:00:00.000Z',
+ event_memberships: [{ user: 'https://api.calendly.com/users/1' }],
+ },
+ },
+ });
+
+ await expect(
+ service.resolveScheduledStartTime(
+ 'specialist-1',
+ 'https://api.calendly.com/scheduled_events/event-1',
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
+ 'client-1',
+ ),
+ ).resolves.toEqual(new Date('2099-01-01T10:00:00.000Z'));
+ });
+
+ it('rejeita horário do invitee quando o evento não pertence ao usuário Calendly conectado', async () => {
+ const { service, prisma } = makeRefreshService();
+ prisma.user.findUnique.mockResolvedValue({ email: 'cliente@example.com' });
+ jest
+ .mocked(axios.get)
+ .mockResolvedValueOnce({
+ data: {
+ resource: {
+ email: 'cliente@example.com',
+ event: 'https://api.calendly.com/scheduled_events/event-1',
+ start_time: '2099-01-01T10:00:00.000Z',
+ },
+ },
+ })
+ .mockResolvedValueOnce({
+ data: {
+ resource: {
+ start_time: '2099-01-01T10:00:00.000Z',
+ event_memberships: [
+ { user: 'https://api.calendly.com/users/another-user' },
+ ],
+ },
+ },
+ });
await expect(
service.resolveScheduledStartTime(
@@ -400,7 +457,68 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
'client-1',
),
+ ).rejects.toThrow('Evento do Calendly não pertence ao especialista');
+ expect(axios.get).toHaveBeenCalledTimes(2);
+ expect(prisma.calendlyConnection.update).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ undefined,
+ null,
+ {},
+ { resource: null },
+ { resource: { start_time: '2099-01-01T10:00:00.000Z' } },
+ {
+ resource: {
+ start_time: '2099-01-01T10:00:00.000Z',
+ event_memberships: {},
+ },
+ },
+ ])(
+ 'falha fechado para shape de evento Calendly inválido: %p',
+ async (data) => {
+ const { service, prisma } = makeRefreshService();
+ jest.mocked(axios.get).mockResolvedValueOnce({ data });
+
+ await expect(
+ service.resolveScheduledStartTime(
+ 'specialist-1',
+ 'https://api.calendly.com/scheduled_events/event-1',
+ ),
+ ).rejects.toBeInstanceOf(BadRequestException);
+ expect(prisma.calendlyConnection.update).not.toHaveBeenCalled();
+ },
+ );
+
+ it('usa o horário autoritativo do evento após validar a membership', async () => {
+ const { service } = makeRefreshService();
+ jest
+ .mocked(axios.get)
+ .mockResolvedValueOnce({
+ data: {
+ resource: {
+ event: 'https://api.calendly.com/scheduled_events/event-1',
+ start_time: '2099-01-01T09:00:00.000Z',
+ },
+ },
+ })
+ .mockResolvedValueOnce({
+ data: {
+ resource: {
+ start_time: '2099-01-01T10:00:00.000Z',
+ event_memberships: [{ user: 'https://api.calendly.com/users/1' }],
+ },
+ },
+ });
+
+ await expect(
+ service.resolveScheduledStartTime(
+ 'specialist-1',
+ 'https://api.calendly.com/scheduled_events/event-1',
+ 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
+ ),
).resolves.toEqual(new Date('2099-01-01T10:00:00.000Z'));
+ expect(axios.get).toHaveBeenCalledTimes(2);
});
it('rejeita URI de evento não confiável retornada pelo recurso de convidado', async () => {
@@ -425,17 +543,20 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
.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,
+ resource: {
+ start_time: '2099-01-01T10:00:00.000Z',
+ event_memberships: [{ user: 'https://api.calendly.com/users/1' }],
+ },
},
});
+ jest.mocked(axios.post).mockResolvedValue({
+ data: {
+ access_token: 'renewed-access',
+ refresh_token: 'renewed-refresh',
+ expires_in: 3600,
+ },
+ });
expect(
await service.resolveScheduledStartTime(
'specialist-1',
@@ -487,6 +608,7 @@ describe('CalendlyIntegrationService connection lifecycle', () => {
user_id: 'specialist-1',
is_active: true,
last_error: null as string | null,
+ calendly_user_uri: 'https://api.calendly.com/users/1',
access_token_encrypted: (service as any).encryptToken('old-access'),
refresh_token_encrypted: (service as any).encryptToken('old-refresh'),
};
@@ -632,10 +754,7 @@ describe('CalendlyIntegrationService webhook authentication', () => {
const { service } = makeService();
expect(() =>
- (service as any).validateWebhookSignature(
- rawBody,
- signature(timestamp),
- ),
+ (service as any).validateWebhookSignature(rawBody, signature(timestamp)),
).toThrow(ForbiddenException);
});
@@ -668,12 +787,13 @@ describe('CalendlyIntegrationService webhook authentication', () => {
id: 'connection-1',
user_id: 'specialist-1',
calendly_user_uri: 'https://api.calendly.com/users/user-1',
- calendly_organization_uri:
- 'https://api.calendly.com/organizations/org-1',
+ calendly_organization_uri: 'https://api.calendly.com/organizations/org-1',
access_token_encrypted: (service as any).encryptToken('access-token'),
};
prisma.calendlyConnection.findUnique.mockResolvedValue(connection);
- jest.mocked(axios.post).mockRejectedValueOnce({ response: { status: 422 } });
+ jest
+ .mocked(axios.post)
+ .mockRejectedValueOnce({ response: { status: 422 } });
await expect(
(service as any).ensureWebhookSubscription('specialist-1'),
@@ -704,10 +824,8 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
{
event: 'invitee.created',
payload: {
- event:
- 'https://api.calendly.com/scheduled_events/event-1',
- uri:
- 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-official',
+ event: 'https://api.calendly.com/scheduled_events/event-1',
+ uri: 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-official',
invitee:
'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-legacy',
},
@@ -727,8 +845,7 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
const appointment = {
id: 'appointment-1',
specialist_id: 'specialist-1',
- calendly_event_uri:
- 'https://api.calendly.com/scheduled_events/event-1',
+ calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1',
scheduling_method: method,
specialist_rescheduled_at: null,
};
@@ -765,8 +882,7 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
const appointment = {
id: 'appointment-1',
specialist_id: 'specialist-1',
- calendly_event_uri:
- 'https://api.calendly.com/scheduled_events/event-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'),
};
@@ -836,10 +952,8 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
{
event: 'invitee.created',
payload: {
- event:
- 'https://calendly.com/api/v2/scheduled_events/event-1',
- uri:
- 'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1',
+ event: 'https://calendly.com/api/v2/scheduled_events/event-1',
+ uri: 'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1',
scheduled_event: {
start_time: '2099-01-01T10:00:00.000Z',
},
@@ -888,6 +1002,136 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
expect(prisma.appointment.update).not.toHaveBeenCalled();
});
+ it('não ressuscita sync cancelado quando invitee.created chega depois ou é repetido', async () => {
+ const appointment = {
+ id: 'appointment-1',
+ client_id: 'client-1',
+ specialist_id: 'specialist-1',
+ status: StatusAgendamento.PENDING,
+ 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_sync_status: CalendlySyncStatus.PENDING,
+ appointment_datetime: null,
+ scheduling_method: AppointmentSchedulingMethod.CALENDLY,
+ specialist_rescheduled_at: null,
+ };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn(async () => ({ ...appointment })),
+ findFirst: jest.fn().mockResolvedValue(null),
+ update: jest.fn(async ({ data }) => Object.assign(appointment, data)),
+ updateMany: jest.fn(async ({ data }) => {
+ Object.assign(appointment, data);
+ return { count: 1 };
+ }),
+ },
+ };
+ const prisma = {
+ appointment: {
+ findMany: jest.fn(async () => [{ ...appointment }]),
+ },
+ $transaction: jest.fn(async (callback: (client: any) => unknown) =>
+ callback(tx),
+ ),
+ };
+ const service = new CalendlyIntegrationService(prisma as any);
+ jest
+ .spyOn(service as any, 'validateWebhookSignature')
+ .mockReturnValue(undefined);
+ const payload = {
+ event: appointment.calendly_event_uri,
+ uri: appointment.calendly_invitee_uri,
+ scheduled_event: { start_time: '2099-01-01T10:00:00.000Z' },
+ };
+
+ await expect(
+ service.processWebhook(
+ { event: 'invitee.canceled', payload },
+ undefined,
+ undefined,
+ ),
+ ).resolves.toMatchObject({ processed: true });
+ expect(appointment.calendly_sync_status).toBe(CalendlySyncStatus.FAILED);
+
+ for (let replay = 0; replay < 2; replay += 1) {
+ await expect(
+ service.processWebhook(
+ { event: 'invitee.created', payload },
+ undefined,
+ undefined,
+ ),
+ ).resolves.toEqual({
+ processed: false,
+ message: 'Webhook ignorado para preservar a associação atual',
+ });
+ }
+ expect(tx.appointment.update).not.toHaveBeenCalled();
+ expect(appointment.calendly_sync_status).toBe(CalendlySyncStatus.FAILED);
+ });
+
+ it.each([
+ [StatusAgendamento.COMPLETED, 'invitee.created'],
+ [StatusAgendamento.CANCELLED, 'invitee.created'],
+ [StatusAgendamento.COMPLETED, 'invitee.canceled'],
+ [StatusAgendamento.CANCELLED, 'invitee.canceled'],
+ ] as const)(
+ 'não muta appointment terminal %s com %s',
+ async (status, eventType) => {
+ const appointment = {
+ id: 'appointment-1',
+ client_id: 'client-1',
+ specialist_id: 'specialist-1',
+ status,
+ 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_sync_status: CalendlySyncStatus.PENDING,
+ appointment_datetime: new Date('2099-01-01T09:00:00.000Z'),
+ scheduling_method: AppointmentSchedulingMethod.CALENDLY,
+ specialist_rescheduled_at: null,
+ };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ appointment: {
+ findUnique: jest.fn().mockResolvedValue(appointment),
+ findFirst: jest.fn(),
+ update: jest.fn(),
+ updateMany: jest.fn(),
+ },
+ };
+ const prisma = {
+ appointment: { findMany: jest.fn().mockResolvedValue([appointment]) },
+ $transaction: jest.fn(async (callback: (client: any) => unknown) =>
+ callback(tx),
+ ),
+ };
+ const service = new CalendlyIntegrationService(prisma as any);
+ jest
+ .spyOn(service as any, 'validateWebhookSignature')
+ .mockReturnValue(undefined);
+
+ await expect(
+ service.processWebhook(
+ {
+ event: eventType,
+ payload: {
+ event: appointment.calendly_event_uri,
+ uri: appointment.calendly_invitee_uri,
+ scheduled_event: { start_time: '2099-01-01T10:00:00.000Z' },
+ },
+ },
+ undefined,
+ undefined,
+ ),
+ ).resolves.toMatchObject({ processed: false });
+ expect(tx.appointment.findFirst).not.toHaveBeenCalled();
+ expect(tx.appointment.update).not.toHaveBeenCalled();
+ expect(tx.appointment.updateMany).not.toHaveBeenCalled();
+ },
+ );
+
it('encontra e canonicaliza registro legado ao cancelar pelo webhook', async () => {
const appointment = {
id: 'appointment-1',
@@ -924,10 +1168,8 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
{
event: 'invitee.canceled',
payload: {
- event:
- 'https://api.calendly.com/scheduled_events/event-1',
- uri:
- 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
+ event: 'https://api.calendly.com/scheduled_events/event-1',
+ uri: 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1',
},
} as any,
undefined,
@@ -956,8 +1198,7 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
calendly_invitee_uri: appointment.calendly_invitee_uri,
},
data: {
- calendly_event_uri:
- 'https://api.calendly.com/scheduled_events/event-1',
+ 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),
@@ -995,8 +1236,7 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
{
event: 'invitee.created',
payload: {
- event:
- 'https://api.calendly.com/scheduled_events/group-event',
+ event: 'https://api.calendly.com/scheduled_events/group-event',
},
},
undefined,
@@ -1023,8 +1263,7 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
specialist_id: 'specialist-1',
scheduling_method: AppointmentSchedulingMethod.CALENDLY,
specialist_rescheduled_at: null,
- calendly_event_uri:
- 'https://api.calendly.com/scheduled_events/event-1',
+ calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1',
calendly_invitee_uri:
'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-old',
};
@@ -1057,8 +1296,7 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
{
event: 'invitee.created',
payload: {
- event:
- 'https://api.calendly.com/scheduled_events/event-1',
+ event: 'https://api.calendly.com/scheduled_events/event-1',
uri: snapshot.calendly_invitee_uri,
scheduled_event: { start_time: '2099-01-01T10:00:00.000Z' },
},
@@ -1081,8 +1319,7 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
specialist_id: 'specialist-1',
scheduling_method: AppointmentSchedulingMethod.CALENDLY,
specialist_rescheduled_at: null,
- calendly_event_uri:
- 'https://api.calendly.com/scheduled_events/event-1',
+ 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',
};
@@ -1130,8 +1367,7 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => {
specialist_id: 'specialist-1',
scheduling_method: AppointmentSchedulingMethod.CALENDLY,
specialist_rescheduled_at: null,
- calendly_event_uri:
- 'https://api.calendly.com/scheduled_events/event-1',
+ calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1',
calendly_invitee_uri:
'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-old',
};
diff --git a/backend/src/features/appointments/calendly-integration.service.ts b/backend/src/features/appointments/calendly-integration.service.ts
index d2a67a8..a0b4c5d 100644
--- a/backend/src/features/appointments/calendly-integration.service.ts
+++ b/backend/src/features/appointments/calendly-integration.service.ts
@@ -10,6 +10,7 @@ import {
import {
AppointmentSchedulingMethod,
CalendlySyncStatus,
+ StatusAgendamento,
UserRole,
} from '@prisma/client';
import axios from 'axios';
@@ -268,8 +269,7 @@ export class CalendlyIntegrationService {
await this.prisma.calendlyConnection.updateMany({
where: {
id: upsertedConnection.id,
- access_token_encrypted:
- upsertedConnection.access_token_encrypted,
+ access_token_encrypted: upsertedConnection.access_token_encrypted,
is_active: true,
},
data: { last_error: 'webhook_subscription_failed' },
@@ -329,6 +329,14 @@ export class CalendlyIntegrationService {
if (!connection || !connection.is_active) {
return null;
}
+ if (
+ typeof connection.calendly_user_uri !== 'string' ||
+ !connection.calendly_user_uri.trim()
+ ) {
+ throw new BadRequestException(
+ 'Conexão Calendly sem identidade de usuário válida',
+ );
+ }
const inviteeData = inviteeReference
? await this.getCalendlyResourceWithRefresh(
@@ -338,7 +346,9 @@ export class CalendlyIntegrationService {
)
: null;
- const inviteeResource = inviteeData?.resource || inviteeData;
+ const inviteeResource = inviteeReference
+ ? this.requireCalendlyResource(inviteeData, 'convidado')
+ : null;
if (expectedClientId) {
const client = await this.prisma.user.findUnique({
where: { id: expectedClientId },
@@ -366,22 +376,6 @@ export class CalendlyIntegrationService {
inviteeReference,
inviteeEventReference,
);
- const inviteeStartTime =
- inviteeResource?.start_time ||
- inviteeResource?.event_start_time ||
- inviteeData?.payload?.scheduled_event?.start_time;
-
- if (inviteeStartTime) {
- const parsed = parseDate(inviteeStartTime);
- if (parsed) {
- await this.prisma.calendlyConnection.update({
- where: { id: connection.id },
- data: { last_sync_at: new Date(), last_error: null },
- });
- return parsed;
- }
- }
-
const resolvedEventUri =
eventReference?.canonicalUri ||
inviteeEventReference?.canonicalUri ||
@@ -395,10 +389,33 @@ export class CalendlyIntegrationService {
resolvedEventUri,
'event',
);
- const eventResource = eventData?.resource || eventData;
- const eventStartTime =
- eventResource?.start_time ||
- eventData?.payload?.scheduled_event?.start_time;
+ const eventResource = this.requireCalendlyResource(eventData, 'evento');
+ if (
+ !Array.isArray(eventResource.event_memberships) ||
+ eventResource.event_memberships.some(
+ (membership: unknown) =>
+ !membership ||
+ typeof membership !== 'object' ||
+ typeof (membership as { user?: unknown }).user !== 'string',
+ )
+ ) {
+ throw new BadRequestException(
+ 'Calendly retornou memberships de evento inválidas',
+ );
+ }
+ const connectedUserUri = connection.calendly_user_uri.trim();
+ if (
+ !eventResource.event_memberships.some(
+ (membership: { user: string }) =>
+ membership.user.trim() === connectedUserUri,
+ )
+ ) {
+ throw new BadRequestException(
+ 'Evento do Calendly não pertence ao especialista conectado',
+ );
+ }
+
+ const eventStartTime = eventResource.start_time;
if (!eventStartTime) {
return null;
@@ -417,6 +434,26 @@ export class CalendlyIntegrationService {
return parsed;
}
+ private requireCalendlyResource(
+ data: unknown,
+ kind: 'evento' | 'convidado',
+ ): Record {
+ if (
+ !data ||
+ typeof data !== 'object' ||
+ !('resource' in data) ||
+ !(data as { resource?: unknown }).resource ||
+ typeof (data as { resource?: unknown }).resource !== 'object' ||
+ Array.isArray((data as { resource?: unknown }).resource)
+ ) {
+ throw new BadRequestException(
+ `Calendly retornou ${kind} com formato inválido`,
+ );
+ }
+
+ return (data as { resource: Record }).resource;
+ }
+
async processWebhook(
body: CalendlyWebhookPayload,
rawBody: string | undefined,
@@ -468,8 +505,7 @@ export class CalendlyIntegrationService {
'URIs de convidado do Calendly são inconsistentes',
);
}
- const inviteeReference =
- officialInviteeReference || legacyInviteeReference;
+ const inviteeReference = officialInviteeReference || legacyInviteeReference;
this.assertSameCalendlyEvent(eventReference, inviteeReference);
const lookupEventReference =
eventReference ||
@@ -547,7 +583,11 @@ export class CalendlyIntegrationService {
(lockedAppointment.scheduling_method &&
lockedAppointment.scheduling_method !==
AppointmentSchedulingMethod.CALENDLY) ||
- lockedAppointment.specialist_rescheduled_at
+ lockedAppointment.specialist_rescheduled_at ||
+ lockedAppointment.calendly_sync_status ===
+ CalendlySyncStatus.FAILED ||
+ lockedAppointment.status === StatusAgendamento.COMPLETED ||
+ lockedAppointment.status === StatusAgendamento.CANCELLED
) {
return false;
}
@@ -613,6 +653,8 @@ export class CalendlyIntegrationService {
lockedAppointment.scheduling_method !==
AppointmentSchedulingMethod.CALENDLY) ||
lockedAppointment.specialist_rescheduled_at ||
+ lockedAppointment.status === StatusAgendamento.COMPLETED ||
+ lockedAppointment.status === StatusAgendamento.CANCELLED ||
!this.appointmentStillMatchesWebhook(
lockedAppointment,
lookupEventReference,
@@ -1003,10 +1045,7 @@ export class CalendlyIntegrationService {
): boolean {
if (inviteeReference) {
const currentInvitee = appointment.calendly_invitee_uri
- ? parseCalendlyResourceUri(
- appointment.calendly_invitee_uri,
- 'invitee',
- )
+ ? parseCalendlyResourceUri(appointment.calendly_invitee_uri, 'invitee')
: null;
return currentInvitee?.canonicalUri === inviteeReference.canonicalUri;
}
diff --git a/backend/src/features/appointments/calendly.controller.spec.ts b/backend/src/features/appointments/calendly.controller.spec.ts
new file mode 100644
index 0000000..915efb4
--- /dev/null
+++ b/backend/src/features/appointments/calendly.controller.spec.ts
@@ -0,0 +1,64 @@
+import { CalendlyController } from './calendly.controller';
+
+describe('CalendlyController OAuth callback public errors', () => {
+ const originalFrontendUrl = process.env.FRONTEND_URL;
+
+ beforeAll(() => {
+ process.env.FRONTEND_URL = 'https://frontend.example.test';
+ });
+
+ afterAll(() => {
+ if (originalFrontendUrl === undefined) {
+ delete process.env.FRONTEND_URL;
+ } else {
+ process.env.FRONTEND_URL = originalFrontendUrl;
+ }
+ });
+
+ function responseHarness() {
+ return { redirect: jest.fn((url: string) => url) } as any;
+ }
+
+ it('não expõe error_description arbitrária devolvida pelo provedor', async () => {
+ const controller = new CalendlyController({} as any);
+ const response = responseHarness();
+ const secret = 'client_secret=very-sensitive-value';
+
+ await controller.oauthCallback(
+ undefined,
+ undefined,
+ 'access_denied',
+ secret,
+ response,
+ );
+
+ const redirect = response.redirect.mock.calls[0][0];
+ expect(redirect).toBe(
+ 'https://frontend.example.test/profile?calendly=error&reason=oauth_denied',
+ );
+ expect(redirect).not.toContain('very-sensitive-value');
+ });
+
+ it('não expõe detalhes internos de falha do callback', async () => {
+ const secret = 'upstream access_token=very-sensitive-value';
+ const service = {
+ handleOAuthCallback: jest.fn().mockRejectedValue(new Error(secret)),
+ };
+ const controller = new CalendlyController(service as any);
+ const response = responseHarness();
+
+ await controller.oauthCallback(
+ 'code',
+ 'state',
+ undefined,
+ undefined,
+ response,
+ );
+
+ const redirect = response.redirect.mock.calls[0][0];
+ expect(redirect).toBe(
+ 'https://frontend.example.test/profile?calendly=error&reason=oauth_callback_failed',
+ );
+ expect(redirect).not.toContain('very-sensitive-value');
+ });
+});
diff --git a/backend/src/features/appointments/calendly.controller.ts b/backend/src/features/appointments/calendly.controller.ts
index ad3b79f..279a0cc 100644
--- a/backend/src/features/appointments/calendly.controller.ts
+++ b/backend/src/features/appointments/calendly.controller.ts
@@ -76,7 +76,7 @@ export class CalendlyController {
const isGoogleDomainBlocked =
/google.*(domain|workspace)|domain.*denied/i.test(rawReason);
const reason = encodeURIComponent(
- isGoogleDomainBlocked ? 'google_domain_blocked' : rawReason,
+ isGoogleDomainBlocked ? 'google_domain_blocked' : 'oauth_denied',
);
return res.redirect(
`${frontendUrl}/profile?calendly=error&reason=${reason}`,
@@ -101,7 +101,9 @@ export class CalendlyController {
const isGoogleDomainBlocked =
/google.*(domain|workspace)|domain.*denied/i.test(rawReason);
const reason = encodeURIComponent(
- isGoogleDomainBlocked ? 'google_domain_blocked' : rawReason,
+ isGoogleDomainBlocked
+ ? 'google_domain_blocked'
+ : 'oauth_callback_failed',
);
return res.redirect(
diff --git a/backend/src/features/meetings/meetings.service.spec.ts b/backend/src/features/meetings/meetings.service.spec.ts
index 30f275c..badb440 100644
--- a/backend/src/features/meetings/meetings.service.spec.ts
+++ b/backend/src/features/meetings/meetings.service.spec.ts
@@ -18,6 +18,13 @@ function mkProcess(overrides: any = {}) {
client_id: 'client-1',
specialist_id: 'spec-1',
status: 'SCHEDULING',
+ appointment_id: 'appointment-1',
+ appointment: {
+ id: 'appointment-1',
+ client_id: 'client-1',
+ specialist_id: 'spec-1',
+ status: StatusAgendamento.SCHEDULED,
+ },
meeting_session: null,
client: {
id: 'client-1',
@@ -489,6 +496,29 @@ describe('MeetingsService — criação via Meet REST API', () => {
});
describe('MeetingsService.startMeetingForProcess — serialização canônica', () => {
+ it('não cria claim enquanto o appointment ainda está PENDING', async () => {
+ const process = mkProcess({
+ appointment: {
+ id: 'appointment-1',
+ client_id: 'client-1',
+ specialist_id: 'spec-1',
+ status: StatusAgendamento.PENDING,
+ },
+ });
+ const prisma = mkPrisma(process);
+ const service = new MeetingsService(
+ prisma,
+ mkConfig('OPEN', 'JITSI'),
+ notification,
+ {} as any,
+ );
+
+ await expect(
+ service.startMeetingForProcess(process.id, 'spec-1'),
+ ).rejects.toThrow('Agendamento não está confirmado');
+ expect(prisma.meetingSession.create).not.toHaveBeenCalled();
+ });
+
it('remove o claim se a revalidação final encontrar processo terminal', async () => {
const process = mkProcess();
const prisma = mkPrisma(process);
diff --git a/backend/src/features/meetings/meetings.service.ts b/backend/src/features/meetings/meetings.service.ts
index e3e3d2b..a44c5e7 100644
--- a/backend/src/features/meetings/meetings.service.ts
+++ b/backend/src/features/meetings/meetings.service.ts
@@ -146,16 +146,24 @@ export class MeetingsService {
);
}
if (
- Boolean(process.appointment) !== Boolean(process.appointment_id) ||
- (process.appointment &&
- (process.appointment.id !== process.appointment_id ||
- process.appointment.client_id !== process.client_id ||
- process.appointment.specialist_id !== process.specialist_id))
+ !process.appointment_id ||
+ !process.appointment ||
+ process.appointment.id !== process.appointment_id ||
+ process.appointment.client_id !== process.client_id ||
+ process.appointment.specialist_id !== process.specialist_id
) {
throw new BadRequestException(
'Agendamento não corresponde aos participantes do processo',
);
}
+ if (
+ process.appointment.status !== StatusAgendamento.SCHEDULED &&
+ process.appointment.status !== StatusAgendamento.COMPLETED
+ ) {
+ throw new BadRequestException(
+ 'Agendamento não está confirmado para iniciar reunião',
+ );
+ }
if (
process.status !== ProcessStatus.SCHEDULING &&
process.status !== ProcessStatus.NEGOTIATION &&
diff --git a/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts b/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts
index 5db5542..7f8fd6d 100644
--- a/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts
+++ b/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts
@@ -4,6 +4,7 @@ import {
ProcessStatus,
ProductCurrency,
ProductType,
+ StatusAgendamento,
UserRole,
} from '@prisma/client';
import { randomUUID } from 'node:crypto';
@@ -160,6 +161,7 @@ describeWithPostgres('process rejection CAS — PostgreSQL concurrency', () => {
const specialistId = randomUUID();
const carId = randomUUID();
const processId = randomUUID();
+ const appointmentId = randomUUID();
const rejectClient = new PrismaClient({
datasources: {
db: { url: withApplicationName(prismaDatabaseUrl, `reject_a_${suffix}`) },
@@ -218,6 +220,9 @@ describeWithPostgres('process rejection CAS — PostgreSQL concurrency', () => {
where: { processId },
});
await completionClient.process.deleteMany({ where: { id: processId } });
+ await completionClient.appointment.deleteMany({
+ where: { id: appointmentId },
+ });
});
afterAll(async () => {
@@ -228,6 +233,9 @@ describeWithPostgres('process rejection CAS — PostgreSQL concurrency', () => {
where: { processId },
});
await completionClient.process.deleteMany({ where: { id: processId } });
+ await completionClient.appointment.deleteMany({
+ where: { id: appointmentId },
+ });
await completionClient.car.deleteMany({ where: { id: carId } });
await completionClient.user.deleteMany({
where: { id: { in: [clientId, specialistId] } },
@@ -238,6 +246,21 @@ describeWithPostgres('process rejection CAS — PostgreSQL concurrency', () => {
]);
});
+ async function createConfirmedAppointment() {
+ await completionClient.appointment.create({
+ data: {
+ id: appointmentId,
+ client_id: clientId,
+ specialist_id: specialistId,
+ appointment_datetime: new Date('2099-01-01T10:00:00.000Z'),
+ // Rejeição de processo bloqueia appointments ativos
+ // (PENDING/SCHEDULED); COMPLETED mantém esta fixture focada apenas
+ // na serialização entre rejeição e criação da reunião.
+ status: StatusAgendamento.COMPLETED,
+ },
+ });
+ }
+
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({
@@ -403,11 +426,13 @@ describeWithPostgres('process rejection CAS — PostgreSQL concurrency', () => {
}, 15_000);
it('não cria reunião nem envia e-mail quando a rejeição ganha o lock', async () => {
+ await createConfirmedAppointment();
await completionClient.process.create({
data: {
id: processId,
client_id: clientId,
specialist_id: specialistId,
+ appointment_id: appointmentId,
status: ProcessStatus.SCHEDULING,
},
});
@@ -462,11 +487,13 @@ describeWithPostgres('process rejection CAS — PostgreSQL concurrency', () => {
}, 15_000);
it('mantém reunião e recusa rejeição quando o início ganha o lock', async () => {
+ await createConfirmedAppointment();
await completionClient.process.create({
data: {
id: processId,
client_id: clientId,
specialist_id: specialistId,
+ appointment_id: appointmentId,
status: ProcessStatus.SCHEDULING,
},
});
@@ -527,11 +554,13 @@ describeWithPostgres('process rejection CAS — PostgreSQL concurrency', () => {
}, 15_000);
it('libera pool connection_limit=1 durante provider e impede start/e-mail duplicado', async () => {
+ await createConfirmedAppointment();
await completionClient.process.create({
data: {
id: processId,
client_id: clientId,
specialist_id: specialistId,
+ appointment_id: appointmentId,
status: ProcessStatus.SCHEDULING,
},
});
From bc0462de52be2107bc3b8f1f16eb002852e71bc9 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 12:55:33 -0300
Subject: [PATCH 45/60] fix(frontend): close scheduling lifecycle gaps
---
.../components/processes/ProcessCard.test.tsx | 33 ++
.../src/components/processes/ProcessCard.tsx | 8 +-
.../StartProcessForClientModal.test.tsx | 510 +++++++++---------
.../processes/StartProcessForClientModal.tsx | 119 +---
.../src/hooks/useCalendlyScheduling.test.tsx | 108 ++++
frontend/src/hooks/useCalendlyScheduling.ts | 77 ++-
.../src/pages/catalog/ProductPage.test.tsx | 2 +-
frontend/src/pages/catalog/ProductPage.tsx | 15 +-
8 files changed, 452 insertions(+), 420 deletions(-)
diff --git a/frontend/src/components/processes/ProcessCard.test.tsx b/frontend/src/components/processes/ProcessCard.test.tsx
index 019d966..684a46b 100644
--- a/frontend/src/components/processes/ProcessCard.test.tsx
+++ b/frontend/src/components/processes/ProcessCard.test.tsx
@@ -121,6 +121,39 @@ describe("ProcessCard appointment time actions", () => {
expect(screen.getByText("Aguardando sincronização do Calendly")).toBeTruthy();
});
+ it("tells the client that a pending Calendly request is synchronizing, not awaiting specialist confirmation", () => {
+ renderCard(
+ {
+ ...baseProcess,
+ appointment_scheduling_method: "CALENDLY",
+ },
+ { isClientView: true },
+ );
+
+ expect(screen.getByText("Aguardando sincronização do Calendly")).toBeTruthy();
+ expect(
+ screen.queryByText("Aguardando confirmação do especialista"),
+ ).toBeNull();
+ });
+
+ it("labels a provisional Calendly datetime as synchronizing", () => {
+ renderCard(
+ {
+ ...baseProcess,
+ appointment_scheduling_method: "CALENDLY",
+ appointment_datetime: "2099-09-20T17:30:00.000Z",
+ },
+ { isClientView: true },
+ );
+
+ expect(
+ screen.getAllByText(/aguardando sincronização do Calendly/i),
+ ).toHaveLength(2);
+ expect(
+ screen.queryByText(/aguardando confirmação do especialista/i),
+ ).toBeNull();
+ });
+
it("lets the specialist recover a legacy undated request", () => {
renderCard({
...baseProcess,
diff --git a/frontend/src/components/processes/ProcessCard.tsx b/frontend/src/components/processes/ProcessCard.tsx
index 05e0604..29b8013 100644
--- a/frontend/src/components/processes/ProcessCard.tsx
+++ b/frontend/src/components/processes/ProcessCard.tsx
@@ -573,7 +573,9 @@ export default function ProcessCard({
{formattedAppointmentTime}
{isAppointmentConfirmed
? "."
- : " (aguardando confirmação do especialista)."}
+ : process.appointment_scheduling_method === "CALENDLY"
+ ? " (aguardando sincronização do Calendly)."
+ : " (aguardando confirmação do especialista)."}
)}
{process.specialist_rescheduled_at && (
@@ -589,7 +591,9 @@ export default function ProcessCard({
{isClientView
- ? "Aguardando confirmação do especialista"
+ ? process.appointment_scheduling_method === "CALENDLY"
+ ? "Aguardando sincronização do Calendly"
+ : "Aguardando confirmação do especialista"
: "Solicitação de agendamento"}
{dateTimeActionError && dateTimeAction === null && (
diff --git a/frontend/src/components/processes/StartProcessForClientModal.test.tsx b/frontend/src/components/processes/StartProcessForClientModal.test.tsx
index 35b0333..0e9e393 100644
--- a/frontend/src/components/processes/StartProcessForClientModal.test.tsx
+++ b/frontend/src/components/processes/StartProcessForClientModal.test.tsx
@@ -1,334 +1,304 @@
// @vitest-environment jsdom
-import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+} from "@testing-library/react";
import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useCalendlyEventListener } from "react-calendly";
import StartProcessForClientModal from "./StartProcessForClientModal";
-import { createConsultantProcess, getClients, type Client } from "../../services/consultant.service";
-import { getPublicSpecialistById, type PublicSpecialistProfile } from "../../services/specialists.service";
-import { getUserById } from "../../services/users.service";
+import {
+ createConsultantProcess,
+ getClients,
+ type Client,
+} from "../../services/consultant.service";
import { officeService } from "../../services/office";
-import { getCalendlySyncStatus, registerCalendlyScheduledEvent } from "../../services/appointments.service";
-import { useCalendlyEventListener } from "react-calendly";
-
-const { popupClosers } = vi.hoisted(() => ({ popupClosers: [] as Array<() => void> }));
-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/specialists.service", () => ({ getPublicSpecialistById: vi.fn() }));
-vi.mock("../../services/users.service", () => ({ getUserById: vi.fn() }));
-vi.mock("../../services/appointments.service", () => ({ getCalendlySyncStatus: vi.fn(), registerCalendlyScheduledEvent: vi.fn() }));
-vi.mock("react-calendly", () => ({
- PopupModal: ({ url, prefill, onModalClose }: { url: string; prefill: { name?: string; email?: string }; onModalClose(): void }) => {
- popupClosers.push(onModalClose);
- return <>
Agendar no Calendly Fechar Calendly >;
- },
- useCalendlyEventListener: 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("react-calendly", () => ({ useCalendlyEventListener: vi.fn() }));
+
+const client: Client = {
+ id: "customer-1",
+ name: "Cliente",
+ surname: "Teste",
+ email: "cliente@example.com",
+ cpf: "12345678900",
+ rg: "12345678",
+ role: "CUSTOMER",
+};
+const secondClient: Client = {
+ ...client,
+ id: "customer-2",
+ name: "Outro",
+ email: "outro@example.com",
+};
-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"; onCalendlyOpenChange?(open: boolean): void } = {}, visible = true) {
- return
{visible && };
+function Location() {
+ return
{useLocation().pathname}
;
+}
+
+function scopeContent(
+ props: {
+ specialistId?: string;
+ productType?: "CAR" | "BOAT" | "AIRCRAFT";
+ productId?: string;
+ mode?: "CONSULTANT" | "OFFICE";
+ productLabel?: string;
+ onBusyChange?(busy: boolean): void;
+ } = {},
+ visible = true,
+) {
+ return (
+
+
+ {visible && (
+
+ )}
+
+ );
}
function renderModal(mode: "CONSULTANT" | "OFFICE" = "CONSULTANT") {
- return render(
- } />
- Processos do consultor} />
- Processos do escritório} />
- );
+ return render(
+
+
+
+ }
+ />
+ Processos do consultor} />
+ Processos do escritório} />
+
+ ,
+ );
}
async function selectAndCreate() {
- fireEvent.click(await screen.findByRole("button", { name: /Cliente Teste/i }));
+ fireEvent.click(
+ await screen.findByRole("button", { name: /Cliente Teste/i }),
+ );
fireEvent.click(screen.getByRole("button", { name: "Criar processo" }));
}
-describe("StartProcessForClientModal capability", () => {
+describe("StartProcessForClientModal delegated EMAIL flow", () => {
beforeEach(() => {
- 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);
+ 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(createConsultantProcess).mockResolvedValue({
+ id: "process-1",
+ appointment_id: "appointment-1",
+ status: "SCHEDULING",
+ });
+ vi.mocked(officeService.createProcess).mockResolvedValue({
+ id: "process-1",
+ appointment_id: "appointment-1",
+ });
});
- afterEach(() => { cleanup(); vi.resetAllMocks(); vi.useRealTimers(); });
- 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();
+ afterEach(() => {
+ cleanup();
+ vi.resetAllMocks();
});
- 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.each(["CONSULTANT", "OFFICE"] as const)(
+ "creates and navigates without mounting Calendly in %s mode",
+ async (mode) => {
+ renderModal(mode);
+ await selectAndCreate();
+
+ expect(
+ await screen.findByText(
+ mode === "OFFICE" ? "Processos do escritório" : "Processos do consultor",
+ ),
+ ).toBeTruthy();
+ expect(
+ mode === "OFFICE" ? officeService.createProcess : createConsultantProcess,
+ ).toHaveBeenCalledWith({
+ client_id: client.id,
+ specialist_id: "specialist-1",
+ product_type: "CAR",
+ product_id: "car-1",
+ });
+ expect(useCalendlyEventListener).not.toHaveBeenCalled();
+ expect(screen.queryByRole("link", { name: "Agendar no Calendly" })).toBeNull();
+ },
+ );
- it("preserves process creation without a Calendly URL when capability is false", async () => {
- vi.mocked(getPublicSpecialistById).mockResolvedValue({ ...specialist, calendly_url: null });
+ it("keeps one submitted client and one write while creation is pending", async () => {
+ let resolve!: (value: Awaited
>) => void;
+ vi.mocked(getClients).mockResolvedValue([client, secondClient]);
+ vi.mocked(createConsultantProcess).mockImplementationOnce(
+ () => new Promise((done) => (resolve = done)),
+ );
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));
- });
+ const other = screen.getByRole("button", { name: /Outro Teste/i }) as HTMLButtonElement;
+ expect(other.disabled).toBe(true);
+ fireEvent.click(other);
+ fireEvent.click(screen.getByRole("button", { name: "Criando..." }));
+ expect(createConsultantProcess).toHaveBeenCalledOnce();
- 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();
+ await act(async () =>
+ resolve({ id: "process-1", appointment_id: "appointment-1", status: "SCHEDULING" }),
+ );
+ expect(createConsultantProcess).toHaveBeenCalledWith(
+ expect.objectContaining({ client_id: client.id }),
+ );
});
- 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();
+ it("reports creation errors inline and releases busy state", async () => {
+ const onBusyChange = vi.fn();
+ vi.mocked(createConsultantProcess).mockRejectedValue(new Error("Falha ao criar"));
+ render(scopeContent({ onBusyChange }));
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((await screen.findByRole("alert")).textContent).toContain("Falha ao criar");
+ expect(onBusyChange).toHaveBeenNthCalledWith(1, true);
+ expect(onBusyChange).toHaveBeenLastCalledWith(false);
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) => {
+ 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;
+ }),
+ );
+ const view = render(scopeContent());
+ await selectAndCreate();
+ view.rerender(scopeContent({ specialistId: "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.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; }));
+ 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();
- });
+ await act(async () =>
+ resolve({ id: "old-process", appointment_id: "old-appointment", status: "SCHEDULING" }),
+ );
- 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();
+ expect(screen.getByTestId("location").textContent).toBe("/start");
});
- it("does not navigate after the modal unmounts during creation", async () => {
+ it("does not navigate after unmount during creation", async () => {
let resolve!: (value: Awaited>) => void;
- vi.mocked(createConsultantProcess).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
+ 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" }));
+ 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 () => {
+ it("ignores an obsolete client list after switching mode", 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" }]);
+ 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 a Calendly event after its scope changes", 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!;
- view.rerender(scopeContent({ specialistId: "specialist-2" }));
- await act(async () => {
- 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("does not register an on-behalf EMAIL appointment through the client-only Calendly endpoint", async () => {
- vi.mocked(getPublicSpecialistById).mockResolvedValue({
- ...specialist,
- calendly_scheduling_available: true,
- });
- renderModal();
- await selectAndCreate();
- await screen.findByRole("link", { name: "Agendar no Calendly" });
- vi.useFakeTimers();
- const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
- .onEventScheduled!;
- let completion!: Promise;
- act(() => {
- completion = Promise.resolve(
- listener({
- data: {
- event: "calendly.event_scheduled",
- payload: {
- event: { uri: "event-uri" },
- invitee: { uri: "invitee-uri" },
- },
- },
- } as Parameters[0]),
- );
- });
- await act(async () => {
- await vi.runAllTimersAsync();
- await completion;
- });
-
- expect(registerCalendlyScheduledEvent).not.toHaveBeenCalled();
- expect(getCalendlySyncStatus).not.toHaveBeenCalled();
- expect(screen.getByText("Processos do consultor")).toBeTruthy();
- });
-
- it("keeps the selected client when only label or callback props change", async () => {
+ it("keeps selection and search when only presentation 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 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)!;
- 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]);
+ fireEvent.change(screen.getByPlaceholderText("Buscar por nome ou e-mail..."), {
+ target: { value: "Cliente" },
});
- expect(registerCalendlyScheduledEvent).not.toHaveBeenCalled();
- expect(getCalendlySyncStatus).not.toHaveBeenCalled();
- expect(screen.getByTestId("location").textContent).toBe("/start");
- expect(onCalendlyOpenChange).not.toHaveBeenCalled();
- });
+ view.rerender(scopeContent({ productLabel: "Novo texto" }));
- 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();
- 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");
+ 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();
});
});
diff --git a/frontend/src/components/processes/StartProcessForClientModal.tsx b/frontend/src/components/processes/StartProcessForClientModal.tsx
index 5e809f0..85d7214 100644
--- a/frontend/src/components/processes/StartProcessForClientModal.tsx
+++ b/frontend/src/components/processes/StartProcessForClientModal.tsx
@@ -1,9 +1,7 @@
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, type PublicSpecialistProfile } from "../../services/specialists.service";
import Button from "../../components/ui/button";
import { Loader2, Search } from "lucide-react";
@@ -37,8 +35,6 @@ 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) {
@@ -55,8 +51,6 @@ function StartProcessForClientModalInner({
mode = "CONSULTANT",
onClose,
onBusyChange,
- calendlyRootElement,
- onCalendlyOpenChange,
}: Props) {
const config = MODES[mode];
const navigate = useNavigate();
@@ -68,34 +62,20 @@ function StartProcessForClientModalInner({
const [error, setError] = useState(null);
const searchRef = useRef(null);
- // Calendly
- 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 calendlyOpenCallbackRef = useRef(onCalendlyOpenChange);
- const [pendingOperation, setPendingOperation] = useState<{
- 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;
- calendlyOpenCallbackRef.current = onCalendlyOpenChange;
- }, [onBusyChange, onCalendlyOpenChange]);
+ }, [onBusyChange]);
useLayoutEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
operationGeneration.current += 1;
- calendlyOpenCallbackRef.current?.(false);
busyCallbackRef.current?.(false);
};
}, []);
@@ -108,11 +88,6 @@ function StartProcessForClientModalInner({
busyCallbackRef.current?.(busy);
};
- const setCalendlyOpen = (open: boolean) => {
- setIsCalendlyOpen(open);
- calendlyOpenCallbackRef.current?.(open);
- };
-
useEffect(() => {
let active = true;
setClients([]);
@@ -129,19 +104,6 @@ function StartProcessForClientModalInner({
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((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(() => {
const q = search.trim().toLowerCase();
if (!q) return clients;
@@ -150,72 +112,34 @@ function StartProcessForClientModalInner({
);
}, [clients, search]);
- // Este fluxo cria o processo em nome do cliente como EMAIL. O endpoint de
- // sincronização Calendly é exclusivo do próprio cliente autenticado, então
- // o evento do popup apenas conclui a navegação deste fluxo delegado.
- useCalendlyEventListener({
- onEventScheduled: () => {
- const pending = pendingOperation;
- if (!pending || !isCurrentOperation(pending.generation)) return;
- operationGeneration.current += 1;
- setCalendlyOpen(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 (submittingRef.current) return;
if (!selectedClient) {
setError("Selecione um cliente.");
return;
}
setError(null);
- 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({
+ await config.createProcess({
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 (specialistProfile.calendly_scheduling_available && specialistCalendlyUrl && process.appointment_id) {
- let url = specialistCalendlyUrl.trim();
- if (!url.startsWith("http://") && !url.startsWith("https://")) {
- url = `https://${url}`;
- }
- awaitingCalendly = true;
- setPendingOperation({ generation, client: submittedClient });
- setCalendlyUrl(url);
- setCalendlyOpen(true);
- setCalendlyMessage(
- "Conclua o agendamento no Calendly para marcar o horário da reunião.",
- );
- } else {
- navigate(config.redirectTo);
- }
+ // Criação delegada é sempre EMAIL; somente o próprio cliente pode abrir
+ // e sincronizar um popup Calendly em uma sessão autenticada dele.
+ navigate(config.redirectTo);
} catch (err) {
if (isCurrentOperation(generation)) {
setError((err as Error).message || "Erro ao criar processo. Tente novamente.");
}
} finally {
- if (isCurrentOperation(generation) && !awaitingCalendly) {
+ if (isCurrentOperation(generation)) {
submittingRef.current = false;
setBusy(false);
}
@@ -284,11 +208,7 @@ function StartProcessForClientModalInner({
)}
- {specialistError && {specialistError}
}
{error && {error}
}
- {calendlyMessage && (
- {calendlyMessage}
- )}
{
@@ -301,34 +221,11 @@ function StartProcessForClientModalInner({
{isSubmitting ? "Criando..." : "Criar processo"}
-
- {calendlyRootElement && calendlyUrl && isCalendlyOpen && (
- {
- if (!pendingOperation || !isCurrentOperation(pendingOperation.generation)) return;
- operationGeneration.current += 1;
- setCalendlyOpen(false);
- setPendingOperation(null);
- submittingRef.current = false;
- setBusy(false);
- navigate(config.redirectTo);
- }}
- rootElement={calendlyRootElement}
- prefill={{
- name: pendingOperation
- ? `${pendingOperation.client.name} ${pendingOperation.client.surname}`.trim()
- : undefined,
- email: pendingOperation?.client.email,
- }}
- />
- )}
);
}
diff --git a/frontend/src/hooks/useCalendlyScheduling.test.tsx b/frontend/src/hooks/useCalendlyScheduling.test.tsx
index a6caf37..7f848bb 100644
--- a/frontend/src/hooks/useCalendlyScheduling.test.tsx
+++ b/frontend/src/hooks/useCalendlyScheduling.test.tsx
@@ -1,12 +1,14 @@
// @vitest-environment jsdom
import { act, cleanup, renderHook } from "@testing-library/react";
+import { StrictMode, type ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
useCalendlyEventListener,
type EventScheduledEvent,
} from "react-calendly";
import {
+ cancelPendingAppointment,
getCalendlySyncStatus,
registerCalendlyScheduledEvent,
} from "../services/appointments.service";
@@ -83,6 +85,7 @@ describe("useCalendlyScheduling active registration retry", () => {
popup.className = "calendly-popup-content";
popup.appendChild(document.createElement("iframe"));
document.body.appendChild(popup);
+ vi.mocked(cancelPendingAppointment).mockResolvedValue({} as never);
});
afterEach(() => {
@@ -160,9 +163,114 @@ describe("useCalendlyScheduling active registration retry", () => {
expect(registerCalendlyScheduledEvent).toHaveBeenCalledTimes(1);
expect(getCalendlySyncStatus).toHaveBeenCalledTimes(1);
+ expect(cancelPendingAppointment).not.toHaveBeenCalled();
expect(navigate).not.toHaveBeenCalled();
});
+ it("cancela exatamente uma vez o PENDING ao desmontar antes do evento", async () => {
+ const { result, unmount } = renderHook(
+ () => useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ {children}
+ ),
+ },
+ );
+
+ act(() =>
+ result.current.openPopup("appointment-abandoned", "https://calendly.com/a"),
+ );
+ unmount();
+ await flushPromises();
+
+ expect(cancelPendingAppointment).toHaveBeenCalledTimes(1);
+ expect(cancelPendingAppointment).toHaveBeenCalledWith("appointment-abandoned");
+ });
+
+ it("não cancela quando o fechamento disputa com um evento confiável", async () => {
+ vi.mocked(registerCalendlyScheduledEvent).mockResolvedValue({
+ appointment_id: "appointment-race",
+ calendly_sync_status: "SYNCED",
+ appointment_datetime: syncedStatus.appointment_datetime,
+ });
+ vi.mocked(getCalendlySyncStatus).mockResolvedValue({
+ ...syncedStatus,
+ appointment_id: "appointment-race",
+ });
+ const { result } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ );
+ act(() =>
+ result.current.openPopup("appointment-race", "https://calendly.com/a"),
+ );
+ const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
+ .onEventScheduled!;
+
+ await act(async () => {
+ const sync = listener(scheduledEvent());
+ await result.current.closePopup();
+ await sync;
+ });
+
+ expect(cancelPendingAppointment).not.toHaveBeenCalled();
+ });
+
+ it("não cancela no unmount depois que um evento confiável foi recebido", async () => {
+ let resolveRegistration!: (value: {
+ appointment_id: string;
+ calendly_sync_status: "SYNCED";
+ appointment_datetime: string;
+ }) => void;
+ vi.mocked(registerCalendlyScheduledEvent).mockReturnValue(
+ new Promise((resolve) => {
+ resolveRegistration = resolve;
+ }),
+ );
+ const { result, unmount } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ );
+ act(() =>
+ result.current.openPopup("appointment-confirmed", "https://calendly.com/a"),
+ );
+ const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
+ .onEventScheduled!;
+
+ act(() => {
+ void listener(scheduledEvent());
+ });
+ unmount();
+ await flushPromises();
+
+ expect(cancelPendingAppointment).not.toHaveBeenCalled();
+ resolveRegistration({
+ appointment_id: "appointment-confirmed",
+ calendly_sync_status: "SYNCED",
+ appointment_datetime: syncedStatus.appointment_datetime,
+ });
+ await flushPromises();
+ expect(navigate).not.toHaveBeenCalled();
+ });
+
+ it("deduplica fechamento e cleanup mesmo quando o cancelamento falha", async () => {
+ vi.mocked(cancelPendingAppointment).mockRejectedValue(new Error("offline"));
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+ const { result, unmount } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ );
+ act(() =>
+ result.current.openPopup("appointment-once", "https://calendly.com/a"),
+ );
+
+ await act(async () => {
+ await result.current.closePopup();
+ });
+ unmount();
+ await flushPromises();
+
+ expect(cancelPendingAppointment).toHaveBeenCalledTimes(1);
+ expect(consoleError).toHaveBeenCalledTimes(1);
+ });
+
it("encerra após oito tentativas sem criar loop de retry", async () => {
vi.mocked(registerCalendlyScheduledEvent).mockResolvedValue({
appointment_id: "appointment-1",
diff --git a/frontend/src/hooks/useCalendlyScheduling.ts b/frontend/src/hooks/useCalendlyScheduling.ts
index b54051f..153e94b 100644
--- a/frontend/src/hooks/useCalendlyScheduling.ts
+++ b/frontend/src/hooks/useCalendlyScheduling.ts
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useCalendlyEventListener } from "react-calendly";
import {
@@ -28,6 +28,11 @@ interface UseCalendlySchedulingOptions {
onSynced?: (status: CalendlySyncStatus) => void;
}
+type PendingCalendlyAttempt = {
+ appointmentId: string;
+ phase: "waiting_event" | "event_received" | "cancelling" | "settled";
+};
+
/**
* useCalendlyScheduling
*
@@ -50,30 +55,53 @@ export function useCalendlyScheduling({
const navigate = useNavigate();
const [isModalOpen, setIsModalOpen] = useState(false);
const [modalUrl, setModalUrl] = useState(null);
- const [pendingAppointmentId, setPendingAppointmentId] = useState<
- string | null
- >(null);
const [syncState, setSyncState] = useState("idle");
const [syncMessage, setSyncMessage] = useState("");
- const confirmedRef = useRef(false);
+ const pendingAttemptRef = useRef(null);
const mountedRef = useRef(false);
const syncAbortRef = useRef(null);
const navigateTimerRef = useRef | null>(null);
+ const abandonAttempt = useCallback(
+ (attempt: PendingCalendlyAttempt, resetVisibleState: boolean) => {
+ if (attempt.phase !== "waiting_event") return Promise.resolve();
+
+ // Claim the cancellation synchronously. A modal close, route unmount and
+ // StrictMode cleanup can all observe the same attempt, but only the first
+ // caller is allowed to issue the DELETE.
+ attempt.phase = "cancelling";
+ return cancelPendingAppointment(attempt.appointmentId)
+ .catch((err) => {
+ console.error("Erro ao cancelar agendamento pendente", err);
+ })
+ .finally(() => {
+ if (pendingAttemptRef.current === attempt) {
+ pendingAttemptRef.current = null;
+ }
+ if (resetVisibleState && mountedRef.current) {
+ setSyncState("idle");
+ setSyncMessage("");
+ }
+ });
+ },
+ [],
+ );
+
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
+ const attempt = pendingAttemptRef.current;
+ if (attempt) void abandonAttempt(attempt, false);
syncAbortRef.current?.abort();
if (navigateTimerRef.current) clearTimeout(navigateTimerRef.current);
};
- }, []);
+ }, [abandonAttempt]);
useCalendlyEventListener({
onEventScheduled: async (event) => {
- if (!pendingAppointmentId) {
- return;
- }
+ const attempt = pendingAttemptRef.current;
+ if (!attempt || attempt.phase !== "waiting_event") return;
const currentFrame = document.querySelector(
".calendly-popup-content iframe",
@@ -106,7 +134,7 @@ export function useCalendlyScheduling({
// a janela de corrida em que o usuário fecha o popup entre o evento do
// Calendly e a resposta do nosso backend — nesse intervalo o registro
// NÃO pode ser tratado como abandono e cancelado.
- confirmedRef.current = true;
+ attempt.phase = "event_received";
const registrationPayload: RegisterCalendlyScheduledPayload = {
event_uri: eventUri,
invitee_uri: inviteeUri,
@@ -122,12 +150,13 @@ export function useCalendlyScheduling({
setSyncMessage("Sincronizando seu agendamento...");
const status = await synchronizeCalendlyRegistration(
- pendingAppointmentId,
+ attempt.appointmentId,
registrationPayload,
{ signal: syncController.signal },
);
if (!mountedRef.current || syncController.signal.aborted || !status) return;
+ attempt.phase = "settled";
setIsModalOpen(false);
if (isCalendlySyncComplete(status)) {
onSynced?.(status);
@@ -155,8 +184,8 @@ export function useCalendlyScheduling({
);
}
} catch (err) {
- // O agendamento já aconteceu de verdade no Calendly (confirmedRef já
- // é true) — só a nossa sincronização falhou. Não deixar o usuário
+ // O agendamento já aconteceu de verdade no Calendly (a tentativa já
+ // recebeu o evento) — só a nossa sincronização falhou. Não deixar o usuário
// preso num popup fechado/stale: fecha e manda pra Meus Processos,
// igual ao fluxo de sucesso, só que com aviso de que pode faltar
// atualizar a página.
@@ -182,13 +211,17 @@ export function useCalendlyScheduling({
/** Seta o agendamento pendente em foco, abre o popup do Calendly. */
const openPopup = (appointmentId: string, calendlyUrl: string) => {
+ const previousAttempt = pendingAttemptRef.current;
+ if (previousAttempt) void abandonAttempt(previousAttempt, false);
syncAbortRef.current?.abort();
if (navigateTimerRef.current) clearTimeout(navigateTimerRef.current);
const normalizedUrl = /^https?:\/\//i.test(calendlyUrl)
? calendlyUrl
: `https://${calendlyUrl}`;
- confirmedRef.current = false;
- setPendingAppointmentId(appointmentId);
+ pendingAttemptRef.current = {
+ appointmentId,
+ phase: "waiting_event",
+ };
setModalUrl(normalizedUrl);
setSyncState("waiting_event");
setSyncMessage(
@@ -204,18 +237,8 @@ export function useCalendlyScheduling({
*/
const closePopup = async () => {
setIsModalOpen(false);
-
- if (!confirmedRef.current && pendingAppointmentId) {
- try {
- await cancelPendingAppointment(pendingAppointmentId);
- } catch (err) {
- console.error("Erro ao cancelar agendamento ao fechar modal", err);
- } finally {
- setPendingAppointmentId(null);
- setSyncState("idle");
- setSyncMessage("");
- }
- }
+ const attempt = pendingAttemptRef.current;
+ if (attempt) await abandonAttempt(attempt, true);
};
return {
diff --git a/frontend/src/pages/catalog/ProductPage.test.tsx b/frontend/src/pages/catalog/ProductPage.test.tsx
index 61d2e57..5d70966 100644
--- a/frontend/src/pages/catalog/ProductPage.test.tsx
+++ b/frontend/src/pages/catalog/ProductPage.test.tsx
@@ -678,7 +678,7 @@ describe("ProductPage scheduling", () => {
{
appointment_status: "PENDING" as const,
scheduling_method: "CALENDLY" as const,
- message: "Aguardando confirmação do especialista",
+ message: "Aguardando sincronização do Calendly",
},
{
appointment_status: "SCHEDULED" as const,
diff --git a/frontend/src/pages/catalog/ProductPage.tsx b/frontend/src/pages/catalog/ProductPage.tsx
index e221dcf..2fb4258 100644
--- a/frontend/src/pages/catalog/ProductPage.tsx
+++ b/frontend/src/pages/catalog/ProductPage.tsx
@@ -107,8 +107,6 @@ 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;
@@ -564,14 +562,18 @@ export default function ProductPage() {
{currentRequest.appointment_status === "PENDING"
- ? "Aguardando confirmação do especialista"
+ ? currentRequest.scheduling_method === "CALENDLY"
+ ? "Aguardando sincronização do Calendly"
+ : "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.scheduling_method === "CALENDLY"
+ ? "Seu horário foi enviado pelo Calendly e a plataforma está concluindo a sincronização. Acompanhe em Meus Processos."
+ : "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."}
@@ -684,9 +686,6 @@ 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 db39c808bbb0432030ae6653d344282d776fef11 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 13:00:15 -0300
Subject: [PATCH 46/60] fix(frontend): consume owner-scoped specialist contact
---
.../ProductPage.calendly.integration.test.tsx | 325 +++++++++---------
.../src/pages/catalog/ProductPage.test.tsx | 8 +-
frontend/src/pages/catalog/ProductPage.tsx | 7 +-
.../pages/customer/ConsultoriaPage.test.tsx | 2 +-
.../src/pages/customer/ConsultoriaPage.tsx | 1 -
.../src/services/appointments.service.test.ts | 32 +-
frontend/src/services/appointments.service.ts | 12 +
frontend/src/services/specialists.service.ts | 1 -
8 files changed, 215 insertions(+), 173 deletions(-)
diff --git a/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx b/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx
index 74daafe..8c3b8a7 100644
--- a/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx
+++ b/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx
@@ -9,81 +9,130 @@ 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";
+import {
+ getPublicSpecialistById,
+ type PublicSpecialistProfile,
+} from "../../services/specialists.service";
+import { checkExistingAppointment } from "../../services/appointments.service";
const { authState } = vi.hoisted(() => ({
- authState: { user: { id: "consultant-1", role: "CONSULTANT", name: "Consultor", surname: "Teste", email: "consultor@example.com" } },
+ 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/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,
+ 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,
+ id: "specialist-1",
+ name: "Ana",
+ surname: "Silva",
+ 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,
};
-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} />
-
- ;
+ 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 });
+ return render(strict ? {pageContent()} : pageContent(), {
+ container: root,
+ });
}
-async function openCalendly(preserveEnabledFocus = false) {
+async function submitDelegatedProcess() {
const user = userEvent.setup();
- await user.click(await screen.findByRole("button", { name: "Iniciar processo para cliente" }));
+ 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 };
+ await user.click(screen.getByRole("button", { name: "Criar processo" }));
+ return user;
}
-describe("delegated Calendly with the real Radix dialog and PopupModal", () => {
+describe("delegated EMAIL flow with the real Radix dialog", () => {
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",
+ 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);
+ 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",
+ });
});
afterEach(() => {
@@ -92,149 +141,95 @@ describe("delegated Calendly with the real Radix dialog and PopupModal", () => {
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.each(["CONSULTANT", "OFFICE"] as const)(
+ "creates %s delegated process as EMAIL without opening Calendly",
+ async (role) => {
+ authState.user.role = role;
+ page();
+ await submitDelegatedProcess();
+
+ expect(
+ await screen.findByRole("heading", {
+ name: role === "OFFICE" ? "Processos do escritório" : "Processos do consultor",
+ }),
+ ).toBeTruthy();
+ expect(screen.queryByTitle("Calendly Scheduling Page")).toBeNull();
+ expect(document.querySelector("iframe")).toBeNull();
+ expect(
+ role === "OFFICE" ? officeService.createProcess : createConsultantProcess,
+ ).toHaveBeenCalledOnce();
+ },
+ );
+
+ it.each(["Fechar", "Escape", "outside"])(
+ "keeps the 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");
+
+ await act(async () =>
+ resolve({ id: "process-1", appointment_id: "appointment-1", status: "SCHEDULING" }),
+ );
+ expect(
+ await screen.findByRole("heading", { name: "Processos do consultor" }),
+ ).toBeTruthy();
+ expect(screen.queryByTitle("Calendly Scheduling Page")).toBeNull();
+ },
+ );
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 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"])("does not call the client-only Calendly sync endpoint for delegated EMAIL flow 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).not.toHaveBeenCalled();
- expect(getCalendlySyncStatus).not.toHaveBeenCalled();
- await waitFor(() => expect(document.body.style.pointerEvents).not.toBe("none"));
+ it("does not duplicate the delegated write in StrictMode", async () => {
+ page(true);
+ await submitDelegatedProcess();
+ expect(
+ await screen.findByRole("heading", { name: "Processos do consultor" }),
+ ).toBeTruthy();
+ expect(createConsultantProcess).toHaveBeenCalledOnce();
+ expect(screen.queryByTitle("Calendly Scheduling Page")).toBeNull();
});
- it("ignores a delegated Calendly event after the real popup is closed without attempting client-only sync", async () => {
+ it("ignores unrelated global Calendly messages because delegated flow has no listener", async () => {
page();
- const { user, iframe } = await openCalendly();
- await user.click(iframe.closest(".calendly-overlay")!.querySelector(".calendly-popup-close")!);
- expect(await screen.findByRole("heading", { name: "Processos do consultor" })).toBeTruthy();
fireEvent(window, new MessageEvent("message", {
origin: "https://calendly.com",
- data: { event: "calendly.event_scheduled", payload: { event: { uri: "event-uri" }, invitee: { uri: "invitee-uri" } } },
+ data: {
+ event: "calendly.event_scheduled",
+ payload: { event: { uri: "event-uri" }, invitee: { uri: "invitee-uri" } },
+ },
}));
- expect(registerCalendlyScheduledEvent).not.toHaveBeenCalled();
- expect(getCalendlySyncStatus).not.toHaveBeenCalled();
+ expect(createConsultantProcess).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.test.tsx b/frontend/src/pages/catalog/ProductPage.test.tsx
index 5d70966..404e2cd 100644
--- a/frontend/src/pages/catalog/ProductPage.test.tsx
+++ b/frontend/src/pages/catalog/ProductPage.test.tsx
@@ -97,7 +97,6 @@ const specialist: PublicSpecialistProfile = {
id: "specialist-1",
name: "Especialista",
surname: "Teste",
- email: "especialista@example.com",
calendly_url: null,
speciality: "CAR",
calendly_scheduling_available: false,
@@ -112,6 +111,7 @@ const appointment: PendingAppointmentCreated = {
appointment_datetime: "2099-09-20T17:30:00.000Z",
status: "PENDING",
scheduling_method: "EMAIL",
+ specialist_contact_email: "private-specialist@example.com",
created_at: "2026-01-01T00:00:00.000Z",
updated_at: "2026-01-01T00:00:00.000Z",
};
@@ -121,6 +121,7 @@ const existingRequest: ActiveProcessSnapshot = {
appointment_status: "PENDING",
scheduling_method: "EMAIL",
appointment_datetime: appointment.appointment_datetime ?? null,
+ specialist_contact_email: "private-specialist@example.com",
};
function ChangeProductButton() {
@@ -454,6 +455,11 @@ describe("ProductPage scheduling", () => {
);
expect(createPlatformAppointment).not.toHaveBeenCalled();
expect(screen.getByRole("link", { name: "Abrir no Gmail" })).toBeTruthy();
+ expect(
+ screen
+ .getByRole("link", { name: "Abrir aplicativo de e-mail" })
+ .getAttribute("href"),
+ ).toContain("private-specialist%40example.com");
expect(
screen
.getByRole("link", { name: "Acompanhar processo" })
diff --git a/frontend/src/pages/catalog/ProductPage.tsx b/frontend/src/pages/catalog/ProductPage.tsx
index 2fb4258..e3d0e3b 100644
--- a/frontend/src/pages/catalog/ProductPage.tsx
+++ b/frontend/src/pages/catalog/ProductPage.tsx
@@ -49,6 +49,7 @@ function appointmentSnapshot(
appointment_status: appointment.status,
scheduling_method: appointment.scheduling_method ?? null,
appointment_datetime: appointment.appointment_datetime ?? null,
+ specialist_contact_email: appointment.specialist_contact_email,
};
}
@@ -65,12 +66,14 @@ function isPendingEmailRequest(
): request is ActiveProcessSnapshot & {
appointment_id: string;
appointment_datetime: string;
+ specialist_contact_email: string;
} {
return (
request?.appointment_status === "PENDING" &&
request.scheduling_method === "EMAIL" &&
Boolean(request.appointment_id) &&
- Boolean(validAppointmentDate(request.appointment_datetime))
+ Boolean(validAppointmentDate(request.appointment_datetime)) &&
+ Boolean(request.specialist_contact_email?.trim())
);
}
@@ -547,7 +550,7 @@ export default function ProductPage() {
({
useCalendlyScheduling: useCalendlySchedulingMock,
}));
-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 specialist: PublicSpecialistProfile = { id: "specialist-1", name: "Ana", surname: "Silva", 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: [] });
}
diff --git a/frontend/src/pages/customer/ConsultoriaPage.tsx b/frontend/src/pages/customer/ConsultoriaPage.tsx
index f7d4373..da80df3 100644
--- a/frontend/src/pages/customer/ConsultoriaPage.tsx
+++ b/frontend/src/pages/customer/ConsultoriaPage.tsx
@@ -298,7 +298,6 @@ function SpecialistCard({
{specialist.name} {specialist.surname}
- {specialist.email}
onRequestMeeting(specialist)}
diff --git a/frontend/src/services/appointments.service.test.ts b/frontend/src/services/appointments.service.test.ts
index 5db8407..d727f94 100644
--- a/frontend/src/services/appointments.service.test.ts
+++ b/frontend/src/services/appointments.service.test.ts
@@ -13,6 +13,7 @@ const base = {
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",
+ specialist_contact_email: "private-specialist@example.com",
};
describe("owned existing appointment check", () => {
@@ -35,7 +36,7 @@ describe("owned existing appointment check", () => {
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" };
+ 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, specialist_contact_email: snapshot.specialist_contact_email, 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 });
@@ -67,10 +68,37 @@ describe("pending product request contracts", () => {
});
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) => {
+ it.each([
+ snapshot,
+ {
+ appointment_id: null,
+ process_id: snapshot.process_id,
+ 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("preserves the owner-scoped specialist contact from an EMAIL duplicate", () => {
+ expect(
+ service.getActiveProcessSnapshot({
+ response: {
+ status: 409,
+ data: {
+ error: {
+ code: "ACTIVE_PROCESS_EXISTS",
+ details: { existing_request: snapshot },
+ },
+ },
+ },
+ }),
+ ).toMatchObject({
+ specialist_contact_email: snapshot.specialist_contact_email,
+ });
+ });
+
it.each([
{ response: { status: 409, data: { message: "Conflito" } } },
{ response: { status: 409, data: { error: { code: "CALENDLY_UNAVAILABLE", details: { existing_request: snapshot } } } } },
diff --git a/frontend/src/services/appointments.service.ts b/frontend/src/services/appointments.service.ts
index 2004a0a..ca702c6 100644
--- a/frontend/src/services/appointments.service.ts
+++ b/frontend/src/services/appointments.service.ts
@@ -25,6 +25,8 @@ export interface Appointment {
calendly_last_sync_at?: string | null;
calendly_sync_status?: "PENDING" | "SYNCED" | "FAILED";
scheduling_method?: AppointmentSchedulingMethod | null;
+ /** Released only by authenticated, owner-scoped EMAIL request responses. */
+ specialist_contact_email?: string;
specialist_rescheduled_at?: string | null;
specialist_rescheduled_from?: string | null;
client?: {
@@ -64,6 +66,7 @@ export type ExistingAppointmentCheck =
appointment_status: Appointment["status"];
scheduling_method: AppointmentSchedulingMethod | null;
appointment_datetime: string | null;
+ specialist_contact_email?: string;
};
export interface ActiveProcessSnapshot {
@@ -72,6 +75,7 @@ export interface ActiveProcessSnapshot {
appointment_status: Appointment["status"] | null;
scheduling_method: AppointmentSchedulingMethod | null;
appointment_datetime: string | null;
+ specialist_contact_email?: string;
}
interface BaseProductRequest {
@@ -101,12 +105,20 @@ export function getActiveProcessSnapshot(error: unknown): ActiveProcessSnapshot
|| !(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;
+ const specialistContactEmail = snapshot.specialist_contact_email;
+ const hasValidSpecialistContact =
+ snapshot.scheduling_method === "EMAIL" &&
+ typeof specialistContactEmail === "string" &&
+ specialistContactEmail.trim().length > 0;
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,
+ ...(hasValidSpecialistContact
+ ? { specialist_contact_email: specialistContactEmail.trim() }
+ : {}),
};
}
diff --git a/frontend/src/services/specialists.service.ts b/frontend/src/services/specialists.service.ts
index fdc8e68..e5000eb 100644
--- a/frontend/src/services/specialists.service.ts
+++ b/frontend/src/services/specialists.service.ts
@@ -32,7 +32,6 @@ export type PublicSpecialistProfile = {
id: string;
name: string;
surname: string;
- email: string;
speciality: "CAR" | "BOAT" | "AIRCRAFT" | null;
calendly_url: string | null;
calendly_scheduling_available: boolean;
From c52cb79a22e15c3b1ee8d03dbe09f71f8f4af79a Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 13:01:22 -0300
Subject: [PATCH 47/60] test(frontend): cover scoped contact fallbacks
---
.../appointments-concurrency.postgres.spec.ts | 195 +++++-
.../appointments/appointments.controller.ts | 3 +-
.../appointments/appointments.service.spec.ts | 235 ++++---
.../appointments/appointments.service.ts | 61 +-
.../entities/appointment.response.ts | 6 +
.../notification.service.spec.ts | 20 +
.../notifications/notification.service.ts | 30 +-
.../processes/process-dedup-lock.spec.ts | 5 +
.../features/processes/process-dedup-lock.ts | 11 +-
...ocesses-dedup-concurrency.postgres.spec.ts | 571 +++++++++++-------
.../processes/processes.service.spec.ts | 133 +++-
.../features/processes/processes.service.ts | 90 +--
.../specialists/specialists.service.spec.ts | 5 +-
.../specialists/specialists.service.ts | 4 +-
.../src/pages/catalog/ProductPage.test.tsx | 17 +
.../src/services/appointments.service.test.ts | 20 +
16 files changed, 1005 insertions(+), 401 deletions(-)
diff --git a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts
index 330d148..d814dc0 100644
--- a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts
+++ b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts
@@ -13,16 +13,107 @@ import {
import { ProcessesService } from '../processes/processes.service';
import { AppointmentsService } from './appointments.service';
-type Deferred = { promise: Promise; resolve: () => void };
+type Deferred = { promise: Promise; resolve: (value: T) => void };
-function deferred(): Deferred {
- let resolve!: () => void;
- const promise = new Promise((done) => {
+function deferred(): Deferred {
+ let resolve!: (value: T) => void;
+ const promise = new Promise((done) => {
resolve = done;
});
return { promise, resolve };
}
+function observeFirstAdvisoryLock(
+ client: PrismaClient,
+ attempted: Deferred,
+ productAcquired: Deferred,
+) {
+ let observed = false;
+ return new Proxy(client, {
+ get(target, property) {
+ if (property === '$transaction') {
+ return (callback: (tx: any) => Promise, options?: any) =>
+ target.$transaction(
+ (tx) =>
+ callback(
+ new Proxy(tx, {
+ get(transaction, member) {
+ if (member === '$queryRaw') {
+ return async (
+ strings: TemplateStringsArray,
+ ...values: unknown[]
+ ) => {
+ const key = String(values[0]);
+ if (!observed) {
+ observed = true;
+ attempted.resolve(key);
+ }
+ const result = await transaction.$queryRaw(
+ strings,
+ ...values,
+ );
+ if (key.startsWith('product-money:')) {
+ productAcquired.resolve();
+ }
+ return result;
+ };
+ }
+ return bindMember(transaction, member);
+ },
+ }),
+ ),
+ options,
+ );
+ }
+ return bindMember(target, property);
+ },
+ });
+}
+
+function pauseAfterScheduleLock(
+ client: PrismaClient,
+ acquired: Deferred,
+ release: Deferred,
+) {
+ return new Proxy(client, {
+ get(target, property) {
+ if (property === '$transaction') {
+ return (callback: (tx: any) => Promise, options?: any) =>
+ target.$transaction(
+ (tx) =>
+ callback(
+ new Proxy(tx, {
+ get(transaction, member) {
+ if (member === '$queryRaw') {
+ return async (
+ strings: TemplateStringsArray,
+ ...values: unknown[]
+ ) => {
+ const result = await transaction.$queryRaw(
+ strings,
+ ...values,
+ );
+ if (
+ String(values[0]).startsWith('appointment-schedule:')
+ ) {
+ acquired.resolve();
+ await release.promise;
+ }
+ return result;
+ };
+ }
+ return bindMember(transaction, member);
+ },
+ }),
+ ),
+ options,
+ );
+ }
+ return bindMember(target, property);
+ },
+ });
+}
+
function withApplicationName(url: string, name: string): string {
const separator = url.includes('?') ? '&' : '?';
return `${url}${separator}application_name=${encodeURIComponent(name)}&connection_limit=1&pool_timeout=3`;
@@ -618,6 +709,97 @@ describeWithPostgres(
15_000,
);
+ it('keeps schedule → product lock order across completion and legacy confirmation', async () => {
+ const confirmingAppointment = await holder.appointment.create({
+ data: {
+ client_id: clientIds[0],
+ specialist_id: specialistId,
+ product_type: ProductType.CAR,
+ product_id: carIds[0],
+ status: StatusAgendamento.PENDING,
+ scheduling_method: AppointmentSchedulingMethod.CALENDLY,
+ },
+ });
+ await holder.process.create({
+ data: {
+ client_id: clientIds[0],
+ specialist_id: specialistId,
+ product_type: ProductType.CAR,
+ car_id: carIds[0],
+ appointment_id: confirmingAppointment.id,
+ status: ProcessStatus.SCHEDULING,
+ },
+ });
+
+ const completingAppointment = await holder.appointment.create({
+ data: {
+ client_id: clientIds[1],
+ specialist_id: specialistId,
+ product_type: ProductType.CAR,
+ product_id: carIds[0],
+ status: StatusAgendamento.SCHEDULED,
+ scheduling_method: AppointmentSchedulingMethod.CALENDLY,
+ appointment_datetime: new Date('2099-01-01T08:00:00.000Z'),
+ },
+ });
+ await holder.process.create({
+ data: {
+ client_id: clientIds[1],
+ specialist_id: specialistId,
+ product_type: ProductType.CAR,
+ car_id: carIds[0],
+ appointment_id: completingAppointment.id,
+ status: ProcessStatus.SCHEDULING,
+ },
+ });
+
+ const completionHasSchedule = deferred();
+ const releaseCompletion = deferred();
+ const confirmationFirstAttempt = deferred();
+ const confirmationProductAcquired = deferred();
+ const completionService = new AppointmentsService(
+ pauseAfterScheduleLock(
+ second,
+ completionHasSchedule,
+ releaseCompletion,
+ ) as any,
+ notifications as any,
+ {} as any,
+ );
+ const confirmationService = new AppointmentsService(
+ observeFirstAdvisoryLock(
+ first,
+ confirmationFirstAttempt,
+ confirmationProductAcquired,
+ ) as any,
+ notifications as any,
+ {} as any,
+ );
+
+ const completion = completionService.updateStatus(
+ completingAppointment.id,
+ { status: StatusAgendamento.COMPLETED },
+ specialistId,
+ UserRole.SPECIALIST,
+ );
+ await completionHasSchedule.promise;
+ const confirmation = confirmationService.confirmPending(
+ confirmingAppointment.id,
+ specialistId,
+ new Date('2099-01-02T10:00:00.000Z'),
+ );
+ const firstKey = await confirmationFirstAttempt.promise;
+ if (firstKey.startsWith('product-money:')) {
+ await confirmationProductAcquired.promise;
+ }
+ releaseCompletion.resolve();
+
+ await expect(
+ Promise.all([completion, confirmation]),
+ ).resolves.toHaveLength(2);
+ expect(firstKey).toBe(`appointment-schedule:${specialistId}`);
+ }, 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) => [
@@ -664,10 +846,7 @@ describeWithPostgres(
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(first, a).cancelAppointment(request.process_id, clientIds[0]),
processes(second, b).confirmAppointment(
request.process_id,
specialistId,
diff --git a/backend/src/features/appointments/appointments.controller.ts b/backend/src/features/appointments/appointments.controller.ts
index 798896c..38d0641 100644
--- a/backend/src/features/appointments/appointments.controller.ts
+++ b/backend/src/features/appointments/appointments.controller.ts
@@ -120,7 +120,8 @@ export class AppointmentsController {
*
* 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.
+ * Retorna um snapshot mínimo. O e-mail do especialista só é incluído para
+ * um pedido EMAIL pertencente ao próprio cliente autenticado.
*/
@Get('check')
async checkExisting(
diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts
index 53b2133..3737d5d 100644
--- a/backend/src/features/appointments/appointments.service.spec.ts
+++ b/backend/src/features/appointments/appointments.service.spec.ts
@@ -355,6 +355,7 @@ describe('AppointmentsService.createPending — associação e atomicidade', ()
expect(result).toMatchObject({
id: 'appointment-1',
process_id: 'process-1',
+ specialist_contact_email: specialist.email,
});
expect(historyCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
@@ -626,6 +627,7 @@ describe('AppointmentsService.createPending — associação e atomicidade', ()
).resolves.toMatchObject({
process_id: 'process-1',
appointment_datetime: null,
+ specialist_contact_email: specialist.email,
});
expect(appointmentCreate).toHaveBeenCalledWith(
expect.objectContaining({
@@ -661,9 +663,51 @@ describe('AppointmentsService.createPending — associação e atomicidade', ()
expect.anything(),
'appointment-schedule:specialist-1',
);
+ expect(tx.$queryRaw.mock.calls.map((call) => call[1])).toEqual([
+ 'appointment-schedule:specialist-1',
+ 'process-dedup:client-1:specialist-1:CONSULTANCY:none',
+ ]);
expect(tx.appointment.findFirst).toHaveBeenCalledTimes(2);
});
+ it.each([
+ [
+ 'appointment concluído',
+ {
+ id: 'completed-appointment',
+ client_id: client.id,
+ status: StatusAgendamento.COMPLETED,
+ scheduling_method: AppointmentSchedulingMethod.EMAIL,
+ appointment_datetime: new Date('2098-01-01T10:00:00.000Z'),
+ },
+ ],
+ ['processo legado sem appointment', null],
+ ])(
+ 'rejeita nova consultoria diante de processo ativo com %s',
+ async (_label, appointment) => {
+ const { service, appointmentCreate } = harness({
+ existingProcess: {
+ id: 'active-consultancy',
+ client_id: client.id,
+ appointment,
+ },
+ });
+
+ await expect(
+ service.createPending(
+ {
+ client_id: client.id,
+ specialist_id: specialist.id,
+ scheduling_method: AppointmentSchedulingMethod.EMAIL,
+ },
+ client.id,
+ UserRole.CUSTOMER,
+ ),
+ ).rejects.toThrow(ConflictException);
+ expect(appointmentCreate).not.toHaveBeenCalled();
+ },
+ );
+
it.each([
'not-a-date',
'01/01/2099',
@@ -704,6 +748,7 @@ describe('AppointmentsService.createPending — associação e atomicidade', ()
existingProcess: {
id: 'process-existing',
client_id: client.id,
+ specialist: { email: specialist.email },
appointment: {
id: 'appointment-existing',
client_id: client.id,
@@ -723,6 +768,7 @@ describe('AppointmentsService.createPending — associação e atomicidade', ()
appointment_status: StatusAgendamento.PENDING,
scheduling_method: AppointmentSchedulingMethod.EMAIL,
appointment_datetime: proposedDate,
+ specialist_contact_email: specialist.email,
});
expect(prisma.appointment.findFirst).not.toHaveBeenCalled();
expect(tx.$queryRaw.mock.invocationCallOrder[1]).toBeLessThan(
@@ -772,7 +818,11 @@ describe('AppointmentsService.findExistingAppointment — own minimal projection
name: 'Private Client',
email: 'private@example.com',
},
- specialist: { id: 'specialist-1', name: 'Specialist' },
+ specialist: {
+ id: 'specialist-1',
+ name: 'Specialist',
+ email: 'specialist@example.com',
+ },
notes: 'private-notes',
created_at: new Date(),
updated_at: new Date(),
@@ -812,6 +862,9 @@ describe('AppointmentsService.findExistingAppointment — own minimal projection
appointment_status: appointment.status,
scheduling_method: appointment.scheduling_method,
appointment_datetime: appointment.appointment_datetime,
+ ...(appointment.scheduling_method === AppointmentSchedulingMethod.EMAIL
+ ? { specialist_contact_email: 'specialist@example.com' }
+ : {}),
});
expect(prisma.appointment.findFirst).toHaveBeenCalledWith({
where: expect.objectContaining({
@@ -843,11 +896,27 @@ describe('AppointmentsService.findExistingAppointment — own minimal projection
scheduling_method: true,
appointment_datetime: true,
process: { select: { id: true, client_id: true } },
+ specialist: { select: { email: true } },
},
});
expect(prisma.car.findUnique).not.toHaveBeenCalled();
},
);
+ it('não expõe contato do especialista para pedido CALENDLY', async () => {
+ const { service } = harness({
+ ...ownedAppointment,
+ scheduling_method: AppointmentSchedulingMethod.CALENDLY,
+ });
+
+ const result = await service.findExistingAppointment(
+ 'client-1',
+ 'specialist-1',
+ ProductType.CAR,
+ 'car-1',
+ );
+
+ expect(result).not.toHaveProperty('specialist_contact_email');
+ });
it.each([
null,
{ ...ownedAppointment, client_id: 'another-client' },
@@ -947,12 +1016,9 @@ describe('AppointmentsService.createPending — integridade das partes', () => {
).rejects.toThrow(BadRequestException);
});
- it.each([
- [undefined, AppointmentSchedulingMethod.CALENDLY],
- [AppointmentSchedulingMethod.EMAIL, AppointmentSchedulingMethod.EMAIL],
- ])(
- 'permite consultoria com processo existente e persiste a origem %s como %s',
- async (inputMethod, expectedMethod) => {
+ it.each([undefined, AppointmentSchedulingMethod.EMAIL])(
+ 'bloqueia consultoria com processo ativo para a origem %s',
+ async (inputMethod) => {
const client = {
id: 'client-1',
name: 'Client',
@@ -1005,34 +1071,18 @@ describe('AppointmentsService.createPending — integridade das partes', () => {
client.id,
UserRole.CUSTOMER,
),
- ).rejects.toThrow('stop after checks');
+ ).rejects.toThrow(ConflictException);
expect(tx.$queryRaw).toHaveBeenCalledWith(
expect.anything(),
'process-dedup:client-1:specialist-1:CONSULTANCY:none',
);
- expect(processFindFirst).not.toHaveBeenCalled();
- expect(appointmentFindFirst).toHaveBeenCalledWith({
- where: expect.objectContaining({
- client_id: client.id,
- specialist_id: specialist.id,
- product_type: null,
- product_id: null,
- status: {
- in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED],
- },
- }),
- });
+ expect(processFindFirst).toHaveBeenCalled();
+ expect(appointmentFindFirst).not.toHaveBeenCalled();
expect(tx.$queryRaw.mock.invocationCallOrder[0]).toBeLessThan(
- appointmentFindFirst.mock.invocationCallOrder[0],
- );
- expect(tx.appointment.create).toHaveBeenCalledWith(
- expect.objectContaining({
- data: expect.objectContaining({
- scheduling_method: expectedMethod,
- }),
- }),
+ processFindFirst.mock.invocationCallOrder[0],
);
+ expect(tx.appointment.create).not.toHaveBeenCalled();
},
);
@@ -1636,7 +1686,7 @@ describe('AppointmentsService.confirmPending — snapshot da negociação', () =
expect(prisma.$transaction).not.toHaveBeenCalled();
});
- it('confirma consultoria mesmo quando existe processo ativo anterior', async () => {
+ it('rejeita consultoria quando existe outro processo ativo e exclui somente o processo associado', async () => {
const client = {
id: 'client-1',
name: 'Cliente',
@@ -1722,21 +1772,20 @@ describe('AppointmentsService.confirmPending — snapshot da negociação', () =
await expect(
service.confirmPending(appointment.id, specialist.id),
- ).resolves.toMatchObject({ id: appointment.id });
+ ).rejects.toThrow(ConflictException);
- expect(processFindFirst).not.toHaveBeenCalled();
- expect(appointmentFindFirst).toHaveBeenCalledWith({
- where: {
- id: { not: appointment.id },
- client_id: client.id,
- specialist_id: specialist.id,
- product_type: null,
- product_id: null,
- status: {
- in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED],
- },
- },
- });
+ expect(processFindFirst).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: expect.objectContaining({
+ id: { not: currentProcess.id },
+ client_id: client.id,
+ specialist_id: specialist.id,
+ product_type: null,
+ status: { in: expect.arrayContaining([ProcessStatus.SCHEDULING]) },
+ }),
+ }),
+ );
+ expect(appointmentFindFirst).not.toHaveBeenCalled();
});
it.each([
@@ -1854,12 +1903,12 @@ describe('AppointmentsService.confirmPending — snapshot da negociação', () =
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
expect(tx.$queryRaw).toHaveBeenCalledTimes(4);
- expect(tx.$queryRaw.mock.calls[0][1]).toBe('product-money:CAR:product-1');
- expect(tx.$queryRaw.mock.calls[1][1]).toBe(
- 'process-dedup:client-1:specialist-1:CAR:product-1',
+ expect(tx.$queryRaw.mock.calls[0][1]).toBe(
+ 'appointment-schedule:specialist-1',
);
+ expect(tx.$queryRaw.mock.calls[1][1]).toBe('product-money:CAR:product-1');
expect(tx.$queryRaw.mock.calls[2][1]).toBe(
- 'appointment-schedule:specialist-1',
+ 'process-dedup:client-1:specialist-1:CAR:product-1',
);
expect(tx.$queryRaw.mock.calls[3][1]).toBe('product-money:CAR:product-1');
expect(processUpdateMany).toHaveBeenCalledWith({
@@ -2021,8 +2070,7 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
calendly_invitee_uri: appointment.calendly_invitee_uri,
},
data: {
- calendly_event_uri:
- 'https://api.calendly.com/scheduled_events/event-1',
+ 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',
},
@@ -2068,9 +2116,13 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
.fn()
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(trustedDate);
- const service = new AppointmentsService(prisma, {} as any, {
- resolveScheduledStartTime,
- } as any);
+ const service = new AppointmentsService(
+ prisma,
+ {} as any,
+ {
+ resolveScheduledStartTime,
+ } as any,
+ );
await expect(
service.registerCalendlyScheduled(appointment.id, appointment.client_id, {
@@ -2131,9 +2183,13 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
$transaction: jest.fn(async (callback: any) => callback(tx)),
} as any;
const resolveScheduledStartTime = jest.fn().mockResolvedValue(null);
- const service = new AppointmentsService(prisma, {} as any, {
- resolveScheduledStartTime,
- } as any);
+ const service = new AppointmentsService(
+ prisma,
+ {} as any,
+ {
+ resolveScheduledStartTime,
+ } as any,
+ );
await expect(
service.registerCalendlyScheduled(appointment.id, appointment.client_id, {
@@ -2159,8 +2215,7 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
status: StatusAgendamento.PENDING,
scheduling_method: AppointmentSchedulingMethod.CALENDLY,
specialist_rescheduled_at: null,
- calendly_event_uri:
- 'https://api.calendly.com/scheduled_events/event-1',
+ 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_sync_status: CalendlySyncStatus.PENDING,
@@ -2189,9 +2244,13 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
};
return resolvedDate;
});
- const service = new AppointmentsService(prisma, {} as any, {
- resolveScheduledStartTime,
- } as any);
+ const service = new AppointmentsService(
+ prisma,
+ {} as any,
+ {
+ resolveScheduledStartTime,
+ } as any,
+ );
await expect(
service.registerCalendlyScheduled(appointment.id, appointment.client_id, {
@@ -2215,8 +2274,7 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
status: StatusAgendamento.PENDING,
scheduling_method: AppointmentSchedulingMethod.CALENDLY,
specialist_rescheduled_at: null,
- calendly_event_uri:
- 'https://api.calendly.com/scheduled_events/event-1',
+ 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_sync_status: 'PENDING',
@@ -2238,9 +2296,13 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
$transaction: jest.fn(async (callback: any) => callback(tx)),
} as any;
const resolveScheduledStartTime = jest.fn().mockResolvedValue(resolvedDate);
- const service = new AppointmentsService(prisma, {} as any, {
- resolveScheduledStartTime,
- } as any);
+ const service = new AppointmentsService(
+ prisma,
+ {} as any,
+ {
+ resolveScheduledStartTime,
+ } as any,
+ );
await expect(
service.registerCalendlyScheduled(appointment.id, appointment.client_id, {
@@ -2320,8 +2382,7 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
};
const lockedAppointment = {
...appointment,
- calendly_event_uri:
- 'https://api.calendly.com/scheduled_events/event-1',
+ calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1',
calendly_invitee_uri:
'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-old',
};
@@ -2465,8 +2526,7 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
appointment.id,
appointment.client_id,
{
- event_uri:
- 'https://calendly.com/api/v2/scheduled_events/event-1',
+ event_uri: 'https://calendly.com/api/v2/scheduled_events/event-1',
invitee_uri:
'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1',
scheduled_start_time: '2099-01-01T10:00:00.000Z',
@@ -2537,17 +2597,20 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
apiResult instanceof Error
? jest.fn().mockRejectedValue(apiResult)
: jest.fn().mockResolvedValue(apiResult);
- const service = new AppointmentsService(prisma, {} as any, {
- resolveScheduledStartTime,
- } as any);
+ const service = new AppointmentsService(
+ prisma,
+ {} as any,
+ {
+ resolveScheduledStartTime,
+ } as any,
+ );
await expect(
service.registerCalendlyScheduled(
appointment.id,
appointment.client_id,
{
- event_uri:
- 'https://api.calendly.com/scheduled_events/event-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',
@@ -2600,9 +2663,13 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
apiResult instanceof Error
? jest.fn().mockRejectedValue(apiResult)
: jest.fn().mockResolvedValue(apiResult);
- const service = new AppointmentsService(prisma, {} as any, {
- resolveScheduledStartTime,
- } as any);
+ const service = new AppointmentsService(
+ prisma,
+ {} as any,
+ {
+ resolveScheduledStartTime,
+ } as any,
+ );
await expect(
service.registerCalendlyScheduled(
@@ -2651,11 +2718,15 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () =
appointment: { findUnique: jest.fn().mockResolvedValue(appointment) },
$transaction: jest.fn(async (callback: any) => callback(tx)),
} as any;
- const service = new AppointmentsService(prisma, {} as any, {
- resolveScheduledStartTime: jest
- .fn()
- .mockResolvedValue(new Date('2099-01-01T10:00:00.000Z')),
- } as any);
+ const service = new AppointmentsService(
+ prisma,
+ {} as any,
+ {
+ resolveScheduledStartTime: jest
+ .fn()
+ .mockResolvedValue(new Date('2099-01-01T10:00:00.000Z')),
+ } as any,
+ );
await expect(
service.registerCalendlyScheduled(appointment.id, appointment.client_id, {
diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts
index 4dbda1d..970e005 100644
--- a/backend/src/features/appointments/appointments.service.ts
+++ b/backend/src/features/appointments/appointments.service.ts
@@ -48,6 +48,7 @@ import { validateSpecialistProductAssociation } from 'src/features/products/prod
import {
ACTIVE_PROCESS_STATUSES,
acquireActiveProcessDedupLock,
+ assertNoActiveProcess,
lockAndAssertNoActiveProcess,
} from 'src/features/processes/process-dedup-lock';
import {
@@ -1224,6 +1225,16 @@ export class AppointmentsService {
const { appointment, process, product } = await this.prisma.$transaction(
async (tx) => {
+ // Ordem global dos advisory locks: agenda → produto → deduplicação.
+ // Consultoria datada não tem lock de produto, portanto agenda → dedup.
+ if (isConsultancy && pendingDateTime) {
+ await lockAndAssertSpecialistScheduleAvailable(
+ tx,
+ dto.specialist_id,
+ pendingDateTime,
+ );
+ }
+
const product = await validateSpecialistProductAssociation(tx, {
specialistId: dto.specialist_id,
productType: dto.product_type,
@@ -1238,27 +1249,17 @@ export class AppointmentsService {
};
if (isConsultancy) {
await acquireActiveProcessDedupLock(tx, processScope);
+ await assertNoActiveProcess(tx, processScope, undefined, {
+ authenticatedClientId: userId,
+ });
const existingAfterLock = await tx.appointment.findFirst({
where: consultancyAppointmentWhere,
});
assertNoDuplicateAppointment(existingAfterLock);
} else {
- await lockAndAssertNoActiveProcess(
- tx,
- processScope,
- undefined,
- { authenticatedClientId: userId },
- );
- }
-
- // 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,
- pendingDateTime,
- );
+ await lockAndAssertNoActiveProcess(tx, processScope, undefined, {
+ authenticatedClientId: userId,
+ });
}
const appointment = await tx.appointment.create({
@@ -1311,6 +1312,9 @@ export class AppointmentsService {
this.mapToResponseEntity(appointment, client, specialist, product),
{
process_id: process.id,
+ ...(schedulingMethod === AppointmentSchedulingMethod.EMAIL
+ ? { specialist_contact_email: specialist.email }
+ : {}),
},
);
}
@@ -1455,6 +1459,11 @@ export class AppointmentsService {
// Atualizar para SCHEDULED e atualizar Process para NEGOTIATION em transação
const [updated, process] = await this.prisma.$transaction(async (tx) => {
+ // Ordem global dos advisory locks: agenda → produto → deduplicação.
+ // updateStatus já usa agenda → produto; manter a mesma ordem elimina o
+ // ciclo em que cada transação aguardava o lock retido pela outra.
+ await acquireSpecialistScheduleLock(tx, appointment.specialist_id);
+
await validateSpecialistProductAssociation(tx, {
specialistId: appointment.specialist_id,
productType: appointment.product_type,
@@ -1472,6 +1481,7 @@ export class AppointmentsService {
if (isConsultancy) {
await acquireActiveProcessDedupLock(tx, processScope);
+ await assertNoActiveProcess(tx, processScope, appointment.process?.id);
const existingAppointment = await tx.appointment.findFirst({
where: {
id: { not: appointmentId },
@@ -1505,8 +1515,6 @@ export class AppointmentsService {
appointment.process?.id,
);
}
- await acquireSpecialistScheduleLock(tx, appointment.specialist_id);
-
const lockedAppointment = await tx.appointment.findUnique({
where: { id: appointmentId },
include: { client: true, specialist: true, process: true },
@@ -1923,6 +1931,7 @@ export class AppointmentsService {
scheduling_method: true,
appointment_datetime: true,
process: { select: { id: true, client_id: true } },
+ specialist: { select: { email: true } },
},
});
@@ -1934,6 +1943,7 @@ export class AppointmentsService {
) {
return { exists: false };
}
+ const specialistContactEmail = appointment.specialist?.email;
return {
exists: true,
appointment_id: appointment.id,
@@ -1941,6 +1951,10 @@ export class AppointmentsService {
appointment_status: appointment.status,
scheduling_method: appointment.scheduling_method,
appointment_datetime: appointment.appointment_datetime,
+ ...(appointment.scheduling_method === AppointmentSchedulingMethod.EMAIL &&
+ specialistContactEmail
+ ? { specialist_contact_email: specialistContactEmail }
+ : {}),
};
}
@@ -2037,10 +2051,7 @@ export class AppointmentsService {
?.canonicalUri === eventUri
) {
const storedInviteeReference = appointment.calendly_invitee_uri
- ? parseCalendlyResourceUri(
- appointment.calendly_invitee_uri,
- 'invitee',
- )
+ ? parseCalendlyResourceUri(appointment.calendly_invitee_uri, 'invitee')
: null;
if (
appointment.calendly_invitee_uri &&
@@ -2150,10 +2161,8 @@ export class AppointmentsService {
}
if (
lockedAppointment.calendly_event_uri &&
- parseCalendlyResourceUri(
- lockedAppointment.calendly_event_uri,
- 'event',
- )?.canonicalUri === eventUri
+ parseCalendlyResourceUri(lockedAppointment.calendly_event_uri, 'event')
+ ?.canonicalUri === eventUri
) {
if (
lockedAppointment.calendly_invitee_uri &&
diff --git a/backend/src/features/appointments/entities/appointment.response.ts b/backend/src/features/appointments/entities/appointment.response.ts
index fb56052..1157530 100644
--- a/backend/src/features/appointments/entities/appointment.response.ts
+++ b/backend/src/features/appointments/entities/appointment.response.ts
@@ -15,6 +15,7 @@ export type ExistingAppointmentCheck =
appointment_status: StatusAgendamento;
scheduling_method: AppointmentSchedulingMethod | null;
appointment_datetime: Date | null;
+ specialist_contact_email?: string;
};
export interface ActiveProcessSnapshot {
@@ -23,6 +24,7 @@ export interface ActiveProcessSnapshot {
appointment_status: StatusAgendamento | null;
scheduling_method: AppointmentSchedulingMethod | null;
appointment_datetime: Date | null;
+ specialist_contact_email?: string;
}
/**
@@ -161,6 +163,10 @@ export class AppointmentResponseEntity {
@Expose()
process_id?: string;
+ /** Contato liberado somente ao cliente autenticado no fluxo EMAIL. */
+ @Expose()
+ specialist_contact_email?: string;
+
/**
* ID único do agendamento (UUID)
*/
diff --git a/backend/src/features/notifications/notification.service.spec.ts b/backend/src/features/notifications/notification.service.spec.ts
index dc661d1..95f9626 100644
--- a/backend/src/features/notifications/notification.service.spec.ts
+++ b/backend/src/features/notifications/notification.service.spec.ts
@@ -173,4 +173,24 @@ describe('NotificationService proposal emails', () => {
expect(htmlBody).not.toContain(' alert(1)');
});
+
+ it('escapes user-controlled fields in process status HTML', async () => {
+ await service.sendProcessStatusChangedEmail({
+ recipientEmail: 'client@example.com',
+ recipientName: ' ',
+ processId: 'process-1',
+ previousStatus: 'SCHEDULING',
+ currentStatus: 'REJECTED',
+ changedByName: 'Actor ',
+ productDetails: 'Product ',
+ reason: '',
+ });
+
+ const htmlBody = sendEmailSafely.mock.calls[0][3];
+ expect(htmlBody).toContain('<img');
+ expect(htmlBody).toContain('<b>Actor</b>');
+ expect(htmlBody).toContain('<i>Product</i>');
+ expect(htmlBody).toContain('<script>alert(1)</script>');
+ expect(htmlBody).not.toContain('');
+ });
});
diff --git a/backend/src/features/notifications/notification.service.ts b/backend/src/features/notifications/notification.service.ts
index d35c62a..fbe76cf 100644
--- a/backend/src/features/notifications/notification.service.ts
+++ b/backend/src/features/notifications/notification.service.ts
@@ -1473,6 +1473,20 @@ Acesse ${this.frontendUrl}/processes/${data.processId}/negotiation para continua
const previousStatusLabel = data.previousStatus
? (statusLabelMap[data.previousStatus] ?? data.previousStatus)
: undefined;
+ const recipientName = escapeHtml(data.recipientName);
+ const safeProcessId = escapeHtml(data.processId);
+ const safePreviousStatusLabel = previousStatusLabel
+ ? escapeHtml(previousStatusLabel)
+ : undefined;
+ const safeCurrentStatusLabel = escapeHtml(currentStatusLabel);
+ const changedByName = data.changedByName
+ ? escapeHtml(data.changedByName)
+ : undefined;
+ const productDetails = data.productDetails
+ ? escapeHtml(data.productDetails)
+ : undefined;
+ const reason = data.reason ? escapeHtml(data.reason) : undefined;
+ const processPath = encodeURIComponent(data.processId);
const subject = `Atualização no Processo #${data.processId.slice(0, 8)} | BMF Lux Brokerage`;
@@ -1486,18 +1500,18 @@ Acesse ${this.frontendUrl}/processes/${data.processId}/negotiation para continua
Atualização de Processo
-
Olá ${data.recipientName} ,
+
Olá ${recipientName} ,
Houve uma atualização importante no seu processo.
-
Processo: ${data.processId}
- ${previousStatusLabel ? `
Status anterior: ${previousStatusLabel}
` : ''}
-
Novo status: ${currentStatusLabel}
- ${data.changedByName ? `
Atualizado por: ${data.changedByName}
` : ''}
- ${data.productDetails ? `
Produto: ${data.productDetails}
` : ''}
- ${data.reason ? `
Detalhes: ${data.reason}
` : ''}
+
Processo: ${safeProcessId}
+ ${safePreviousStatusLabel ? `
Status anterior: ${safePreviousStatusLabel}
` : ''}
+
Novo status: ${safeCurrentStatusLabel}
+ ${changedByName ? `
Atualizado por: ${changedByName}
` : ''}
+ ${productDetails ? `
Produto: ${productDetails}
` : ''}
+ ${reason ? `
Detalhes: ${reason}
` : ''}
-
diff --git a/backend/src/features/processes/process-dedup-lock.spec.ts b/backend/src/features/processes/process-dedup-lock.spec.ts
index cd4fc32..1bfec01 100644
--- a/backend/src/features/processes/process-dedup-lock.spec.ts
+++ b/backend/src/features/processes/process-dedup-lock.spec.ts
@@ -86,6 +86,7 @@ describe('own active process snapshot', () => {
id: 'process-1',
client_id: scope.clientId,
appointment: attached,
+ specialist: { email: 'specialist@example.com' },
notes: 'private-notes',
});
expect(await response(tx)).toEqual({
@@ -100,6 +101,9 @@ describe('own active process snapshot', () => {
appointment_status: attached?.status ?? null,
scheduling_method: attached?.scheduling_method ?? null,
appointment_datetime: attached?.appointment_datetime ?? null,
+ ...(attached
+ ? { specialist_contact_email: 'specialist@example.com' }
+ : {}),
},
},
},
@@ -118,6 +122,7 @@ describe('own active process snapshot', () => {
appointment_datetime: true,
},
},
+ specialist: { select: { email: true } },
},
});
},
diff --git a/backend/src/features/processes/process-dedup-lock.ts b/backend/src/features/processes/process-dedup-lock.ts
index 3bf2ead..4fc3f5d 100644
--- a/backend/src/features/processes/process-dedup-lock.ts
+++ b/backend/src/features/processes/process-dedup-lock.ts
@@ -1,5 +1,9 @@
import { ConflictException } from '@nestjs/common';
-import { ProcessStatus, ProductType } from '@prisma/client';
+import {
+ AppointmentSchedulingMethod,
+ ProcessStatus,
+ ProductType,
+} from '@prisma/client';
import type { ActiveProcessSnapshot } from '../appointments/entities/appointment.response';
export const ACTIVE_PROCESS_STATUSES: ProcessStatus[] = [
@@ -78,6 +82,7 @@ export async function assertNoActiveProcess(
appointment_datetime: true,
},
},
+ specialist: { select: { email: true } },
},
});
if (existing) {
@@ -95,6 +100,10 @@ export async function assertNoActiveProcess(
appointment_status: appointment?.status ?? null,
scheduling_method: appointment?.scheduling_method ?? null,
appointment_datetime: appointment?.appointment_datetime ?? null,
+ ...(appointment?.scheduling_method ===
+ AppointmentSchedulingMethod.EMAIL && existing.specialist?.email
+ ? { specialist_contact_email: existing.specialist.email }
+ : {}),
};
throw new ConflictException({
success: false,
diff --git a/backend/src/features/processes/processes-dedup-concurrency.postgres.spec.ts b/backend/src/features/processes/processes-dedup-concurrency.postgres.spec.ts
index f370317..6973f3e 100644
--- a/backend/src/features/processes/processes-dedup-concurrency.postgres.spec.ts
+++ b/backend/src/features/processes/processes-dedup-concurrency.postgres.spec.ts
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
import { ConflictException } from '@nestjs/common';
-import { PrismaClient, UserRole } from '@prisma/client';
+import { PrismaClient, ProcessStatus, UserRole } from '@prisma/client';
import { ProcessesService } from './processes.service';
type Deferred = { promise: Promise; resolve: () => void };
@@ -52,239 +52,388 @@ function signalDedupLockAttempt(client: PrismaClient, attempted: Deferred) {
const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL;
const describeWithPostgres = databaseUrl ? describe : describe.skip;
-describeWithPostgres('process active dedup lock — PostgreSQL concurrency', () => {
- const suffix = randomUUID().replaceAll('-', '');
- const clientId = randomUUID();
- const specialistId = randomUUID();
- const first = new PrismaClient({
- datasources: { db: { url: withApplicationName(databaseUrl!, `dedup_a_${suffix}`) } },
- });
- const second = new PrismaClient({
- datasources: { db: { url: withApplicationName(databaseUrl!, `dedup_b_${suffix}`) } },
- });
- const holder = new PrismaClient({
- datasources: { db: { url: withApplicationName(databaseUrl!, `dedup_holder_${suffix}`) } },
- });
-
- beforeAll(async () => {
- await holder.user.createMany({
- data: [
- {
- id: clientId,
- name: 'Dedup',
- surname: 'Client',
- email: `dedup-client-${suffix}@example.test`,
- rg: suffix.slice(0, 11),
- role: UserRole.CUSTOMER,
- password_hash: 'not-used',
- },
- {
- id: specialistId,
- name: 'Dedup',
- surname: 'Specialist',
- email: `dedup-specialist-${suffix}@example.test`,
- rg: suffix.slice(11, 22),
- role: UserRole.SPECIALIST,
- password_hash: 'not-used',
+describeWithPostgres(
+ 'process active dedup lock — PostgreSQL concurrency',
+ () => {
+ const suffix = randomUUID().replaceAll('-', '');
+ const clientId = randomUUID();
+ const specialistId = randomUUID();
+ const otherSpecialistId = randomUUID();
+ const first = new PrismaClient({
+ datasources: {
+ db: { url: withApplicationName(databaseUrl!, `dedup_a_${suffix}`) },
+ },
+ });
+ const second = new PrismaClient({
+ datasources: {
+ db: { url: withApplicationName(databaseUrl!, `dedup_b_${suffix}`) },
+ },
+ });
+ const holder = new PrismaClient({
+ datasources: {
+ db: {
+ url: withApplicationName(databaseUrl!, `dedup_holder_${suffix}`),
},
- ],
+ },
});
- });
- beforeEach(async () => {
- const processes = await holder.process.findMany({
- where: { client_id: clientId, specialist_id: specialistId },
- select: { id: true, appointment_id: true },
+ beforeAll(async () => {
+ await holder.user.createMany({
+ data: [
+ {
+ id: clientId,
+ name: 'Dedup',
+ surname: 'Client',
+ email: `dedup-client-${suffix}@example.test`,
+ rg: suffix.slice(0, 11),
+ role: UserRole.CUSTOMER,
+ password_hash: 'not-used',
+ },
+ {
+ id: specialistId,
+ name: 'Dedup',
+ surname: 'Specialist',
+ email: `dedup-specialist-${suffix}@example.test`,
+ rg: suffix.slice(11, 22),
+ role: UserRole.SPECIALIST,
+ password_hash: 'not-used',
+ },
+ {
+ id: otherSpecialistId,
+ name: 'Other',
+ surname: 'Specialist',
+ email: `dedup-other-specialist-${suffix}@example.test`,
+ rg: suffix.slice(22, 32),
+ role: UserRole.SPECIALIST,
+ password_hash: 'not-used',
+ },
+ ],
+ });
});
- await holder.processStatusHistory.deleteMany({
- where: { processId: { in: processes.map(({ id }) => id) } },
+
+ beforeEach(async () => {
+ const processes = await holder.process.findMany({
+ where: { client_id: clientId },
+ select: { id: true, appointment_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: processes.flatMap(({ appointment_id }) =>
+ appointment_id ? [appointment_id] : [],
+ ),
+ },
+ },
+ });
});
- await holder.process.deleteMany({
- where: { id: { in: processes.map(({ id }) => id) } },
+
+ afterAll(async () => {
+ const processes = await holder.process.findMany({
+ where: { client_id: clientId },
+ select: { id: true, appointment_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: processes.flatMap(({ appointment_id }) =>
+ appointment_id ? [appointment_id] : [],
+ ),
+ },
+ },
+ });
+ await holder.user.deleteMany({
+ where: { id: { in: [clientId, specialistId, otherSpecialistId] } },
+ });
+ await Promise.all([
+ first.$disconnect(),
+ second.$disconnect(),
+ holder.$disconnect(),
+ ]);
});
- await holder.appointment.deleteMany({
- where: {
- id: {
- in: processes.flatMap(({ appointment_id }) =>
- appointment_id ? [appointment_id] : [],
+
+ it.each(['completed appointment', 'legacy without appointment'] as const)(
+ 'rejects create-on-behalf when an active consultancy already exists with %s',
+ async (fixture) => {
+ const appointment =
+ fixture === 'completed appointment'
+ ? await holder.appointment.create({
+ data: {
+ client_id: clientId,
+ specialist_id: specialistId,
+ status: 'COMPLETED',
+ scheduling_method: 'EMAIL',
+ appointment_datetime: new Date('2026-01-01T10:00:00.000Z'),
+ },
+ })
+ : null;
+ await holder.process.create({
+ data: {
+ client_id: clientId,
+ specialist_id: specialistId,
+ appointment_id: appointment?.id,
+ status: ProcessStatus.SCHEDULING,
+ },
+ });
+
+ await expect(
+ new ProcessesService(holder as any, {} as any).createOnBehalfOfClient(
+ {
+ client_id: clientId,
+ specialist_id: specialistId,
+ product_type: 'CAR',
+ product_id: undefined,
+ createdBy: specialistId,
+ actorLabel: 'consultor',
+ },
),
- },
+ ).rejects.toThrow(ConflictException);
+
+ await expect(
+ holder.process.count({
+ where: {
+ client_id: clientId,
+ specialist_id: specialistId,
+ status: ProcessStatus.SCHEDULING,
+ },
+ }),
+ ).resolves.toBe(1);
},
- });
- });
+ 15_000,
+ );
- afterAll(async () => {
- const processes = await holder.process.findMany({
- where: { client_id: clientId, specialist_id: specialistId },
- select: { id: true, appointment_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: processes.flatMap(({ appointment_id }) => appointment_id ? [appointment_id] : []) } },
+ it('returns only the assigned specialist processes in both rows and count', async () => {
+ const own = await holder.process.create({
+ data: {
+ client_id: clientId,
+ specialist_id: specialistId,
+ status: ProcessStatus.SCHEDULING,
+ },
+ });
+ await holder.process.create({
+ data: {
+ client_id: clientId,
+ specialist_id: otherSpecialistId,
+ status: ProcessStatus.SCHEDULING,
+ },
+ });
+
+ const result = await new ProcessesService(
+ holder as any,
+ {} as any,
+ ).getByClientId(
+ clientId,
+ { page: 1, perPage: 20 },
+ specialistId,
+ UserRole.SPECIALIST,
+ );
+
+ expect(result.count).toBe(1);
+ expect(result.processes.map(({ id }) => id)).toEqual([own.id]);
});
- await holder.user.deleteMany({ where: { id: { in: [clientId, specialistId] } } });
- await Promise.all([first.$disconnect(), second.$disconnect(), holder.$disconnect()]);
- });
- it('allows only one concurrent active consultancy for the same client and specialist', async () => {
- const lockKey = `process-dedup:${clientId}:${specialistId}:CONSULTANCY:none`;
- const holderReady = deferred();
- const releaseHolder = deferred();
- const firstAttempted = deferred();
- const secondAttempted = deferred();
- const held = holder.$transaction(async (tx) => {
- await tx.$queryRaw`
+ it('allows only one concurrent active consultancy for the same client and specialist', async () => {
+ const lockKey = `process-dedup:${clientId}:${specialistId}:CONSULTANCY:none`;
+ 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;
- });
- await holderReady.promise;
+ holderReady.resolve();
+ await releaseHolder.promise;
+ });
+ await holderReady.promise;
- const serviceA = new ProcessesService(
- signalDedupLockAttempt(first, firstAttempted) as any,
- {} as any,
- );
- const serviceB = new ProcessesService(
- signalDedupLockAttempt(second, secondAttempted) as any,
- {} as any,
- );
- const input = {
- client_id: clientId,
- specialist_id: specialistId,
- product_type: 'CAR' as const,
- product_id: undefined,
- createdBy: specialistId,
- actorLabel: 'especialista',
- };
+ const serviceA = new ProcessesService(
+ signalDedupLockAttempt(first, firstAttempted) as any,
+ {} as any,
+ );
+ const serviceB = new ProcessesService(
+ signalDedupLockAttempt(second, secondAttempted) as any,
+ {} as any,
+ );
+ const input = {
+ client_id: clientId,
+ specialist_id: specialistId,
+ product_type: 'CAR' as const,
+ product_id: undefined,
+ createdBy: specialistId,
+ actorLabel: 'especialista',
+ };
- const outcomesPromise = Promise.allSettled([
- serviceA.createOnBehalfOfClient(input),
- serviceB.createOnBehalfOfClient(input),
- ]);
- await Promise.all([firstAttempted.promise, secondAttempted.promise]);
- releaseHolder.resolve();
- await held;
- const outcomes = await outcomesPromise;
+ const outcomesPromise = Promise.allSettled([
+ serviceA.createOnBehalfOfClient(input),
+ serviceB.createOnBehalfOfClient(input),
+ ]);
+ 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.process.count({ where: { client_id: clientId, specialist_id: specialistId } }),
- ).resolves.toBe(1);
- }, 15_000);
+ expect(
+ outcomes.filter(({ status }) => status === 'fulfilled'),
+ ).toHaveLength(1);
+ expect(
+ outcomes.find(({ status }) => status === 'rejected'),
+ ).toMatchObject({
+ reason: expect.any(ConflictException),
+ });
+ await expect(
+ holder.process.count({
+ where: { client_id: clientId, specialist_id: specialistId },
+ }),
+ ).resolves.toBe(1);
+ }, 15_000);
- it('serializes two public create requests on the same active-process key', async () => {
- const lockKey = `process-dedup:${clientId}:${specialistId}:CONSULTANCY:none`;
- const holderReady = deferred();
- const releaseHolder = deferred();
- const firstAttempted = deferred();
- const secondAttempted = deferred();
- const held = holder.$transaction(async (tx) => {
- await tx.$queryRaw`
+ it('serializes two public create requests on the same active-process key', async () => {
+ const lockKey = `process-dedup:${clientId}:${specialistId}:CONSULTANCY:none`;
+ 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;
- });
- await holderReady.promise;
+ holderReady.resolve();
+ await releaseHolder.promise;
+ });
+ await holderReady.promise;
- const serviceA = new ProcessesService(
- signalDedupLockAttempt(first, firstAttempted) as any,
- {} as any,
- );
- const serviceB = new ProcessesService(
- signalDedupLockAttempt(second, secondAttempted) as any,
- {} as any,
- );
- const dto = {
- client_id: clientId,
- specialist_id: specialistId,
- } as any;
- const requester = { id: randomUUID(), role: UserRole.ADMIN };
- const firstCreate = serviceA.create(dto, requester);
- const secondCreate = serviceB.create(dto, requester);
- const bothAttemptedBeforeCompletion = await Promise.race([
- Promise.all([firstAttempted.promise, secondAttempted.promise]).then(
- () => true,
- ),
- Promise.allSettled([firstCreate, secondCreate]).then(() => false),
- ]);
- releaseHolder.resolve();
- await held;
- const outcomes = await Promise.allSettled([firstCreate, secondCreate]);
+ const serviceA = new ProcessesService(
+ signalDedupLockAttempt(first, firstAttempted) as any,
+ {} as any,
+ );
+ const serviceB = new ProcessesService(
+ signalDedupLockAttempt(second, secondAttempted) as any,
+ {} as any,
+ );
+ const dto = {
+ client_id: clientId,
+ specialist_id: specialistId,
+ } as any;
+ const requester = { id: randomUUID(), role: UserRole.ADMIN };
+ const firstCreate = serviceA.create(dto, requester);
+ const secondCreate = serviceB.create(dto, requester);
+ const bothAttemptedBeforeCompletion = await Promise.race([
+ Promise.all([firstAttempted.promise, secondAttempted.promise]).then(
+ () => true,
+ ),
+ Promise.allSettled([firstCreate, secondCreate]).then(() => false),
+ ]);
+ releaseHolder.resolve();
+ await held;
+ const outcomes = await Promise.allSettled([firstCreate, secondCreate]);
- 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);
+ 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 public create with create-on-behalf without blocking consultancy', async () => {
- const lockKey = `process-dedup:${clientId}:${specialistId}:CONSULTANCY:none`;
- const holderReady = deferred();
- const releaseHolder = deferred();
- const publicAttempted = deferred();
- const behalfAttempted = deferred();
- const held = holder.$transaction(async (tx) => {
- await tx.$queryRaw`
+ it('serializes public create with create-on-behalf and permits only one active consultancy', async () => {
+ const lockKey = `process-dedup:${clientId}:${specialistId}:CONSULTANCY:none`;
+ const holderReady = deferred();
+ const releaseHolder = deferred();
+ const publicAttempted = deferred();
+ const behalfAttempted = 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;
- });
- await holderReady.promise;
+ holderReady.resolve();
+ await releaseHolder.promise;
+ });
+ await holderReady.promise;
- const publicService = new ProcessesService(
- signalDedupLockAttempt(first, publicAttempted) as any,
- {} as any,
- );
- const behalfService = new ProcessesService(
- signalDedupLockAttempt(second, behalfAttempted) as any,
- {} as any,
- );
- const publicCreate = publicService.create(
- { client_id: clientId, specialist_id: specialistId } as any,
- { id: randomUUID(), role: UserRole.ADMIN },
- );
- const behalfCreate = behalfService.createOnBehalfOfClient({
- client_id: clientId,
- specialist_id: specialistId,
- product_type: 'CAR',
- product_id: undefined,
- createdBy: specialistId,
- actorLabel: 'especialista',
- });
- const bothAttemptedBeforeCompletion = await Promise.race([
- Promise.all([publicAttempted.promise, behalfAttempted.promise]).then(
- () => true,
- ),
- publicCreate.then(
- () => false,
- () => false,
- ),
- ]);
- releaseHolder.resolve();
- await held;
- const outcomes = await Promise.allSettled([publicCreate, behalfCreate]);
+ const publicService = new ProcessesService(
+ signalDedupLockAttempt(first, publicAttempted) as any,
+ {} as any,
+ );
+ const behalfService = new ProcessesService(
+ signalDedupLockAttempt(second, behalfAttempted) as any,
+ {} as any,
+ );
+ const publicCreate = publicService.create(
+ { client_id: clientId, specialist_id: specialistId } as any,
+ { id: randomUUID(), role: UserRole.ADMIN },
+ );
+ const behalfCreate = behalfService.createOnBehalfOfClient({
+ client_id: clientId,
+ specialist_id: specialistId,
+ product_type: 'CAR',
+ product_id: undefined,
+ createdBy: specialistId,
+ actorLabel: 'especialista',
+ });
+ const bothAttemptedBeforeCompletion = await Promise.race([
+ Promise.all([publicAttempted.promise, behalfAttempted.promise]).then(
+ () => true,
+ ),
+ publicCreate.then(
+ () => false,
+ () => false,
+ ),
+ ]);
+ releaseHolder.resolve();
+ await held;
+ const outcomes = await Promise.allSettled([publicCreate, behalfCreate]);
- expect(bothAttemptedBeforeCompletion).toBe(true);
- expect(outcomes[1]).toMatchObject({ status: 'fulfilled' });
- await expect(
- holder.appointment.count({
- where: {
- client_id: clientId,
- specialist_id: specialistId,
- product_type: null,
- product_id: null,
- },
- }),
- ).resolves.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),
+ });
+ await expect(
+ holder.appointment.count({
+ where: {
+ client_id: clientId,
+ specialist_id: specialistId,
+ product_type: null,
+ product_id: null,
+ },
+ }),
+ ).resolves.toBeLessThanOrEqual(1);
+ await expect(
+ holder.process.count({
+ where: {
+ client_id: clientId,
+ specialist_id: specialistId,
+ product_type: null,
+ status: {
+ in: [
+ ProcessStatus.SCHEDULING,
+ ProcessStatus.NEGOTIATION,
+ ProcessStatus.PROCESSING_CONTRACT,
+ ProcessStatus.DOCUMENTATION,
+ ],
+ },
+ },
+ }),
+ ).resolves.toBe(1);
+ }, 15_000);
+ },
+);
diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts
index 7c5929e..e885934 100644
--- a/backend/src/features/processes/processes.service.spec.ts
+++ b/backend/src/features/processes/processes.service.spec.ts
@@ -116,6 +116,7 @@ describe('ProcessesService — produto UUID', () => {
appointment_datetime: true,
},
},
+ specialist: { select: { email: true } },
},
}),
);
@@ -204,6 +205,14 @@ describe('ProcessesService.create — autorização por cliente', () => {
).rejects.toThrow(ForbiddenException);
});
+ it('SPECIALIST não usa a rota genérica para escolher cliente nem obter PII', async () => {
+ const { service } = mkService();
+
+ await expect(
+ service.create(dto, { id: specialistId, role: UserRole.SPECIALIST }),
+ ).rejects.toThrow(ForbiddenException);
+ });
+
it('CUSTOMER não cria processo em nome de outro cliente', async () => {
const { service } = mkService();
@@ -381,29 +390,58 @@ describe('ProcessesService.createOnBehalfOfClient', () => {
expect(data.notes).toContain('Consultoria');
});
- it('permite consultoria em nome do cliente mesmo com processo ativo anterior', async () => {
+ it('rejeita consultoria em nome do cliente quando há processo ativo mesmo com appointment concluído', async () => {
const { service, appointmentCreate, tx } = mkService();
- tx.process.findFirst.mockResolvedValue({ id: 'active-process-1' });
-
- await service.createOnBehalfOfClient({
- ...base,
- product_id: undefined,
- actorLabel: 'consultor',
- });
-
- expect(tx.process.findFirst).not.toHaveBeenCalled();
- expect(tx.appointment.findFirst).toHaveBeenCalledWith({
- where: {
+ tx.process.findFirst.mockResolvedValue({
+ id: 'active-process-1',
+ client_id: clientId,
+ appointment: {
+ id: 'completed-appointment-1',
client_id: clientId,
- specialist_id: specialistId,
- product_type: null,
- product_id: null,
- status: {
- in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED],
- },
+ status: StatusAgendamento.COMPLETED,
+ scheduling_method: AppointmentSchedulingMethod.EMAIL,
+ appointment_datetime: new Date('2026-01-01T10:00:00.000Z'),
},
});
- expect(appointmentCreate).toHaveBeenCalled();
+
+ await expect(
+ service.createOnBehalfOfClient({
+ ...base,
+ product_id: undefined,
+ actorLabel: 'consultor',
+ }),
+ ).rejects.toThrow(ConflictException);
+
+ expect(tx.process.findFirst).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: expect.objectContaining({
+ client_id: clientId,
+ specialist_id: specialistId,
+ product_type: null,
+ status: { in: expect.arrayContaining([ProcessStatus.SCHEDULING]) },
+ }),
+ }),
+ );
+ expect(appointmentCreate).not.toHaveBeenCalled();
+ });
+
+ it('rejeita consultoria em nome do cliente diante de processo ativo legado sem appointment', async () => {
+ const { service, appointmentCreate, tx } = mkService();
+ tx.process.findFirst.mockResolvedValue({
+ id: 'legacy-active-process-1',
+ client_id: clientId,
+ appointment: null,
+ });
+
+ await expect(
+ service.createOnBehalfOfClient({
+ ...base,
+ product_id: undefined,
+ actorLabel: 'consultor',
+ }),
+ ).rejects.toThrow(ConflictException);
+
+ expect(appointmentCreate).not.toHaveBeenCalled();
});
it('rejeita consultoria duplicada em nome do cliente', async () => {
@@ -1581,6 +1619,7 @@ describe('ProcessesService — telefone da contraparte após confirmação', ()
const prisma = {
user: {
findUnique: jest.fn().mockResolvedValue({
+ role: UserRole.CUSTOMER,
consultant_id: 'consultant-1',
}),
},
@@ -1624,6 +1663,55 @@ describe('ProcessesService — telefone da contraparte após confirmação', ()
},
);
+ it('aplica o mesmo escopo do especialista atribuído em findMany e count da lista por cliente', async () => {
+ const service = listService(StatusAgendamento.SCHEDULED);
+
+ await service.getByClientId(
+ clientId,
+ { page: 1, perPage: 20 } as any,
+ specialistId,
+ UserRole.SPECIALIST,
+ );
+
+ const processDelegate = (service as any).prismaService.process;
+ const expectedWhere = {
+ client_id: clientId,
+ specialist_id: specialistId,
+ };
+ expect(processDelegate.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({ where: expectedWhere }),
+ );
+ expect(processDelegate.count).toHaveBeenCalledWith({
+ where: expectedWhere,
+ });
+ });
+
+ it('mantém o vínculo do consultor no where de findMany e count', async () => {
+ const service = listService(StatusAgendamento.SCHEDULED);
+
+ await service.getByClientId(
+ clientId,
+ { page: 1, perPage: 20 } as any,
+ 'consultant-1',
+ UserRole.CONSULTANT,
+ );
+
+ const processDelegate = (service as any).prismaService.process;
+ const expectedWhere = {
+ client_id: clientId,
+ client: {
+ role: UserRole.CUSTOMER,
+ consultant_id: 'consultant-1',
+ },
+ };
+ expect(processDelegate.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({ where: expectedWhere }),
+ );
+ expect(processDelegate.count).toHaveBeenCalledWith({
+ where: expectedWhere,
+ });
+ });
+
it.each([
[StatusAgendamento.PENDING, null],
[StatusAgendamento.SCHEDULED, clientPhone],
@@ -1812,9 +1900,10 @@ describe('ProcessesService — matriz de contatos do cliente', () => {
};
const prisma = {
user: {
- findUnique: jest
- .fn()
- .mockResolvedValue({ consultant_id: 'consultant-1' }),
+ findUnique: jest.fn().mockResolvedValue({
+ role: UserRole.CUSTOMER,
+ consultant_id: 'consultant-1',
+ }),
},
process: {
findUniqueOrThrow: jest.fn().mockResolvedValue(process),
diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts
index f0643cf..1c6d00f 100644
--- a/backend/src/features/processes/processes.service.ts
+++ b/backend/src/features/processes/processes.service.ts
@@ -34,6 +34,7 @@ import { acquireProductMonetaryLock } from '../products/product-monetary-lock';
import { validateSpecialistProductAssociation } from '../products/product-association-validator';
import {
acquireActiveProcessDedupLock,
+ assertNoActiveProcess,
lockAndAssertNoActiveProcess,
} from './process-dedup-lock';
import { parseDate, isFutureDate } from 'src/shared/utils/date.utils';
@@ -355,9 +356,9 @@ export class ProcessesService {
* Antes disso o endpoint aceitava qualquer `client_id` de qualquer usuário
* autenticado: dava para abrir processo em nome de um cliente alheio.
*
- * O especialista não é restringido a clientes com quem já tem relação —
- * abrir o primeiro processo de um cliente novo é justamente o caso de uso
- * da tela dele. O que se exige é que ele seja o especialista do processo.
+ * Especialistas não usam esta rota genérica: o fluxo legítimo parte de um
+ * pedido autenticado do cliente, ou das rotas delegadas de consultor/escritório.
+ * Assim, um client_id arbitrário nunca vira um oráculo de dados pessoais.
*
* @throws {ForbiddenException} - Sem vínculo com o cliente informado
*/
@@ -383,11 +384,13 @@ export class ProcessesService {
case UserRole.ADMIN:
return;
- case UserRole.SPECIALIST:
- if (dto.specialist_id !== requester.id) {
- deny('especialista só cria processo para si mesmo');
- }
- return;
+ case UserRole.SPECIALIST: {
+ // O fluxo legítimo começa pelo pedido autenticado do próprio cliente.
+ // Esta rota genérica devolve dados do cliente criado; permitir que o
+ // especialista forneça client_id a transformaria em um oráculo de PII.
+ deny('especialista deve partir de um pedido do cliente');
+ break;
+ }
case UserRole.CUSTOMER:
if (dto.client_id !== requester.id) {
@@ -587,6 +590,7 @@ export class ProcessesService {
if (isConsultancy) {
await acquireActiveProcessDedupLock(tx, processScope);
+ await assertNoActiveProcess(tx, processScope);
const existingAppointment = await tx.appointment.findFirst({
where: {
client_id: input.client_id,
@@ -1888,31 +1892,49 @@ export class ProcessesService {
processes: (ProcessResponse & { rejection_reason?: string | null })[];
count: number;
}> {
- if (userId && userRole !== 'ADMIN' && userId !== clientId) {
- const client = await this.prismaService.user.findUnique({
- where: { id: clientId },
- select: { consultant_id: true },
+ const deny = (): never => {
+ throw new ForbiddenException({
+ success: false,
+ error: {
+ code: 403,
+ message: 'Você não tem acesso a este cliente',
+ details: { user_id: userId, client_id: clientId },
+ },
});
+ };
+ if (!userId || !userRole) deny();
- const isConsultantOfClient =
- userRole === 'CONSULTANT' && client?.consultant_id === userId;
- const isSpecialistWithProcess =
- userRole === 'SPECIALIST' &&
- (await this.prismaService.process.findFirst({
- where: { client_id: clientId, specialist_id: userId },
- select: { id: true },
- }));
-
- if (!isConsultantOfClient && !isSpecialistWithProcess) {
- throw new ForbiddenException({
- success: false,
- error: {
- code: 403,
- message: 'Você não tem acesso a este cliente',
- details: { user_id: userId, client_id: clientId },
- },
+ const where: Prisma.ProcessWhereInput = { client_id: clientId };
+ switch (userRole) {
+ case UserRole.ADMIN:
+ break;
+ case UserRole.CUSTOMER:
+ if (userId !== clientId) deny();
+ break;
+ case UserRole.SPECIALIST:
+ where.specialist_id = userId;
+ break;
+ case UserRole.CONSULTANT: {
+ const client = await this.prismaService.user.findUnique({
+ where: { id: clientId },
+ select: { role: true, consultant_id: true },
});
+ if (
+ client?.role !== UserRole.CUSTOMER ||
+ client.consultant_id !== userId
+ )
+ deny();
+ // Repete a capability no próprio filtro de dados. Se o vínculo for
+ // revogado depois da checagem acima, findMany e count deixam de ler o
+ // cliente em vez de depender de uma autorização já obsoleta.
+ where.client = {
+ role: UserRole.CUSTOMER,
+ consultant_id: userId,
+ };
+ break;
}
+ default:
+ deny();
}
const pageNum = Number(page) || 1;
@@ -1923,9 +1945,7 @@ export class ProcessesService {
const [processes, count] = await Promise.all([
this.prismaService.process.findMany({
- where: {
- client_id: clientId,
- },
+ where,
include: {
client: true,
car: true,
@@ -1950,11 +1970,7 @@ export class ProcessesService {
skip,
take: perPageNum,
}),
- this.prismaService.process.count({
- where: {
- client_id: clientId,
- },
- }),
+ this.prismaService.process.count({ where }),
]);
const processEntities = processes.map((process: any) => ({
diff --git a/backend/src/features/specialists/specialists.service.spec.ts b/backend/src/features/specialists/specialists.service.spec.ts
index a7122f1..5cba96a 100644
--- a/backend/src/features/specialists/specialists.service.spec.ts
+++ b/backend/src/features/specialists/specialists.service.spec.ts
@@ -118,7 +118,6 @@ const publicSelect = {
id: true,
name: true,
surname: true,
- email: true,
speciality: true,
calendly_url: true,
calendly_connection: { select: { is_active: true } },
@@ -127,7 +126,6 @@ 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,
@@ -163,6 +161,9 @@ describe('SpecialistsService.findPublicProfile', () => {
where: { id: 'specialist-1', role: 'SPECIALIST' },
select: publicSelect,
});
+ expect(await service.findPublicProfile('specialist-1')).not.toHaveProperty(
+ 'email',
+ );
});
it.each([null, { is_active: false }])(
diff --git a/backend/src/features/specialists/specialists.service.ts b/backend/src/features/specialists/specialists.service.ts
index 1b69eff..7618561 100644
--- a/backend/src/features/specialists/specialists.service.ts
+++ b/backend/src/features/specialists/specialists.service.ts
@@ -22,7 +22,6 @@ const publicSpecialistSelect = {
id: true,
name: true,
surname: true,
- email: true,
speciality: true,
calendly_url: true,
calendly_connection: { select: { is_active: true } },
@@ -34,7 +33,7 @@ type PublicSpecialistRecord = Prisma.UserGetPayload<{
export type PublicSpecialistProfile = Pick<
PublicSpecialistRecord,
- 'id' | 'name' | 'surname' | 'email' | 'speciality' | 'calendly_url'
+ 'id' | 'name' | 'surname' | 'speciality' | 'calendly_url'
> & { calendly_scheduling_available: boolean };
function toPublicProfile(
@@ -44,7 +43,6 @@ function toPublicProfile(
id: specialist.id,
name: specialist.name,
surname: specialist.surname,
- email: specialist.email,
speciality: specialist.speciality,
calendly_url: specialist.calendly_url,
calendly_scheduling_available: isCalendlySchedulingAvailable({
diff --git a/frontend/src/pages/catalog/ProductPage.test.tsx b/frontend/src/pages/catalog/ProductPage.test.tsx
index 404e2cd..6e0a16a 100644
--- a/frontend/src/pages/catalog/ProductPage.test.tsx
+++ b/frontend/src/pages/catalog/ProductPage.test.tsx
@@ -651,6 +651,23 @@ describe("ProductPage scheduling", () => {
);
});
+ it("does not compose email when an EMAIL snapshot lacks owner-scoped contact", async () => {
+ vi.mocked(checkExistingAppointment).mockResolvedValue({
+ ...existingRequest,
+ exists: true,
+ specialist_contact_email: undefined,
+ });
+ render(page());
+
+ expect(
+ await screen.findByText("Aguardando confirmação do especialista"),
+ ).toBeTruthy();
+ expect(
+ screen.queryByRole("link", { name: "Abrir aplicativo de e-mail" }),
+ ).toBeNull();
+ expect(screen.queryByRole("link", { name: "Abrir no Gmail" })).toBeNull();
+ });
+
it.each([
{
...existingRequest,
diff --git a/frontend/src/services/appointments.service.test.ts b/frontend/src/services/appointments.service.test.ts
index d727f94..16263dd 100644
--- a/frontend/src/services/appointments.service.test.ts
+++ b/frontend/src/services/appointments.service.test.ts
@@ -99,6 +99,26 @@ describe("duplicate recovery", () => {
});
});
+ it("drops a contact field from non-EMAIL duplicate payloads", () => {
+ const calendlySnapshot = {
+ ...snapshot,
+ scheduling_method: "CALENDLY",
+ };
+ expect(
+ service.getActiveProcessSnapshot({
+ response: {
+ status: 409,
+ data: {
+ error: {
+ code: "ACTIVE_PROCESS_EXISTS",
+ details: { existing_request: calendlySnapshot },
+ },
+ },
+ },
+ }),
+ ).not.toHaveProperty("specialist_contact_email");
+ });
+
it.each([
{ response: { status: 409, data: { message: "Conflito" } } },
{ response: { status: 409, data: { error: { code: "CALENDLY_UNAVAILABLE", details: { existing_request: snapshot } } } } },
From 11cf86a7cfd289fc454d067e563b18358f645176 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 13:09:51 -0300
Subject: [PATCH 48/60] fix(frontend): preserve late Calendly completion
---
.../src/hooks/useCalendlyScheduling.test.tsx | 174 +++++++-
frontend/src/hooks/useCalendlyScheduling.ts | 382 +++++++++++-------
.../src/pages/catalog/ProductPage.test.tsx | 7 +-
frontend/src/pages/catalog/ProductPage.tsx | 2 +
.../src/pages/customer/ConsultoriaPage.tsx | 2 +
5 files changed, 420 insertions(+), 147 deletions(-)
diff --git a/frontend/src/hooks/useCalendlyScheduling.test.tsx b/frontend/src/hooks/useCalendlyScheduling.test.tsx
index 7f848bb..5aeb0f6 100644
--- a/frontend/src/hooks/useCalendlyScheduling.test.tsx
+++ b/frontend/src/hooks/useCalendlyScheduling.test.tsx
@@ -181,6 +181,10 @@ describe("useCalendlyScheduling active registration retry", () => {
result.current.openPopup("appointment-abandoned", "https://calendly.com/a"),
);
unmount();
+ expect(cancelPendingAppointment).not.toHaveBeenCalled();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(750);
+ });
await flushPromises();
expect(cancelPendingAppointment).toHaveBeenCalledTimes(1);
@@ -215,6 +219,102 @@ describe("useCalendlyScheduling active registration retry", () => {
expect(cancelPendingAppointment).not.toHaveBeenCalled();
});
+ it("aceita evento confiável que chega depois do close e antes do cancelamento", async () => {
+ vi.mocked(registerCalendlyScheduledEvent).mockResolvedValue({
+ appointment_id: "appointment-close-race",
+ calendly_sync_status: "SYNCED",
+ appointment_datetime: syncedStatus.appointment_datetime,
+ });
+ vi.mocked(getCalendlySyncStatus).mockResolvedValue({
+ ...syncedStatus,
+ appointment_id: "appointment-close-race",
+ });
+ const { result } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ );
+ act(() =>
+ result.current.openPopup(
+ "appointment-close-race",
+ "https://calendly.com/a",
+ ),
+ );
+ const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
+ .onEventScheduled!;
+
+ let close!: Promise;
+ act(() => {
+ close = result.current.closePopup();
+ });
+ expect(cancelPendingAppointment).not.toHaveBeenCalled();
+ await act(async () => {
+ await listener(scheduledEvent());
+ await vi.runAllTimersAsync();
+ await close;
+ });
+
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledOnce();
+ expect(cancelPendingAppointment).not.toHaveBeenCalled();
+ });
+
+ it("mantém listener seguro na grace após unmount e deixa o webhook concluir", async () => {
+ const { result, unmount } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ );
+ act(() =>
+ result.current.openPopup(
+ "appointment-unmount-race",
+ "https://calendly.com/a",
+ ),
+ );
+
+ unmount();
+ act(() => {
+ window.dispatchEvent(scheduledEvent());
+ });
+ await act(async () => {
+ await vi.runAllTimersAsync();
+ });
+
+ expect(cancelPendingAppointment).not.toHaveBeenCalled();
+ expect(registerCalendlyScheduledEvent).not.toHaveBeenCalled();
+ expect(navigate).not.toHaveBeenCalled();
+ });
+
+ it("não deixa origem ou source incorretos suprimirem cancelamento na grace", async () => {
+ const foreignFrame = document.createElement("iframe");
+ document.body.appendChild(foreignFrame);
+ const { result, unmount } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ );
+ act(() =>
+ result.current.openPopup(
+ "appointment-forged-close",
+ "https://calendly.com/a",
+ ),
+ );
+
+ unmount();
+ act(() => {
+ window.dispatchEvent(
+ scheduledEvent({
+ source: foreignFrame.contentWindow,
+ origin: "https://calendly.com",
+ }),
+ );
+ window.dispatchEvent(
+ scheduledEvent({ origin: "https://calendly.com.evil.test" }),
+ );
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(750);
+ });
+
+ expect(cancelPendingAppointment).toHaveBeenCalledTimes(1);
+ expect(cancelPendingAppointment).toHaveBeenCalledWith(
+ "appointment-forged-close",
+ );
+ });
+
it("não cancela no unmount depois que um evento confiável foi recebido", async () => {
let resolveRegistration!: (value: {
appointment_id: string;
@@ -261,8 +361,13 @@ describe("useCalendlyScheduling active registration retry", () => {
result.current.openPopup("appointment-once", "https://calendly.com/a"),
);
+ let close!: Promise;
+ act(() => {
+ close = result.current.closePopup();
+ });
await act(async () => {
- await result.current.closePopup();
+ await vi.advanceTimersByTimeAsync(750);
+ await close;
});
unmount();
await flushPromises();
@@ -410,6 +515,73 @@ describe("useCalendlyScheduling active registration retry", () => {
expect(getCalendlySyncStatus).not.toHaveBeenCalled();
});
+ it("não deixa B adotar o iframe de A antes de capturar seu próprio source", async () => {
+ const { result } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ );
+ act(() => result.current.openPopup("appointment-a", "https://calendly.com/a"));
+ const listenerBeforeOpeningB = vi.mocked(useCalendlyEventListener).mock.calls.at(
+ -1,
+ )![0].onEventScheduled!;
+ const sourceA = document.querySelector(
+ ".calendly-popup-content iframe",
+ )!.contentWindow;
+
+ act(() => {
+ result.current.openPopup("appointment-b", "https://calendly.com/b");
+ void listenerBeforeOpeningB(
+ scheduledEvent({
+ source: sourceA,
+ eventUri: "https://api.calendly.com/scheduled_events/event-a",
+ inviteeUri:
+ "https://api.calendly.com/scheduled_events/event-a/invitees/invitee-a",
+ }),
+ );
+ });
+ await flushPromises();
+
+ expect(registerCalendlyScheduledEvent).not.toHaveBeenCalled();
+ expect(getCalendlySyncStatus).not.toHaveBeenCalled();
+ });
+
+ it("captura o novo iframe de B quando a URL do Calendly não muda", async () => {
+ vi.mocked(registerCalendlyScheduledEvent).mockResolvedValue({
+ appointment_id: "appointment-b",
+ calendly_sync_status: "SYNCED",
+ appointment_datetime: syncedStatus.appointment_datetime,
+ });
+ vi.mocked(getCalendlySyncStatus).mockResolvedValue({
+ ...syncedStatus,
+ appointment_id: "appointment-b",
+ });
+ const { result } = renderHook(() =>
+ useCalendlyScheduling({ successRedirectMessage: "ok" }),
+ );
+ act(() =>
+ result.current.openPopup("appointment-a", "https://calendly.com/same"),
+ );
+ const oldFrame = document.querySelector(
+ ".calendly-popup-content iframe",
+ )!;
+ const replacement = document.createElement("iframe");
+ oldFrame.replaceWith(replacement);
+
+ act(() =>
+ result.current.openPopup("appointment-b", "https://calendly.com/same"),
+ );
+ const listener = vi.mocked(useCalendlyEventListener).mock.calls.at(-1)![0]
+ .onEventScheduled!;
+ await act(async () => {
+ await listener(scheduledEvent({ source: replacement.contentWindow }));
+ });
+
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledOnce();
+ expect(registerCalendlyScheduledEvent).toHaveBeenCalledWith(
+ "appointment-b",
+ expect.objectContaining({ event_uri: payload.event_uri }),
+ );
+ });
+
it.each([
"https://evilcalendly.com",
"https://calendly.com.evil.test",
diff --git a/frontend/src/hooks/useCalendlyScheduling.ts b/frontend/src/hooks/useCalendlyScheduling.ts
index 153e94b..8073a8b 100644
--- a/frontend/src/hooks/useCalendlyScheduling.ts
+++ b/frontend/src/hooks/useCalendlyScheduling.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useCalendlyEventListener } from "react-calendly";
import {
@@ -22,31 +22,93 @@ export type CalendlySyncState =
| "error";
interface UseCalendlySchedulingOptions {
- /** Mensagem exibida na página de destino (Meus Processos) após o redirect de sucesso. */
successRedirectMessage: string;
- /** Efeito colateral extra quando a sincronização confirma o agendamento (ex: atualizar estado local da página). */
onSynced?: (status: CalendlySyncStatus) => void;
}
type PendingCalendlyAttempt = {
appointmentId: string;
- phase: "waiting_event" | "event_received" | "cancelling" | "settled";
+ modalUrl: string;
+ phase:
+ | "waiting_event"
+ | "closing_grace"
+ | "event_received"
+ | "cancelling"
+ | "settled";
+ frameSource: MessageEventSource | null;
+ rawListener: ((event: MessageEvent) => void) | null;
+ graceTimer: ReturnType | null;
+ gracePromise: Promise | null;
+ resolveGrace: (() => void) | null;
};
+const ABANDONMENT_GRACE_MS = 750;
+
+function currentCalendlyFrameSource(): MessageEventSource | null {
+ return (
+ document.querySelector(
+ ".calendly-popup-content iframe",
+ )?.contentWindow ?? null
+ );
+}
+
+function trustedScheduledPayload(
+ event: MessageEvent,
+ attempt: PendingCalendlyAttempt,
+): RegisterCalendlyScheduledPayload | null {
+ if (
+ event.data?.event !== "calendly.event_scheduled" ||
+ !isTrustedCalendlyOrigin(attempt.modalUrl) ||
+ !isTrustedCalendlyOrigin(event.origin) ||
+ !attempt.frameSource ||
+ event.source !== attempt.frameSource
+ ) {
+ return null;
+ }
+
+ const eventUri = event.data?.payload?.event?.uri;
+ const inviteeUri = event.data?.payload?.invitee?.uri;
+ if (
+ typeof eventUri !== "string" ||
+ !eventUri ||
+ typeof inviteeUri !== "string" ||
+ !inviteeUri
+ ) {
+ return null;
+ }
+
+ return {
+ event_uri: eventUri,
+ invitee_uri: inviteeUri,
+ client_event: "calendly.event_scheduled",
+ client_observed_at: new Date().toISOString(),
+ };
+}
+
+function removeAttemptListener(attempt: PendingCalendlyAttempt) {
+ if (attempt.rawListener) {
+ window.removeEventListener("message", attempt.rawListener);
+ attempt.rawListener = null;
+ }
+}
+
+function resolveGraceWindow(attempt: PendingCalendlyAttempt) {
+ if (attempt.graceTimer) {
+ clearTimeout(attempt.graceTimer);
+ attempt.graceTimer = null;
+ }
+ const resolve = attempt.resolveGrace;
+ attempt.resolveGrace = null;
+ attempt.gracePromise = null;
+ resolve?.();
+}
+
/**
- * useCalendlyScheduling
- *
- * Ciclo de vida compartilhado do popup do Calendly: abrir, escutar o evento de
- * agendamento (`calendly.event_scheduled`), registrar no backend, sincronizar
- * status (com polling) e navegar para "Meus Processos" ao concluir.
- *
- * Também cobre o cleanup de abandono: se o usuário fechar o popup sem o evento
- * ter sido confirmado, cancela o agendamento PENDING criado para evitar
- * registros órfãos no banco.
- *
- * Não cobre: criação do agendamento (payloads diferentes por página) nem
- * verificações prévias específicas de cada página — isso continua em cada
- * página, que chama `openPopup` já com o `pendingAppointment.id` em mãos.
+ * Owns the Calendly popup lifecycle for a customer-created pending request.
+ * A short close/unmount grace keeps the iframe's WindowProxy trusted long
+ * enough to observe an event already queued by Calendly before deleting the
+ * PENDING request. This is best effort for SPA lifecycle changes; a hard page
+ * unload still relies on the backend webhook and transactional status checks.
*/
export function useCalendlyScheduling({
successRedirectMessage,
@@ -55,34 +117,65 @@ export function useCalendlyScheduling({
const navigate = useNavigate();
const [isModalOpen, setIsModalOpen] = useState(false);
const [modalUrl, setModalUrl] = useState(null);
+ const [modalKey, setModalKey] = useState(null);
const [syncState, setSyncState] = useState("idle");
const [syncMessage, setSyncMessage] = useState("");
const pendingAttemptRef = useRef(null);
const mountedRef = useRef(false);
const syncAbortRef = useRef(null);
const navigateTimerRef = useRef | null>(null);
+ const modalSequenceRef = useRef(0);
+ const receiveScheduledEventRef = useRef<
+ (attempt: PendingCalendlyAttempt, event: MessageEvent) => Promise
+ >(async () => {});
- const abandonAttempt = useCallback(
+ const beginAbandonment = useCallback(
(attempt: PendingCalendlyAttempt, resetVisibleState: boolean) => {
+ if (attempt.phase === "closing_grace" && attempt.gracePromise) {
+ return attempt.gracePromise;
+ }
if (attempt.phase !== "waiting_event") return Promise.resolve();
- // Claim the cancellation synchronously. A modal close, route unmount and
- // StrictMode cleanup can all observe the same attempt, but only the first
- // caller is allowed to issue the DELETE.
- attempt.phase = "cancelling";
- return cancelPendingAppointment(attempt.appointmentId)
- .catch((err) => {
- console.error("Erro ao cancelar agendamento pendente", err);
- })
- .finally(() => {
- if (pendingAttemptRef.current === attempt) {
- pendingAttemptRef.current = null;
- }
- if (resetVisibleState && mountedRef.current) {
- setSyncState("idle");
- setSyncMessage("");
- }
- });
+ attempt.frameSource ??= currentCalendlyFrameSource();
+ attempt.phase = "closing_grace";
+ if (attempt.frameSource && !attempt.rawListener) {
+ attempt.rawListener = (event) => {
+ void receiveScheduledEventRef.current(attempt, event);
+ };
+ window.addEventListener("message", attempt.rawListener);
+ }
+ if (resetVisibleState && mountedRef.current) {
+ setSyncState("idle");
+ setSyncMessage("");
+ }
+
+ attempt.gracePromise = new Promise((resolve) => {
+ attempt.resolveGrace = resolve;
+ });
+ attempt.graceTimer = setTimeout(() => {
+ attempt.graceTimer = null;
+ if (attempt.phase !== "closing_grace") {
+ resolveGraceWindow(attempt);
+ return;
+ }
+
+ // Claim before the HTTP call so close, unmount and StrictMode cleanup
+ // cannot issue duplicate cancellation requests.
+ attempt.phase = "cancelling";
+ removeAttemptListener(attempt);
+ void cancelPendingAppointment(attempt.appointmentId)
+ .catch((err) => {
+ console.error("Erro ao cancelar agendamento pendente", err);
+ })
+ .finally(() => {
+ if (pendingAttemptRef.current === attempt) {
+ pendingAttemptRef.current = null;
+ }
+ resolveGraceWindow(attempt);
+ });
+ }, ABANDONMENT_GRACE_MS);
+
+ return attempt.gracePromise;
},
[],
);
@@ -92,137 +185,142 @@ export function useCalendlyScheduling({
return () => {
mountedRef.current = false;
const attempt = pendingAttemptRef.current;
- if (attempt) void abandonAttempt(attempt, false);
+ if (attempt) void beginAbandonment(attempt, false);
syncAbortRef.current?.abort();
if (navigateTimerRef.current) clearTimeout(navigateTimerRef.current);
};
- }, [abandonAttempt]);
+ }, [beginAbandonment]);
- useCalendlyEventListener({
- onEventScheduled: async (event) => {
- const attempt = pendingAttemptRef.current;
- if (!attempt || attempt.phase !== "waiting_event") return;
-
- const currentFrame = document.querySelector(
- ".calendly-popup-content iframe",
- );
- if (
- !modalUrl ||
- !isTrustedCalendlyOrigin(modalUrl) ||
- !isTrustedCalendlyOrigin(event.origin) ||
- !currentFrame?.contentWindow ||
- event.source !== currentFrame.contentWindow
- ) {
- return;
- }
-
- const payload = event.data?.payload;
- const eventUri = payload?.event?.uri;
- const inviteeUri = payload?.invitee?.uri;
+ useLayoutEffect(() => {
+ if (!isModalOpen) return;
+ const attempt = pendingAttemptRef.current;
+ if (attempt && attempt.phase === "waiting_event") {
+ attempt.frameSource ??= currentCalendlyFrameSource();
+ }
+ }, [isModalOpen, modalUrl, modalKey]);
- if (!eventUri || !inviteeUri) {
- setSyncState("error");
- setSyncMessage(
- "Não foi possível capturar os dados do agendamento. Verifique seus processos para confirmar.",
- );
- return;
- }
+ const synchronizeScheduledEvent = async (
+ attempt: PendingCalendlyAttempt,
+ registrationPayload: RegisterCalendlyScheduledPayload,
+ ) => {
+ syncAbortRef.current?.abort();
+ const syncController = new AbortController();
+ syncAbortRef.current = syncController;
- // Calendly já disparou `event_scheduled` com um payload válido — isso É
- // a fonte da verdade de que o usuário concluiu o agendamento. Marcar
- // como confirmado AQUI (síncrono, antes do await de rede abaixo) evita
- // a janela de corrida em que o usuário fecha o popup entre o evento do
- // Calendly e a resposta do nosso backend — nesse intervalo o registro
- // NÃO pode ser tratado como abandono e cancelado.
- attempt.phase = "event_received";
- const registrationPayload: RegisterCalendlyScheduledPayload = {
- event_uri: eventUri,
- invitee_uri: inviteeUri,
- client_event: "calendly.event_scheduled",
- client_observed_at: new Date().toISOString(),
- };
- syncAbortRef.current?.abort();
- const syncController = new AbortController();
- syncAbortRef.current = syncController;
+ try {
+ setSyncState("syncing");
+ setSyncMessage("Sincronizando seu agendamento...");
- try {
- setSyncState("syncing");
- setSyncMessage("Sincronizando seu agendamento...");
+ const status = await synchronizeCalendlyRegistration(
+ attempt.appointmentId,
+ registrationPayload,
+ { signal: syncController.signal },
+ );
+ if (!mountedRef.current || syncController.signal.aborted || !status) return;
- const status = await synchronizeCalendlyRegistration(
- attempt.appointmentId,
- registrationPayload,
- { signal: syncController.signal },
- );
- if (!mountedRef.current || syncController.signal.aborted || !status) return;
-
- attempt.phase = "settled";
- setIsModalOpen(false);
- if (isCalendlySyncComplete(status)) {
- onSynced?.(status);
- setSyncState("done");
- setSyncMessage(
- "Agendamento recebido! Você pode acompanhar os detalhes em Meus Processos.",
- );
- navigateTimerRef.current = setTimeout(() => {
- if (!mountedRef.current) return;
- navigate("/customer/processes", {
- state: { message: successRedirectMessage },
- });
- }, 900);
- } else if (isCalendlySyncTerminalFailure(status)) {
- setSyncState("error");
- setSyncMessage(
- status.status === "CANCELLED"
- ? "O agendamento foi cancelado no Calendly. Verifique Meus Processos antes de tentar novamente."
- : "Não foi possível confirmar o horário no Calendly. Verifique Meus Processos ou tente novamente.",
- );
- } else {
- setSyncState("pending");
- setSyncMessage(
- "Solicitação registrada. Estamos finalizando a sincronização do horário com o calendário.",
- );
- }
- } catch (err) {
- // O agendamento já aconteceu de verdade no Calendly (a tentativa já
- // recebeu o evento) — só a nossa sincronização falhou. Não deixar o usuário
- // preso num popup fechado/stale: fecha e manda pra Meus Processos,
- // igual ao fluxo de sucesso, só que com aviso de que pode faltar
- // atualizar a página.
- if (!mountedRef.current || syncController.signal.aborted) return;
- console.error("Erro ao sincronizar evento do Calendly:", err);
- setSyncState("error");
+ attempt.phase = "settled";
+ setIsModalOpen(false);
+ if (isCalendlySyncComplete(status)) {
+ onSynced?.(status);
+ setSyncState("done");
setSyncMessage(
- "Agendamento confirmado no Calendly, mas houve falha ao sincronizar com a plataforma. Redirecionando para Meus Processos...",
+ "Agendamento recebido! Você pode acompanhar os detalhes em Meus Processos.",
);
- setIsModalOpen(false);
navigateTimerRef.current = setTimeout(() => {
if (!mountedRef.current) return;
navigate("/customer/processes", {
- state: {
- message:
- "Agendamento confirmado no Calendly! Se o horário não aparecer imediatamente em Meus Processos, atualize a página em instantes.",
- },
+ state: { message: successRedirectMessage },
});
- }, 1000);
+ }, 900);
+ } else if (isCalendlySyncTerminalFailure(status)) {
+ setSyncState("error");
+ setSyncMessage(
+ status.status === "CANCELLED"
+ ? "O agendamento foi cancelado no Calendly. Verifique Meus Processos antes de tentar novamente."
+ : "Não foi possível confirmar o horário no Calendly. Verifique Meus Processos ou tente novamente.",
+ );
+ } else {
+ setSyncState("pending");
+ setSyncMessage(
+ "Solicitação registrada. Estamos finalizando a sincronização do horário com o calendário.",
+ );
}
+ } catch (err) {
+ if (!mountedRef.current || syncController.signal.aborted) return;
+ console.error("Erro ao sincronizar evento do Calendly:", err);
+ setSyncState("error");
+ setSyncMessage(
+ "Agendamento confirmado no Calendly, mas houve falha ao sincronizar com a plataforma. Redirecionando para Meus Processos...",
+ );
+ setIsModalOpen(false);
+ navigateTimerRef.current = setTimeout(() => {
+ if (!mountedRef.current) return;
+ navigate("/customer/processes", {
+ state: {
+ message:
+ "Agendamento confirmado no Calendly! Se o horário não aparecer imediatamente em Meus Processos, atualize a página em instantes.",
+ },
+ });
+ }, 1000);
+ }
+ };
+
+ const receiveScheduledEvent = async (
+ attempt: PendingCalendlyAttempt,
+ event: MessageEvent,
+ ) => {
+ if (
+ attempt.phase !== "waiting_event" &&
+ attempt.phase !== "closing_grace"
+ ) {
+ return;
+ }
+ const registrationPayload = trustedScheduledPayload(event, attempt);
+ if (!registrationPayload) return;
+
+ // Claim synchronously before any await: a close/unmount queued immediately
+ // after this event can no longer delete the real Calendly booking request.
+ attempt.phase = "event_received";
+ removeAttemptListener(attempt);
+ resolveGraceWindow(attempt);
+
+ // After unmount (or for an obsolete A→B popup), the trusted event only
+ // suppresses deletion. Calendly's webhook owns eventual synchronization.
+ if (!mountedRef.current || pendingAttemptRef.current !== attempt) return;
+ await synchronizeScheduledEvent(attempt, registrationPayload);
+ };
+ receiveScheduledEventRef.current = receiveScheduledEvent;
+
+ useCalendlyEventListener({
+ onEventScheduled: (event) => {
+ const attempt = pendingAttemptRef.current;
+ if (!attempt) return;
+ return receiveScheduledEvent(attempt, event);
},
});
- /** Seta o agendamento pendente em foco, abre o popup do Calendly. */
const openPopup = (appointmentId: string, calendlyUrl: string) => {
const previousAttempt = pendingAttemptRef.current;
- if (previousAttempt) void abandonAttempt(previousAttempt, false);
+ if (previousAttempt) void beginAbandonment(previousAttempt, false);
syncAbortRef.current?.abort();
if (navigateTimerRef.current) clearTimeout(navigateTimerRef.current);
const normalizedUrl = /^https?:\/\//i.test(calendlyUrl)
? calendlyUrl
: `https://${calendlyUrl}`;
- pendingAttemptRef.current = {
+ const attempt: PendingCalendlyAttempt = {
appointmentId,
+ modalUrl: normalizedUrl,
phase: "waiting_event",
+ frameSource: null,
+ rawListener: null,
+ graceTimer: null,
+ gracePromise: null,
+ resolveGrace: null,
};
+ pendingAttemptRef.current = attempt;
setModalUrl(normalizedUrl);
+ modalSequenceRef.current += 1;
+ setModalKey(`${appointmentId}:${modalSequenceRef.current}`);
setSyncState("waiting_event");
setSyncMessage(
"Conclua seu agendamento no Calendly para sincronizar automaticamente com a plataforma.",
@@ -230,20 +328,16 @@ export function useCalendlyScheduling({
setIsModalOpen(true);
};
- /**
- * Fecha o popup. Se o usuário abandonou o Calendly sem confirmar o
- * agendamento (`onEventScheduled` nunca disparou), cancela o agendamento
- * PENDING para não deixar registro órfão no banco.
- */
- const closePopup = async () => {
+ const closePopup = () => {
setIsModalOpen(false);
const attempt = pendingAttemptRef.current;
- if (attempt) await abandonAttempt(attempt, true);
+ return attempt ? beginAbandonment(attempt, true) : Promise.resolve();
};
return {
isModalOpen,
modalUrl,
+ modalKey,
syncState,
syncMessage,
openPopup,
diff --git a/frontend/src/pages/catalog/ProductPage.test.tsx b/frontend/src/pages/catalog/ProductPage.test.tsx
index 6e0a16a..dedad5d 100644
--- a/frontend/src/pages/catalog/ProductPage.test.tsx
+++ b/frontend/src/pages/catalog/ProductPage.test.tsx
@@ -653,9 +653,12 @@ describe("ProductPage scheduling", () => {
it("does not compose email when an EMAIL snapshot lacks owner-scoped contact", async () => {
vi.mocked(checkExistingAppointment).mockResolvedValue({
- ...existingRequest,
exists: true,
- specialist_contact_email: undefined,
+ appointment_id: "appointment-no-contact",
+ appointment_status: "PENDING",
+ scheduling_method: "EMAIL",
+ appointment_datetime: appointment.appointment_datetime!,
+ process_id: "process-1",
});
render(page());
diff --git a/frontend/src/pages/catalog/ProductPage.tsx b/frontend/src/pages/catalog/ProductPage.tsx
index e3d0e3b..895b599 100644
--- a/frontend/src/pages/catalog/ProductPage.tsx
+++ b/frontend/src/pages/catalog/ProductPage.tsx
@@ -158,6 +158,7 @@ export default function ProductPage() {
const {
isModalOpen: isCalendlyModalOpen,
modalUrl: calendlyModalUrl,
+ modalKey: calendlyModalKey,
syncState: calendlySyncState,
syncMessage: calendlySyncMessage,
openPopup,
@@ -655,6 +656,7 @@ export default function ProductPage() {
)}
{calendlyModalUrl && isCalendlyModalOpen && (
Date: Wed, 14 Oct 2026 13:16:40 -0300
Subject: [PATCH 49/60] fix(processes): restore negotiation monetary snapshot
---
.../processes/processes.service.spec.ts | 154 ++++++++++++++++--
.../features/processes/processes.service.ts | 100 ++++++++++--
2 files changed, 224 insertions(+), 30 deletions(-)
diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts
index e885934..6181d40 100644
--- a/backend/src/features/processes/processes.service.spec.ts
+++ b/backend/src/features/processes/processes.service.spec.ts
@@ -755,7 +755,7 @@ describe('ProcessesService — snapshot de entrada na negociação', () => {
};
}
- it('bloqueia a transição manual para negociação, reservada ao fluxo canônico', async () => {
+ it('adquire agenda → produto e congela o snapshot na entrada em negociação', async () => {
const processUpdate = jest.fn().mockImplementation(({ data }) =>
Promise.resolve({
...baseProcess(),
@@ -781,21 +781,115 @@ 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,
+ );
+
+ 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(processUpdate).not.toHaveBeenCalled();
+ expect(tx.$queryRaw.mock.calls.map((call) => call[1])).toEqual([
+ 'appointment-schedule:specialist-1',
+ 'product-money:CAR:product-1',
+ ]);
+ // leitura inicial, releituras após agenda/produto e leitura final do CAS
+ expect(tx.process.findUniqueOrThrow).toHaveBeenCalledTimes(4);
+ });
+
+ it('conflita se o especialista mudar depois do lock de agenda', async () => {
+ const originalProcess = baseProcess();
+ const movedProcess = baseProcess({ specialist_id: 'specialist-2' });
+ const processUpdateMany = jest.fn();
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ process: {
+ findUniqueOrThrow: jest
+ .fn()
+ .mockResolvedValueOnce(originalProcess)
+ .mockResolvedValueOnce(movedProcess),
+ updateMany: processUpdateMany,
+ },
+ processStatusHistory: {
+ create: jest.fn(),
+ findMany: jest.fn(),
+ },
+ };
+ const prisma = {
+ $transaction: jest.fn(async (callback) => callback(tx)),
+ } as any;
+ const service = new ProcessesService(prisma, {} as any);
+
await expect(
service.update(
'process-1',
- { status: ProcessStatus.NEGOTIATION, notes: 'Negociando' },
+ { status: ProcessStatus.NEGOTIATION },
'admin-1',
UserRole.ADMIN,
),
- ).rejects.toThrow(BadRequestException);
+ ).rejects.toBeInstanceOf(ConflictException);
+ expect(tx.$queryRaw.mock.calls.map((call) => call[1])).toEqual([
+ 'appointment-schedule:specialist-1',
+ ]);
expect(processUpdateMany).not.toHaveBeenCalled();
- expect(processUpdate).not.toHaveBeenCalled();
- expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
- expect(tx.$queryRaw.mock.calls[0][1]).toBe(
+ });
+
+ it('conflita se o produto mudar depois do lock monetário', async () => {
+ const originalProcess = baseProcess();
+ const movedProcess = baseProcess({
+ car_id: 'product-2',
+ car: { ...usdProduct, id: 'product-2' },
+ });
+ const processUpdateMany = jest.fn();
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ process: {
+ findUniqueOrThrow: jest
+ .fn()
+ .mockResolvedValueOnce(originalProcess)
+ .mockResolvedValueOnce(originalProcess)
+ .mockResolvedValueOnce(movedProcess),
+ updateMany: processUpdateMany,
+ },
+ processStatusHistory: {
+ create: jest.fn(),
+ findMany: jest.fn(),
+ },
+ };
+ const prisma = {
+ $transaction: jest.fn(async (callback) => callback(tx)),
+ } as any;
+ const service = new ProcessesService(prisma, {} as any);
+
+ await expect(
+ service.update(
+ 'process-1',
+ { status: ProcessStatus.NEGOTIATION },
+ 'admin-1',
+ UserRole.ADMIN,
+ ),
+ ).rejects.toBeInstanceOf(ConflictException);
+
+ expect(tx.$queryRaw.mock.calls.map((call) => call[1])).toEqual([
'appointment-schedule:specialist-1',
- );
+ 'product-money:CAR:product-1',
+ ]);
+ expect(processUpdateMany).not.toHaveBeenCalled();
});
it('returns conflict and creates no history when the manual transition loses its CAS claim', async () => {
@@ -2249,8 +2343,19 @@ describe('ProcessesService — autorização centralizada de processos', () => {
expect(processUpdateMany).not.toHaveBeenCalled();
});
- it('especialista atribuído não pode burlar a confirmação canônica para entrar em NEGOTIATION', async () => {
- const { service, processUpdateMany } = updateService();
+ it('especialista atribuído congela o produto ao entrar em NEGOTIATION', async () => {
+ const process = protectedProcess({
+ product_type: ProductType.CAR,
+ car_id: productId,
+ negotiation_currency: null,
+ negotiation_product_value: null,
+ car: {
+ id: productId,
+ valor: new Prisma.Decimal('120000.00'),
+ currency: ProductCurrency.USD,
+ },
+ });
+ const { service, processUpdateMany } = updateService(process);
await expect(
service.update(
@@ -2259,13 +2364,32 @@ describe('ProcessesService — autorização centralizada de processos', () => {
assignedSpecialistId,
UserRole.SPECIALIST,
),
- ).rejects.toThrow(BadRequestException);
+ ).resolves.toBeDefined();
- expect(processUpdateMany).not.toHaveBeenCalled();
+ expect(processUpdateMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ status: ProcessStatus.NEGOTIATION,
+ negotiation_currency: ProductCurrency.USD,
+ negotiation_product_value: new Prisma.Decimal('120000.00'),
+ }),
+ }),
+ );
});
- it('OFFICE da empresa do cliente não pode burlar a confirmação canônica', async () => {
- const { service, processUpdateMany } = updateService();
+ it('OFFICE da empresa do cliente usa a mesma entrada serializada em NEGOTIATION', async () => {
+ const process = protectedProcess({
+ product_type: ProductType.CAR,
+ car_id: productId,
+ negotiation_currency: null,
+ negotiation_product_value: null,
+ car: {
+ id: productId,
+ valor: new Prisma.Decimal('120000.00'),
+ currency: ProductCurrency.USD,
+ },
+ });
+ const { service, processUpdateMany } = updateService(process);
await expect(
service.update(
@@ -2275,9 +2399,9 @@ describe('ProcessesService — autorização centralizada de processos', () => {
UserRole.OFFICE,
clientCompanyId,
),
- ).rejects.toThrow(BadRequestException);
+ ).resolves.toBeDefined();
- expect(processUpdateMany).not.toHaveBeenCalled();
+ expect(processUpdateMany).toHaveBeenCalledTimes(1);
});
it('não promove consultoria sem produto/snapshot de NEGOTIATION para DOCUMENTATION', async () => {
diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts
index 1c6d00f..bb138d7 100644
--- a/backend/src/features/processes/processes.service.ts
+++ b/backend/src/features/processes/processes.service.ts
@@ -30,7 +30,10 @@ 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 } from '../products/product-monetary-lock';
+import {
+ acquireProductMonetaryLock,
+ lockNegotiationProductMoney,
+} from '../products/product-monetary-lock';
import { validateSpecialistProductAssociation } from '../products/product-association-validator';
import {
acquireActiveProcessDedupLock,
@@ -71,7 +74,7 @@ const PROCESS_STATUS_TRANSITIONS: Record<
ProcessStatus,
readonly ProcessStatus[]
> = {
- [ProcessStatus.SCHEDULING]: [],
+ [ProcessStatus.SCHEDULING]: [ProcessStatus.NEGOTIATION],
[ProcessStatus.NEGOTIATION]: [ProcessStatus.DOCUMENTATION],
[ProcessStatus.PROCESSING_CONTRACT]: [],
[ProcessStatus.DOCUMENTATION]: [],
@@ -184,6 +187,18 @@ export class ProcessesService {
}
}
+ private throwStatusTransitionConflict(processId: string): never {
+ throw new ConflictException({
+ success: false,
+ error: {
+ code: 'PROCESS_STATUS_TRANSITION_CONFLICT',
+ message:
+ 'O processo foi alterado por outra operação. Recarregue e tente novamente.',
+ details: { process_id: processId },
+ },
+ });
+ }
+
/**
* Cria um objeto "product" de acordo com o processo enviado
*
@@ -1274,10 +1289,8 @@ export class ProcessesService {
'update-status',
);
- await acquireSpecialistScheduleLock(
- tx,
- existingProcess.specialist_id,
- );
+ const lockedSpecialistId = existingProcess.specialist_id;
+ await acquireSpecialistScheduleLock(tx, lockedSpecialistId);
existingProcess = await tx.process.findUniqueOrThrow({
where: { id: processId },
include: {
@@ -1299,6 +1312,9 @@ export class ProcessesService {
aircraft: true,
},
});
+ if (existingProcess.specialist_id !== lockedSpecialistId) {
+ this.throwStatusTransitionConflict(processId);
+ }
this.assertProcessAccess(
existingProcess,
{
@@ -1323,12 +1339,74 @@ export class ProcessesService {
updateProcessDto.status,
);
+ if (updateProcessDto.status === ProcessStatus.NEGOTIATION) {
+ // Ordem global: agenda → produto → deduplicação. O lock da agenda
+ // já foi adquirido antes da releitura acima; congelar o preço só
+ // depois dele mantém a ordem compatível com confirmPending.
+ const lockedProductType = existingProcess.product_type;
+ const lockedProductId = this.getProductId(existingProcess);
+ 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.product_type !== lockedProductType ||
+ this.getProductId(existingProcess) !== lockedProductId
+ ) {
+ this.throwStatusTransitionConflict(processId);
+ }
+ this.assertProcessAccess(
+ existingProcess,
+ {
+ id: callerId ?? '',
+ role: callerRole as UserRole,
+ companyId: callerCompanyId,
+ },
+ 'update-status',
+ );
+ if (existingProcess.status === updateProcessDto.status) {
+ throw new BadRequestException();
+ }
+ this.assertStatusTransition(
+ existingProcess.status,
+ updateProcessDto.status,
+ );
+ this.assertManualStatusPreconditions(
+ existingProcess,
+ updateProcessDto.status,
+ );
+ }
+
+ 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,
@@ -1338,15 +1416,7 @@ export class ProcessesService {
});
if (claim.count !== 1) {
- throw new ConflictException({
- success: false,
- error: {
- code: 'PROCESS_STATUS_TRANSITION_CONFLICT',
- message:
- 'O processo foi alterado por outra operação. Recarregue e tente novamente.',
- details: { process_id: processId },
- },
- });
+ this.throwStatusTransitionConflict(processId);
}
const process = await tx.process.findUniqueOrThrow({
From 277bf18007b8537caa8a7fd83f7f28bc01fa1830 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Wed, 14 Oct 2026 13:18:48 -0300
Subject: [PATCH 50/60] test(e2e): cover scoped specialist email
---
backend/test/email-scheduling.e2e-spec.ts | 51 +++++++++++++++++------
1 file changed, 38 insertions(+), 13 deletions(-)
diff --git a/backend/test/email-scheduling.e2e-spec.ts b/backend/test/email-scheduling.e2e-spec.ts
index cf15aae..17e59f2 100644
--- a/backend/test/email-scheduling.e2e-spec.ts
+++ b/backend/test/email-scheduling.e2e-spec.ts
@@ -24,6 +24,7 @@ const checkKeys = [
'appointment_status',
'scheduling_method',
'appointment_datetime',
+ 'specialist_contact_email',
];
// A dedicated URL opts in to the real PostgreSQL gate. Ordinary e2e discovery
@@ -380,6 +381,16 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => {
}
}
+ function assertOwnerScopedSpecialistEmail(value: unknown) {
+ assertNoPrivateFields(value);
+ const serialized = JSON.stringify(value);
+ expect(serialized.includes(config.credentials.specialist.email)).toBe(true);
+ expect(serialized.includes(config.credentials.outsider.email)).toBe(false);
+ for (const user of fixture.users) {
+ expect(serialized.includes(user.phone)).toBe(false);
+ }
+ }
+
async function assertStoredState(
productId: string,
processId: string,
@@ -433,7 +444,6 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => {
'id',
'name',
'surname',
- 'email',
'speciality',
'calendly_url',
'calendly_scheduling_available',
@@ -441,10 +451,10 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => {
);
expect(profile.body).toMatchObject({
id: fixture.users[1].id,
- email: config.credentials.specialist.email,
calendly_url: null,
calendly_scheduling_available: false,
});
+ expect(profile.body).not.toHaveProperty('email');
assertNoPrivateFields(profile.body);
expect(profile.body).not.toHaveProperty('phone');
await request(app!.getHttpServer())
@@ -517,6 +527,23 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => {
}
});
+ it('does not expose specialist contact through an unavailable CALENDLY path', async () => {
+ const { appointment_datetime: _date, ...withoutDate } = pendingBody(
+ fixture.cars[0].id,
+ );
+ 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');
+ expect(JSON.stringify(calendly.body)).not.toContain(
+ 'specialist_contact_email',
+ );
+ assertNoContacts(calendly.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;
@@ -548,13 +575,6 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => {
.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 },
@@ -588,8 +608,9 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => {
client: { id: fixture.users[0].id },
specialist: { id: fixture.users[1].id },
product: { id: car.id },
+ specialist_contact_email: config.credentials.specialist.email,
});
- assertNoPrivateFields(response.body);
+ assertOwnerScopedSpecialistEmail(response.body);
created.push({
appointmentId: response.body.data.id,
processId: response.body.data.process_id,
@@ -615,8 +636,9 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => {
appointment_status: 'PENDING',
scheduling_method: 'EMAIL',
appointment_datetime: proposedIso,
+ specialist_contact_email: config.credentials.specialist.email,
});
- assertNoContacts(own.body);
+ assertOwnerScopedSpecialistEmail(own.body);
const duplicate = await request(app!.getHttpServer())
.post('/api/appointments/pending')
.auth(customerToken, { type: 'bearer' })
@@ -627,7 +649,7 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => {
expect(duplicate.body.error.details).toEqual({
existing_request: snapshot,
});
- assertNoContacts(duplicate.body);
+ assertOwnerScopedSpecialistEmail(duplicate.body);
await assertStoredState(
car.id,
response.body.data.process_id,
@@ -793,7 +815,10 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => {
.expect(200);
expect(Object.keys(own.body.data).sort()).toEqual([...checkKeys].sort());
expect(own.body.data.appointment_status).toBe('SCHEDULED');
- assertNoContacts(own.body);
+ expect(own.body.data.specialist_contact_email).toBe(
+ config.credentials.specialist.email,
+ );
+ assertOwnerScopedSpecialistEmail(own.body);
}
expect(
await prisma!.appointment.count({
From c9004275547fdfeb97bd66a03cb88f5202b443c5 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Fri, 23 Oct 2026 11:00:56 -0300
Subject: [PATCH 51/60] fix(contracts): preserve active agreement invariants
---
.../admin-journey-p0.postgres.spec.ts | 306 ++++++++++++++++++
.../contracts/contracts-lock.postgres.spec.ts | 32 ++
.../contracts/contracts.service.spec.ts | 28 +-
.../features/contracts/contracts.service.ts | 213 +++++++-----
.../features/processes/processes.service.ts | 23 ++
.../providers/docusign/docusign.service.ts | 14 +-
.../docusign/webhook/webhook.service.ts | 10 +
7 files changed, 535 insertions(+), 91 deletions(-)
create mode 100644 backend/src/features/contracts/admin-journey-p0.postgres.spec.ts
diff --git a/backend/src/features/contracts/admin-journey-p0.postgres.spec.ts b/backend/src/features/contracts/admin-journey-p0.postgres.spec.ts
new file mode 100644
index 0000000..d28f38f
--- /dev/null
+++ b/backend/src/features/contracts/admin-journey-p0.postgres.spec.ts
@@ -0,0 +1,306 @@
+import {
+ BadRequestException,
+ ConflictException,
+} from '@nestjs/common';
+import {
+ ContractStatus,
+ PrismaClient,
+ ProcessStatus,
+ ProductCurrency,
+ ProviderStatus,
+ SignatureType,
+ UserRole,
+} from '@prisma/client';
+import { randomUUID } from 'node:crypto';
+import { ProcessesService } from '../processes/processes.service';
+import { DocuSignWebhookService } from '../../providers/docusign/webhook/webhook.service';
+import { ContractsService } from './contracts.service';
+import { EnvelopeStatus } from '../../providers/docusign/enums/envelope-status.enum';
+
+const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL;
+const describeWithPostgres = databaseUrl ? describe : describe.skip;
+
+function completedPayload(envelopeId: string) {
+ return {
+ event: 'envelope-completed',
+ generatedDateTime: '2026-10-23T12:00:00.000Z',
+ retryCount: 0,
+ configurationId: 1,
+ apiVersion: 'v2.1',
+ data: {
+ envelopeId,
+ accountId: 'test-account',
+ userId: 'test-provider-user',
+ },
+ };
+}
+
+describeWithPostgres('admin journey P0 — PostgreSQL + simulated DocuSign', () => {
+ const prisma = new PrismaClient({
+ datasources: { db: { url: databaseUrl! } },
+ });
+ const suffix = randomUUID().replaceAll('-', '');
+ const adminId = randomUUID();
+ const clientId = randomUUID();
+ const specialistId = randomUUID();
+ const processIds: string[] = [];
+
+ const notifications = {
+ sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined),
+ sendContractGeneratedEmail: jest.fn().mockResolvedValue(undefined),
+ sendContractSentEmail: jest.fn().mockResolvedValue(undefined),
+ sendContractSignedEmail: jest.fn().mockResolvedValue(undefined),
+ sendContractDeclinedEmail: jest.fn().mockResolvedValue(undefined),
+ sendContractVoidedEmail: jest.fn().mockResolvedValue(undefined),
+ sendContractTimeoutEmail: jest.fn().mockResolvedValue(undefined),
+ } as any;
+
+ beforeAll(async () => {
+ await prisma.user.createMany({
+ data: [
+ {
+ id: adminId,
+ name: 'P0',
+ surname: 'Admin',
+ email: `p0-admin-${suffix}@example.test`,
+ rg: suffix.slice(0, 11),
+ role: UserRole.ADMIN,
+ password_hash: 'not-used',
+ },
+ {
+ id: clientId,
+ name: 'P0',
+ surname: 'Client',
+ email: `p0-client-${suffix}@example.test`,
+ rg: suffix.slice(11, 22),
+ role: UserRole.CUSTOMER,
+ password_hash: 'not-used',
+ },
+ {
+ id: specialistId,
+ name: 'P0',
+ surname: 'Specialist',
+ email: `p0-specialist-${suffix}@example.test`,
+ rg: suffix.slice(21, 32),
+ role: UserRole.SPECIALIST,
+ password_hash: 'not-used',
+ commission_rate: 0,
+ },
+ ],
+ });
+ });
+
+ afterEach(async () => {
+ if (processIds.length === 0) return;
+ await prisma.process.updateMany({
+ where: { id: { in: processIds } },
+ data: { active_contract_id: null },
+ });
+ await prisma.contract.deleteMany({
+ where: { process_id: { in: processIds } },
+ });
+ await prisma.processStatusHistory.deleteMany({
+ where: { processId: { in: processIds } },
+ });
+ await prisma.processRejection.deleteMany({
+ where: { process_id: { in: processIds } },
+ });
+ await prisma.process.deleteMany({ where: { id: { in: processIds } } });
+ processIds.splice(0);
+ });
+
+ afterAll(async () => {
+ await prisma.user.deleteMany({
+ where: { id: { in: [adminId, clientId, specialistId] } },
+ });
+ await prisma.$disconnect();
+ });
+
+ async function createProcess(status = ProcessStatus.DOCUMENTATION) {
+ const id = randomUUID();
+ processIds.push(id);
+ await prisma.process.create({
+ data: {
+ id,
+ client_id: clientId,
+ specialist_id: specialistId,
+ status,
+ negotiation_currency: ProductCurrency.BRL,
+ negotiation_product_value: 100_000,
+ },
+ });
+ return id;
+ }
+
+ async function createContract(
+ processId: string,
+ envelopeId: string,
+ providerStatus = ProviderStatus.SENT,
+ ) {
+ return prisma.contract.create({
+ data: {
+ process_id: processId,
+ provider_name: 'DOCUSIGN',
+ provider_id: envelopeId,
+ provider_status: providerStatus,
+ status: ContractStatus.PENDING,
+ signature_type: SignatureType.SIMPLE,
+ uploaded_by_id: adminId,
+ uploaded_by_type: UserRole.ADMIN,
+ signed_by_id: clientId,
+ buyer_name: 'P0 Client',
+ seller_name: 'P0 Seller',
+ },
+ });
+ }
+
+ it('blocks rejection with a live envelope before a later COMPLETED webhook', async () => {
+ const processId = await createProcess();
+ const envelopeId = `p0-reject-${suffix}`;
+ const contract = await createContract(processId, envelopeId);
+ await prisma.process.update({
+ where: { id: processId },
+ data: { active_contract_id: contract.id },
+ });
+
+ const processes = new ProcessesService(prisma as any, notifications);
+ let rejectionError: unknown;
+ try {
+ await processes.rejectProcess(
+ processId,
+ adminId,
+ 'admin requested cancellation',
+ UserRole.ADMIN,
+ );
+ } catch (error) {
+ rejectionError = error;
+ }
+
+ const webhook = new DocuSignWebhookService(prisma as any, notifications);
+ await webhook.handleEnvelopeStatusChanged(completedPayload(envelopeId));
+
+ expect(rejectionError).toBeInstanceOf(BadRequestException);
+ await expect(
+ prisma.process.findUniqueOrThrow({ where: { id: processId } }),
+ ).resolves.toMatchObject({
+ status: ProcessStatus.COMPLETED,
+ active_contract_id: contract.id,
+ });
+ await expect(
+ prisma.processStatusHistory.count({
+ where: { processId, status: ProcessStatus.REJECTED },
+ }),
+ ).resolves.toBe(0);
+ });
+
+ it('updates an old contract from a delayed webhook without changing the process', async () => {
+ const processId = await createProcess();
+ const oldEnvelopeId = `p0-old-${suffix}`;
+ const oldContract = await createContract(processId, oldEnvelopeId);
+ const activeContract = await createContract(
+ processId,
+ `p0-active-${suffix}`,
+ );
+ await prisma.process.update({
+ where: { id: processId },
+ data: { active_contract_id: activeContract.id },
+ });
+
+ const webhook = new DocuSignWebhookService(prisma as any, notifications);
+ await webhook.handleEnvelopeStatusChanged(completedPayload(oldEnvelopeId));
+
+ await expect(
+ prisma.contract.findUniqueOrThrow({ where: { id: oldContract.id } }),
+ ).resolves.toMatchObject({
+ provider_status: ProviderStatus.COMPLETED,
+ status: ContractStatus.SIGNED,
+ });
+ await expect(
+ prisma.process.findUniqueOrThrow({ where: { id: processId } }),
+ ).resolves.toMatchObject({
+ status: ProcessStatus.DOCUMENTATION,
+ active_contract_id: activeContract.id,
+ });
+ await expect(
+ prisma.processStatusHistory.count({
+ where: { processId, status: ProcessStatus.COMPLETED },
+ }),
+ ).resolves.toBe(0);
+ });
+
+ it('rejects a send DTO whose legal content differs from the approved preview', async () => {
+ const processId = await createProcess(ProcessStatus.PROCESSING_CONTRACT);
+ const envelopeId = `p0-preview-${suffix}`;
+ let previewFingerprint = '';
+ const docusign = {
+ createEnvelopePreview: jest.fn().mockImplementation(async (params) => {
+ previewFingerprint = params.requestFingerprint;
+ params.onEnvelopeCreated?.(envelopeId);
+ return {
+ envelopeId,
+ previewUrl: 'https://docusign.example.test/preview',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ };
+ }),
+ getEnvelopeProcessId: jest.fn().mockResolvedValue(processId),
+ getEnvelopeRequestFingerprint: jest
+ .fn()
+ .mockImplementation(async () => previewFingerprint),
+ getEnvelopeStatus: jest.fn().mockResolvedValue({
+ envelopeId,
+ status: EnvelopeStatus.CREATED,
+ }),
+ sendDraftEnvelope: jest.fn().mockResolvedValue({
+ envelopeId,
+ status: EnvelopeStatus.SENT,
+ }),
+ voidDraftEnvelope: jest.fn().mockResolvedValue(undefined),
+ } as any;
+ const platformCompany = {
+ findOne: jest.fn().mockResolvedValue({ default_commission_rate: 10 }),
+ } as any;
+ const contracts = new ContractsService(
+ prisma as any,
+ docusign,
+ notifications,
+ platformCompany,
+ );
+ const approvedDto = {
+ operation_id: randomUUID(),
+ return_url: 'https://app.example.test/contracts/return',
+ process_id: processId,
+ template_id: 'template-p0',
+ seller_name: 'Approved Seller',
+ seller_email: 'seller@example.test',
+ buyer_name: 'P0 Client',
+ buyer_email: `p0-client-${suffix}@example.test`,
+ specialist_name: 'P0 Specialist',
+ specialist_email: `p0-specialist-${suffix}@example.test`,
+ vehicle_model: 'Approved Model',
+ vehicle_year: '2026',
+ vehicle_price: 100_000,
+ payment_seller_value: 90_000,
+ total_commission_rate: 10,
+ city: 'Sao Paulo',
+ description: 'Approved legal content',
+ } as any;
+
+ const preview = await contracts.previewContract(approvedDto, adminId);
+ await expect(
+ contracts.sendContractAfterPreview(
+ preview.envelope_id,
+ {
+ ...approvedDto,
+ seller_name: 'Tampered Seller',
+ vehicle_price: 1,
+ },
+ adminId,
+ ),
+ ).rejects.toBeInstanceOf(ConflictException);
+
+ expect(docusign.sendDraftEnvelope).not.toHaveBeenCalled();
+ await expect(
+ prisma.contract.count({ where: { process_id: processId } }),
+ ).resolves.toBe(0);
+ });
+});
diff --git a/backend/src/features/contracts/contracts-lock.postgres.spec.ts b/backend/src/features/contracts/contracts-lock.postgres.spec.ts
index 6ac2f06..b431a1b 100644
--- a/backend/src/features/contracts/contracts-lock.postgres.spec.ts
+++ b/backend/src/features/contracts/contracts-lock.postgres.spec.ts
@@ -269,6 +269,7 @@ describeWithPostgres('contract process lock — PostgreSQL concurrency', () => {
});
const docusign = {
getEnvelopeProcessId: jest.fn().mockResolvedValue(sendProcessId),
+ getEnvelopeRequestFingerprint: jest.fn(),
getEnvelopeStatus: jest.fn().mockResolvedValue({
envelopeId: 'send-envelope',
status: EnvelopeStatus.CREATED,
@@ -292,6 +293,21 @@ describeWithPostgres('contract process lock — PostgreSQL concurrency', () => {
platformCompany,
);
const dto = contractDto(sendProcessId, suffix);
+ docusign.getEnvelopeRequestFingerprint.mockResolvedValue(
+ (serviceA as any).buildPreviewFingerprint(
+ dto,
+ null,
+ {
+ platformValue: 10000,
+ platformRate: 10,
+ officeValue: 0,
+ officeRate: 0,
+ specialistValue: 0,
+ specialistRate: 0,
+ },
+ dto.template_id,
+ ).requestFingerprint,
+ );
const outcomesPromise = Promise.allSettled([
serviceA.sendContractAfterPreview('send-envelope', dto, specialistId),
@@ -319,6 +335,7 @@ describeWithPostgres('contract process lock — PostgreSQL concurrency', () => {
});
const docusign = {
getEnvelopeProcessId: jest.fn().mockResolvedValue(ambiguousCommitProcessId),
+ getEnvelopeRequestFingerprint: jest.fn(),
getEnvelopeStatus: jest.fn().mockResolvedValue({
envelopeId: 'ambiguous-envelope',
status: EnvelopeStatus.SENT,
@@ -342,6 +359,21 @@ describeWithPostgres('contract process lock — PostgreSQL concurrency', () => {
platformCompany,
);
const dto = contractDto(ambiguousCommitProcessId, suffix);
+ docusign.getEnvelopeRequestFingerprint.mockResolvedValue(
+ (firstAttempt as any).buildPreviewFingerprint(
+ dto,
+ null,
+ {
+ platformValue: 10000,
+ platformRate: 10,
+ officeValue: 0,
+ officeRate: 0,
+ specialistValue: 0,
+ specialistRate: 0,
+ },
+ dto.template_id,
+ ).requestFingerprint,
+ );
const firstResult = firstAttempt.sendContractAfterPreview(
'ambiguous-envelope',
diff --git a/backend/src/features/contracts/contracts.service.spec.ts b/backend/src/features/contracts/contracts.service.spec.ts
index 2786e18..0e9c6a7 100644
--- a/backend/src/features/contracts/contracts.service.spec.ts
+++ b/backend/src/features/contracts/contracts.service.spec.ts
@@ -745,6 +745,14 @@ describe('ContractsService — locked transaction and compensation', () => {
describe('ContractsService — send after preview integrity', () => {
function makeSendHarness(processOverrides: Record = {}) {
const process = processFixture(processOverrides);
+ const commission = {
+ platformValue: 1000,
+ platformRate: 1,
+ officeValue: 0,
+ officeRate: 0,
+ specialistValue: 9000,
+ specialistRate: 9,
+ };
const tx = {
$queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
process: {
@@ -778,6 +786,7 @@ describe('ContractsService — send after preview integrity', () => {
});
const docusign = {
getEnvelopeProcessId: jest.fn().mockResolvedValue('process-1'),
+ getEnvelopeRequestFingerprint: jest.fn(),
getEnvelopeStatus: jest.fn().mockResolvedValue({
envelopeId: 'envelope-1',
status: EnvelopeStatus.CREATED,
@@ -796,14 +805,9 @@ describe('ContractsService — send after preview integrity', () => {
} as any,
mkPlatformCompanyService(10),
);
- jest.spyOn(service as any, 'resolveCommissionFromTotal').mockResolvedValue({
- platformValue: 1000,
- platformRate: 1,
- officeValue: 0,
- officeRate: 0,
- specialistValue: 9000,
- specialistRate: 9,
- });
+ jest
+ .spyOn(service as any, 'resolveCommissionFromTotal')
+ .mockResolvedValue(commission);
const dto = {
operation_id: '11111111-1111-4111-8111-111111111111',
process_id: 'process-1',
@@ -822,6 +826,14 @@ describe('ContractsService — send after preview integrity', () => {
specialist_email: 'specialist@example.test',
city: 'Sao Paulo',
} as any;
+ docusign.getEnvelopeRequestFingerprint.mockImplementation(async () =>
+ (service as any).buildPreviewFingerprint(
+ dto,
+ process.product_type,
+ commission,
+ dto.template_id,
+ ).requestFingerprint,
+ );
return { service, docusign, tx, dto };
}
diff --git a/backend/src/features/contracts/contracts.service.ts b/backend/src/features/contracts/contracts.service.ts
index a6d18b6..67860c1 100644
--- a/backend/src/features/contracts/contracts.service.ts
+++ b/backend/src/features/contracts/contracts.service.ts
@@ -65,6 +65,15 @@ interface ExternalEnvelopeEffect {
providerStatus?: EnvelopeStatus;
}
+type ResolvedContractCommission = {
+ platformRate: number;
+ officeRate: number;
+ specialistRate: number;
+ platformValue: number;
+ officeValue: number;
+ specialistValue: number;
+};
+
export interface ContractDocumentFields {
seller_cpf?: string;
seller_rg?: string;
@@ -161,6 +170,88 @@ export class ContractsService {
.digest('hex');
}
+ private buildPreviewGenerateDto(
+ dto: PreviewContractDto,
+ commission: ResolvedContractCommission,
+ ): GenerateContractDto {
+ return {
+ operation_id: dto.operation_id,
+ process_id: dto.process_id,
+ total_commission_rate: dto.total_commission_rate,
+ seller_name: dto.seller_name,
+ seller_email: dto.seller_email,
+ seller_cpf: dto.seller_cpf,
+ seller_rg: dto.seller_rg,
+ seller_address: dto.seller_address ?? '',
+ seller_cep: dto.seller_cep,
+ seller_bank: dto.seller_bank ?? '',
+ seller_agency: dto.seller_agency ?? '',
+ seller_checking_account: dto.seller_checking_account ?? '',
+ buyer_name: dto.buyer_name,
+ buyer_email: dto.buyer_email,
+ buyer_cpf: dto.buyer_cpf,
+ buyer_rg: dto.buyer_rg,
+ buyer_address: dto.buyer_address ?? '',
+ buyer_cep: dto.buyer_cep,
+ vehicle_model: dto.vehicle_model ?? '',
+ vehicle_year: dto.vehicle_year ?? '',
+ vehicle_registration_id: dto.vehicle_registration_id ?? '',
+ vehicle_serial_number: dto.vehicle_serial_number ?? '',
+ vehicle_technical_info: dto.vehicle_technical_info,
+ vehicle_price: dto.vehicle_price,
+ payment_seller_value: dto.payment_seller_value,
+ platform_value: commission.platformValue,
+ platform_percentage: commission.platformRate,
+ platform_name: dto.platform_name,
+ platform_cnpj: dto.platform_cnpj,
+ platform_bank: dto.platform_bank,
+ platform_agency: dto.platform_agency,
+ platform_checking_account: dto.platform_checking_account,
+ office_value: commission.officeValue,
+ office_name: dto.office_name,
+ office_cnpj: dto.office_cnpj,
+ office_bank: dto.office_bank,
+ office_agency: dto.office_agency,
+ office_checking_account: dto.office_checking_account,
+ specialist_value: commission.specialistValue,
+ specialist_name: dto.specialist_name,
+ specialist_email: dto.specialist_email,
+ specialist_document: dto.specialist_document,
+ specialist_bank: dto.specialist_bank,
+ specialist_agency: dto.specialist_agency,
+ specialist_checking_account: dto.specialist_checking_account,
+ testimonial1_cpf: dto.testimonial1_cpf,
+ testimonial1_email: dto.testimonial1_email,
+ testimonial2_cpf: dto.testimonial2_cpf,
+ testimonial2_email: dto.testimonial2_email,
+ city: dto.city ?? '',
+ description: dto.description,
+ };
+ }
+
+ private buildPreviewFingerprint(
+ dto: PreviewContractDto,
+ productType: ProductType | null,
+ commission: ResolvedContractCommission,
+ templateId: string,
+ ): { formFields: Record; requestFingerprint: string } {
+ const generateDto = this.buildPreviewGenerateDto(dto, commission);
+ const formFields = this.buildFormFields(generateDto, productType);
+ return {
+ formFields,
+ requestFingerprint: this.contractIntentionFingerprint({
+ processId: dto.process_id,
+ templateId,
+ contract: {
+ ...(dto as unknown as Record),
+ ...(generateDto as unknown as Record),
+ },
+ commission,
+ formFields,
+ }),
+ };
+ }
+
private async getAuthorizedContractProcess(
processId: string,
userId: string,
@@ -1646,70 +1737,6 @@ export class ContractsService {
// ===== ETAPA 2: FORMATAR DADOS PARA DOCUSIGN =====
this.logger.log('Preview Etapa 2: Formatando dados para DocuSign...');
- // Reutilizar buildFormFields criando DTO compatível
- const generateDto: GenerateContractDto = {
- operation_id: dto.operation_id,
- process_id: dto.process_id,
- total_commission_rate: dto.total_commission_rate,
- seller_name: dto.seller_name,
- seller_email: dto.seller_email,
- seller_cpf: dto.seller_cpf,
- seller_rg: dto.seller_rg,
- seller_address: dto.seller_address ?? '',
- seller_cep: dto.seller_cep,
- seller_bank: dto.seller_bank ?? '',
- seller_agency: dto.seller_agency ?? '',
- seller_checking_account: dto.seller_checking_account ?? '',
- buyer_name: dto.buyer_name,
- buyer_email: dto.buyer_email,
- buyer_cpf: dto.buyer_cpf,
- buyer_rg: dto.buyer_rg,
- buyer_address: dto.buyer_address ?? '',
- buyer_cep: dto.buyer_cep,
- vehicle_model: dto.vehicle_model ?? '',
- vehicle_year: dto.vehicle_year ?? '',
- vehicle_registration_id: dto.vehicle_registration_id ?? '',
- vehicle_serial_number: dto.vehicle_serial_number ?? '',
- vehicle_technical_info: dto.vehicle_technical_info,
- vehicle_price: dto.vehicle_price,
- payment_seller_value: dto.payment_seller_value,
- platform_value: commission.platformValue,
- platform_percentage: commission.platformRate,
- platform_name: dto.platform_name,
- platform_cnpj: dto.platform_cnpj,
- platform_bank: dto.platform_bank,
- platform_agency: dto.platform_agency,
- platform_checking_account: dto.platform_checking_account,
- office_value: commission.officeValue,
- office_name: dto.office_name,
- office_cnpj: dto.office_cnpj,
- office_bank: dto.office_bank,
- office_agency: dto.office_agency,
- office_checking_account: dto.office_checking_account,
- specialist_value: commission.specialistValue,
- specialist_name: dto.specialist_name,
- specialist_email: dto.specialist_email,
- specialist_document: dto.specialist_document,
- specialist_bank: dto.specialist_bank,
- specialist_agency: dto.specialist_agency,
- specialist_checking_account: dto.specialist_checking_account,
- testimonial1_cpf: dto.testimonial1_cpf,
- testimonial1_email: dto.testimonial1_email,
- testimonial2_cpf: dto.testimonial2_cpf,
- testimonial2_email: dto.testimonial2_email,
- city: dto.city ?? '',
- description: dto.description,
- };
-
- const formFields = this.buildFormFields(
- generateDto,
- processRecord.product_type,
- );
-
- this.logger.debug(
- `Form fields preparados: ${Object.keys(formFields).length} campos`,
- );
-
// ===== ETAPA 3: CRIAR PREVIEW NO DOCUSIGN =====
this.logger.log('Preview Etapa 3: Criando preview no DocuSign...');
@@ -1721,16 +1748,17 @@ export class ContractsService {
);
}
- const requestFingerprint = this.contractIntentionFingerprint({
- processId: dto.process_id,
- templateId,
- contract: {
- ...(dto as unknown as Record),
- ...(generateDto as unknown as Record),
- },
- commission,
- formFields,
- });
+ const { formFields, requestFingerprint } =
+ this.buildPreviewFingerprint(
+ dto,
+ processRecord.product_type,
+ commission,
+ templateId,
+ );
+
+ this.logger.debug(
+ `Form fields preparados: ${Object.keys(formFields).length} campos`,
+ );
const previewResponse = await this.docuSignService.createEnvelopePreview({
transactionId: dto.operation_id,
@@ -2020,6 +2048,39 @@ export class ContractsService {
tx,
);
+ const templateId =
+ dto.template_id || globalThis.process.env.DOCUSIGN_TEMPLATE_ID;
+ if (!templateId) {
+ throw new InternalServerErrorException(
+ 'Nenhum template informado e DOCUSIGN_TEMPLATE_ID não configurado',
+ );
+ }
+ const { requestFingerprint } = this.buildPreviewFingerprint(
+ dto,
+ processRecord.product_type,
+ commission,
+ templateId,
+ );
+ const approvedFingerprint =
+ await this.docuSignService.getEnvelopeRequestFingerprint(envelopeId);
+ if (
+ !approvedFingerprint ||
+ approvedFingerprint !== requestFingerprint
+ ) {
+ throw new ConflictException({
+ success: false,
+ error: {
+ code: 'CONTRACT_PREVIEW_MISMATCH',
+ message:
+ 'Os dados do contrato mudaram após o preview. Gere e aprove um novo preview antes de enviar.',
+ details: {
+ process_id: dto.process_id,
+ envelope_id: envelopeId,
+ },
+ },
+ });
+ }
+
// ===== ETAPA 2: ENVIAR ENVELOPE NO DOCUSIGN =====
this.logger.log('Enviando envelope para DocuSign...');
@@ -2032,9 +2093,6 @@ export class ContractsService {
// ===== ETAPA 3: SALVAR NO BANCO =====
this.logger.log('Salvando contrato no banco...');
- const templateId =
- dto.template_id || globalThis.process.env.DOCUSIGN_TEMPLATE_ID || '';
-
const cleanDocs = stripContractDocumentFields(dto);
const contract = await tx.contract.create({
data: {
@@ -2052,6 +2110,7 @@ export class ContractsService {
originalStatus: sendResponse.status,
templateId: templateId,
previewUsed: true,
+ requestFingerprint,
} as any,
// Dados do vendedor
diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts
index bb138d7..f3481c0 100644
--- a/backend/src/features/processes/processes.service.ts
+++ b/backend/src/features/processes/processes.service.ts
@@ -22,6 +22,7 @@ import {
ProcessStatus,
ProductCurrency,
ProductType,
+ ProviderStatus,
StatusAgendamento,
UserRole,
} from '@prisma/client';
@@ -2171,6 +2172,13 @@ export class ProcessesService {
ended_at: true,
},
},
+ active_contract: {
+ select: {
+ id: true,
+ provider_id: true,
+ provider_status: true,
+ },
+ },
},
});
@@ -2193,6 +2201,21 @@ export class ProcessesService {
'Processo concluído não pode ser rejeitado',
);
}
+ if (
+ existingProcess.active_contract?.provider_id &&
+ ![
+ ProviderStatus.DECLINED,
+ ProviderStatus.VOIDED,
+ ProviderStatus.TIMEDOUT,
+ ProviderStatus.ERROR,
+ ].includes(
+ existingProcess.active_contract.provider_status as ProviderStatus,
+ )
+ ) {
+ throw new BadRequestException(
+ 'O contrato ativo ainda possui um envelope DocuSign vigente. Anule e reconcilie o envelope antes de rejeitar o processo.',
+ );
+ }
if (
Boolean(existingProcess.appointment) !==
Boolean(existingProcess.appointment_id) ||
diff --git a/backend/src/providers/docusign/docusign.service.ts b/backend/src/providers/docusign/docusign.service.ts
index 33a0fc4..5499afb 100644
--- a/backend/src/providers/docusign/docusign.service.ts
+++ b/backend/src/providers/docusign/docusign.service.ts
@@ -426,12 +426,14 @@ export class DocuSignService {
async getEnvelopeProcessId(envelopeId: string): Promise {
const envelope = await this.client.getEnvelopeWithCustomFields(envelopeId);
- const fields = envelope?.customFields?.textCustomFields;
- if (!Array.isArray(fields)) return null;
- const processField = fields.find(
- (field: any) => field?.name === 'processId',
- );
- return typeof processField?.value === 'string' ? processField.value : null;
+ return this.getCustomFieldValue(envelope, 'processId');
+ }
+
+ async getEnvelopeRequestFingerprint(
+ envelopeId: string,
+ ): Promise {
+ const envelope = await this.client.getEnvelopeWithCustomFields(envelopeId);
+ return this.getCustomFieldValue(envelope, 'requestFingerprint');
}
/**
diff --git a/backend/src/providers/docusign/webhook/webhook.service.ts b/backend/src/providers/docusign/webhook/webhook.service.ts
index 97e0e0d..9287f21 100644
--- a/backend/src/providers/docusign/webhook/webhook.service.ts
+++ b/backend/src/providers/docusign/webhook/webhook.service.ts
@@ -350,6 +350,16 @@ export class DocuSignWebhookService {
return updatedContract;
}
+ // O contrato mantém seu próprio estado, mas somente o contrato ativo
+ // pode dirigir a máquina de estados do processo. Eventos atrasados de
+ // envelopes substituídos não podem reativar nem concluir a venda.
+ if (process.active_contract_id !== contract.id) {
+ this.logger.log(
+ `[SYNC] Webhook do contrato não ativo ${contract.id}; processo ${process.id} preservado`,
+ );
+ return updatedContract;
+ }
+
// 7.3 Sincronizar status do processo com base no status do contrato
const processStatusUpdate: any = {};
let updateProcessActiveContract = false;
From 85e8a69a3889d58b88cfd6df4be5c8910d47a703 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Fri, 23 Oct 2026 11:35:29 -0300
Subject: [PATCH 52/60] feat(admin): complete delegated specialist backend
journey
---
.../migration.sql | 22 +
.../migration.sql | 11 +
.../migration.sql | 3 +
backend/prisma/schema.prisma | 24 +
backend/src/app.module.ts | 2 +
.../aircrafts/aircrafts.controller.spec.ts | 36 ++
.../aircrafts/aircrafts.controller.ts | 148 ++++-
.../features/aircrafts/aircrafts.service.ts | 4 +-
.../appointments-concurrency.postgres.spec.ts | 14 +-
.../appointments/appointments.controller.ts | 77 ++-
.../appointments/appointments.service.spec.ts | 37 +-
.../appointments/appointments.service.ts | 117 +++-
.../features/boats/boats.controller.spec.ts | 41 +-
.../src/features/boats/boats.controller.ts | 147 ++++-
backend/src/features/boats/boats.service.ts | 4 +-
.../src/features/cars/cars.controller.spec.ts | 73 ++-
backend/src/features/cars/cars.controller.ts | 154 ++++-
backend/src/features/cars/cars.service.ts | 4 +-
.../admin-journey-p0.postgres.spec.ts | 1 -
.../contracts/contracts.controller.ts | 24 +
.../contracts/contracts.service.spec.ts | 64 +-
.../features/contracts/contracts.service.ts | 197 +++++-
.../features/meetings/meetings.controller.ts | 49 +-
.../meetings/meetings.service.spec.ts | 60 +-
.../src/features/meetings/meetings.service.ts | 139 ++++-
.../processes/processes.controller.spec.ts | 36 +-
.../processes/processes.controller.ts | 165 ++++-
.../features/processes/processes.service.ts | 256 +++++++-
.../product-import-jobs.controller.ts | 19 +-
.../product-import-jobs.service.spec.ts | 144 +++++
.../product-import-jobs.service.ts | 262 +++++++-
.../products/product-association-validator.ts | 6 +-
.../proposals/proposals.controller.ts | 63 +-
.../proposals/proposals.service.spec.ts | 65 +-
.../features/proposals/proposals.service.ts | 121 +++-
.../actor-context/actor-context.module.ts | 10 +
.../actor-context.service.spec.ts | 100 +++
.../actor-context/actor-context.service.ts | 138 +++++
.../delegated-action-audit.service.ts | 103 ++++
.../shared/helpers/specialist-auth.helper.ts | 12 +-
.../shared/selects/public-catalog.select.ts | 3 +
.../test/admin-specialist-journey.e2e-spec.ts | 578 ++++++++++++++++++
42 files changed, 3353 insertions(+), 180 deletions(-)
create mode 100644 backend/prisma/migrations/20261023110500_add_delegated_action_audit/migration.sql
create mode 100644 backend/prisma/migrations/20261023111500_add_product_import_policy/migration.sql
create mode 100644 backend/prisma/migrations/20261023113000_enforce_single_pending_proposal/migration.sql
create mode 100644 backend/src/shared/actor-context/actor-context.module.ts
create mode 100644 backend/src/shared/actor-context/actor-context.service.spec.ts
create mode 100644 backend/src/shared/actor-context/actor-context.service.ts
create mode 100644 backend/src/shared/actor-context/delegated-action-audit.service.ts
create mode 100644 backend/test/admin-specialist-journey.e2e-spec.ts
diff --git a/backend/prisma/migrations/20261023110500_add_delegated_action_audit/migration.sql b/backend/prisma/migrations/20261023110500_add_delegated_action_audit/migration.sql
new file mode 100644
index 0000000..01f8c21
--- /dev/null
+++ b/backend/prisma/migrations/20261023110500_add_delegated_action_audit/migration.sql
@@ -0,0 +1,22 @@
+CREATE TABLE "DelegatedActionAudit" (
+ "id" UUID NOT NULL DEFAULT gen_random_uuid(),
+ "actor_id" UUID NOT NULL,
+ "actor_role" "UserRole" NOT NULL,
+ "represented_specialist_id" UUID NOT NULL,
+ "action" VARCHAR(80) NOT NULL,
+ "resource_type" VARCHAR(80) NOT NULL,
+ "resource_id" VARCHAR(128) NOT NULL,
+ "metadata" JSONB,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "DelegatedActionAudit_pkey" PRIMARY KEY ("id")
+);
+
+CREATE INDEX "DelegatedActionAudit_actor_id_created_at_idx"
+ ON "DelegatedActionAudit"("actor_id", "created_at");
+CREATE INDEX "DelegatedActionAudit_represented_specialist_id_created_at_idx"
+ ON "DelegatedActionAudit"("represented_specialist_id", "created_at");
+CREATE INDEX "DelegatedActionAudit_resource_type_resource_id_idx"
+ ON "DelegatedActionAudit"("resource_type", "resource_id");
+CREATE INDEX "DelegatedActionAudit_action_created_at_idx"
+ ON "DelegatedActionAudit"("action", "created_at");
diff --git a/backend/prisma/migrations/20261023111500_add_product_import_policy/migration.sql b/backend/prisma/migrations/20261023111500_add_product_import_policy/migration.sql
new file mode 100644
index 0000000..b5bb4e0
--- /dev/null
+++ b/backend/prisma/migrations/20261023111500_add_product_import_policy/migration.sql
@@ -0,0 +1,11 @@
+ALTER TABLE "ProductImportJob"
+ ADD COLUMN "created_by_id" UUID,
+ ADD COLUMN "mode" VARCHAR(20) NOT NULL DEFAULT 'ADDITIVE',
+ ADD COLUMN "sync_confirmed" BOOLEAN NOT NULL DEFAULT false;
+
+CREATE INDEX "ProductImportJob_created_by_id_idx"
+ ON "ProductImportJob"("created_by_id");
+
+ALTER TABLE "ProductImportJob"
+ ADD CONSTRAINT "ProductImportJob_mode_check"
+ CHECK ("mode" IN ('ADDITIVE', 'SYNCHRONIZE'));
diff --git a/backend/prisma/migrations/20261023113000_enforce_single_pending_proposal/migration.sql b/backend/prisma/migrations/20261023113000_enforce_single_pending_proposal/migration.sql
new file mode 100644
index 0000000..8e3c5a6
--- /dev/null
+++ b/backend/prisma/migrations/20261023113000_enforce_single_pending_proposal/migration.sql
@@ -0,0 +1,3 @@
+CREATE UNIQUE INDEX "NegotiationProposal_one_pending_per_process_idx"
+ ON "NegotiationProposal"("process_id")
+ WHERE "status" = 'PENDING';
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index a0a8bf3..a942c5d 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -958,6 +958,26 @@ model ProcessRejection {
@@index([rejected_at])
}
+// Trilha aditiva de ações executadas por um ator em nome de um especialista.
+// IDs são intencionalmente mantidos sem FK/onDelete para preservar a prova
+// mesmo quando o recurso operacional for removido por regras legadas.
+model DelegatedActionAudit {
+ id String @id @default(uuid()) @db.Uuid
+ actor_id String @db.Uuid
+ actor_role UserRole
+ represented_specialist_id String @db.Uuid
+ action String @db.VarChar(80)
+ resource_type String @db.VarChar(80)
+ resource_id String @db.VarChar(128)
+ metadata Json?
+ created_at DateTime @default(now())
+
+ @@index([actor_id, created_at])
+ @@index([represented_specialist_id, created_at])
+ @@index([resource_type, resource_id])
+ @@index([action, created_at])
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// ▸ PROPOSTAS DE NEGOCIAÇÃO
// ─────────────────────────────────────────────────────────────────────────────
@@ -1318,6 +1338,9 @@ model ProductImportJob {
id String @id @default(uuid()) @db.Uuid
product_type ProductType
specialist_id String @db.Uuid
+ created_by_id String? @db.Uuid
+ mode String @default("ADDITIVE") @db.VarChar(20)
+ sync_confirmed Boolean @default(false)
status ProductImportJobStatus @default(PENDING)
total_items Int @default(0)
processed_items Int @default(0)
@@ -1337,6 +1360,7 @@ model ProductImportJob {
items ProductImportJobItem[]
@@index([specialist_id])
+ @@index([created_by_id])
@@index([status])
@@index([product_type])
@@index([created_at])
diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts
index 2a270ee..7e7f3ae 100644
--- a/backend/src/app.module.ts
+++ b/backend/src/app.module.ts
@@ -31,12 +31,14 @@ import { CustomerAdvisorsModule } from './features/customer-advisors/customer-ad
import { OfficeModule } from './features/office/office.module';
import { CommissionsModule } from './features/commissions/commissions.module';
import { AdminDatabaseModule } from './features/admin-database/admin-database.module';
+import { ActorContextModule } from './shared/actor-context/actor-context.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
+ ActorContextModule,
HealthModule,
ConsultantsModule,
SpecialistsModule,
diff --git a/backend/src/features/aircrafts/aircrafts.controller.spec.ts b/backend/src/features/aircrafts/aircrafts.controller.spec.ts
index 3dfb613..93aa2e4 100644
--- a/backend/src/features/aircrafts/aircrafts.controller.spec.ts
+++ b/backend/src/features/aircrafts/aircrafts.controller.spec.ts
@@ -4,13 +4,31 @@ import { AircraftsController } from './aircrafts.controller';
function mkController() {
const aircraftsService = {
create: jest.fn().mockResolvedValue({ id: 'aircraft-1' }),
+ findOne: jest.fn().mockResolvedValue({
+ id: 'aircraft-1',
+ specialist_id: 'spec-1',
+ }),
+ update: jest.fn().mockResolvedValue({ id: 'aircraft-1' }),
} as any;
const productImportJobsService = {
createJobFromCsv: jest.fn().mockResolvedValue({ id: 'job-1' }),
} as any;
+ const actorContext = {
+ resolve: jest.fn().mockImplementation(async (user, target) => ({
+ actorId: user.id,
+ actorRole: user.role,
+ specialistId: target ?? user.id,
+ delegated: user.role === 'ADMIN',
+ specialist: {},
+ })),
+ assertResourceSpecialist: jest.fn(),
+ } as any;
+ const audit = { record: jest.fn().mockResolvedValue(undefined) } as any;
const controller = new AircraftsController(
aircraftsService,
productImportJobsService,
+ actorContext,
+ audit,
);
return { controller, aircraftsService, productImportJobsService };
}
@@ -33,6 +51,19 @@ describe('AircraftsController — Calendly opcional', () => {
expect(aircraftsService.create).toHaveBeenCalledWith(dto);
});
+ it('não permite remover o owner no PATCH comum', async () => {
+ const { controller, aircraftsService } = mkController();
+
+ await expect(
+ controller.update(
+ 'aircraft-1',
+ { specialist_id: null } as any,
+ specialist,
+ ),
+ ).rejects.toMatchObject({ status: 400 });
+ expect(aircraftsService.update).not.toHaveBeenCalled();
+ });
+
it('permite importação CSV sem consultar Calendly', async () => {
const { controller, productImportJobsService } = mkController();
const file = {
@@ -48,6 +79,11 @@ describe('AircraftsController — Calendly opcional', () => {
file.buffer,
specialist,
ProductType.AIRCRAFT,
+ expect.objectContaining({
+ mode: 'ADDITIVE',
+ confirmSynchronize: false,
+ context: expect.objectContaining({ specialistId: specialist.id }),
+ }),
);
});
});
diff --git a/backend/src/features/aircrafts/aircrafts.controller.ts b/backend/src/features/aircrafts/aircrafts.controller.ts
index ab93198..d7033d2 100644
--- a/backend/src/features/aircrafts/aircrafts.controller.ts
+++ b/backend/src/features/aircrafts/aircrafts.controller.ts
@@ -27,27 +27,70 @@ import { UserEntity } from 'src/auth/entities/user.entity';
import {
assertSpecialistCanCreate,
assertSpecialistCanModify,
+ assertNoProductOwnerMutation,
assertSpecialistOwnsProduct,
} from 'src/shared/helpers/specialist-auth.helper';
import { Public } from 'src/shared/decorators/public.decorator';
import { ProductImportJobsService } from '../product-import-jobs/product-import-jobs.service';
+import { ActorContextService } from 'src/shared/actor-context/actor-context.service';
+import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
@Controller('aircrafts')
export class AircraftsController {
constructor(
private readonly aircraftsService: AircraftsService,
private readonly productImportJobsService: ProductImportJobsService,
+ private readonly actorContextService: ActorContextService,
+ private readonly delegatedAudit: DelegatedActionAuditService,
) {}
@Post()
@Roles(UserRole.ADMIN, UserRole.SPECIALIST)
- create(
+ async create(
@Body() createAircraftDto: CreateAircraftDto,
@CurrentUser() user: UserEntity,
) {
- assertSpecialistCanCreate('AIRCRAFT', user);
- createAircraftDto.specialist_id = user.id;
- return this.aircraftsService.create(createAircraftDto);
+ const context = await this.actorContextService.resolve(
+ user,
+ createAircraftDto.specialist_id,
+ ProductType.AIRCRAFT,
+ );
+ createAircraftDto.specialist_id = context.specialistId;
+ const aircraft = await this.aircraftsService.create(createAircraftDto);
+ await this.delegatedAudit.record({
+ context,
+ action: 'PRODUCT_CREATE',
+ resourceType: 'AIRCRAFT',
+ resourceId: aircraft.id,
+ });
+ return aircraft;
+ }
+
+ @Post('import-csv/preview')
+ @Roles(UserRole.ADMIN, UserRole.SPECIALIST)
+ @UseInterceptors(
+ FileInterceptor('file', { limits: { fileSize: 50 * 1024 * 1024 } }),
+ )
+ async previewCsvImport(
+ @UploadedFile() file: Express.Multer.File,
+ @CurrentUser() user: UserEntity,
+ @Body('specialist_id') targetSpecialistId?: string,
+ @Body('mode') mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE',
+ ) {
+ const context = await this.actorContextService.resolve(
+ user,
+ targetSpecialistId,
+ ProductType.AIRCRAFT,
+ );
+ if (!file?.originalname?.toLowerCase().endsWith('.csv')) {
+ throw new BadRequestException('Arquivo CSV é obrigatório.');
+ }
+ return this.productImportJobsService.previewCsvImport(
+ file.buffer,
+ ProductType.AIRCRAFT,
+ context.specialistId,
+ mode,
+ );
}
@Post('import-csv')
@@ -58,8 +101,15 @@ export class AircraftsController {
async importCsv(
@UploadedFile() file: Express.Multer.File,
@CurrentUser() user: UserEntity,
+ @Body('specialist_id') targetSpecialistId?: string,
+ @Body('mode') mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE',
+ @Body('confirm_synchronize') confirmSynchronize = false,
) {
- assertSpecialistCanCreate('AIRCRAFT', user);
+ const context = await this.actorContextService.resolve(
+ user,
+ targetSpecialistId,
+ ProductType.AIRCRAFT,
+ );
if (!file) {
throw new BadRequestException('Arquivo CSV é obrigatório.');
@@ -78,6 +128,7 @@ export class AircraftsController {
file.buffer,
user,
ProductType.AIRCRAFT,
+ { context, mode, confirmSynchronize },
);
}
@@ -138,6 +189,45 @@ export class AircraftsController {
};
}
+ @Get('admin/all')
+ @Roles(UserRole.ADMIN)
+ async getAllAircraftsForAdmin(
+ @Query() query: any,
+ @CurrentUser() user: UserEntity,
+ ) {
+ let { page, perPage, target_specialist_id, ...rawFilters } = query;
+ page = Number(page) || 1;
+ perPage = Number(perPage) || 20;
+ const context = await this.actorContextService.resolve(
+ user,
+ target_specialist_id,
+ ProductType.AIRCRAFT,
+ );
+ rawFilters.specialist_id = context.specialistId;
+ const { data, count, filters = {} } =
+ await this.aircraftsService.getAllAircrafts(
+ { page, perPage, appliedFilters: rawFilters },
+ true,
+ );
+ const skip = (page - 1) * perPage;
+ return {
+ success: true,
+ message: 'Catálogo administrativo de aeronaves listado com sucesso',
+ data,
+ meta: {
+ pagination: {
+ current_page: page,
+ total_pages: Math.ceil(count / perPage),
+ has_next: skip + perPage < count,
+ has_prev: skip > 0,
+ total: count,
+ per_page: perPage,
+ },
+ filters: { applied_filters: filters, total_without_filters: count },
+ },
+ };
+ }
+
@Get(':id')
@Public()
findOne(@Param('id') id: string) {
@@ -150,19 +240,53 @@ export class AircraftsController {
@Param('id') id: string,
@Body() updateAircraftDto: UpdateAircraftDto,
@CurrentUser() user: UserEntity,
+ @Query('target_specialist_id') targetSpecialistId?: string,
) {
- assertSpecialistCanModify('AIRCRAFT', user);
+ assertNoProductOwnerMutation(updateAircraftDto as Record);
+ const context = await this.actorContextService.resolve(
+ user,
+ targetSpecialistId,
+ ProductType.AIRCRAFT,
+ );
const existing = await this.aircraftsService.findOne(id);
- assertSpecialistOwnsProduct(user, existing?.specialist_id);
- return this.aircraftsService.update(id, updateAircraftDto);
+ this.actorContextService.assertResourceSpecialist(
+ context,
+ existing?.specialist_id,
+ );
+ const aircraft = await this.aircraftsService.update(id, updateAircraftDto);
+ await this.delegatedAudit.record({
+ context,
+ action: 'PRODUCT_UPDATE',
+ resourceType: 'AIRCRAFT',
+ resourceId: id,
+ });
+ return aircraft;
}
@Delete(':id')
@Roles(UserRole.ADMIN, UserRole.SPECIALIST)
- async remove(@Param('id') id: string, @CurrentUser() user: UserEntity) {
- assertSpecialistCanModify('AIRCRAFT', user);
+ async remove(
+ @Param('id') id: string,
+ @CurrentUser() user: UserEntity,
+ @Query('target_specialist_id') targetSpecialistId?: string,
+ ) {
+ const context = await this.actorContextService.resolve(
+ user,
+ targetSpecialistId,
+ ProductType.AIRCRAFT,
+ );
const existing = await this.aircraftsService.findOne(id);
- assertSpecialistOwnsProduct(user, existing?.specialist_id);
- return this.aircraftsService.remove(id);
+ this.actorContextService.assertResourceSpecialist(
+ context,
+ existing?.specialist_id,
+ );
+ const result = await this.aircraftsService.remove(id);
+ await this.delegatedAudit.record({
+ context,
+ action: 'PRODUCT_DEACTIVATE',
+ resourceType: 'AIRCRAFT',
+ resourceId: id,
+ });
+ return result;
}
}
diff --git a/backend/src/features/aircrafts/aircrafts.service.ts b/backend/src/features/aircrafts/aircrafts.service.ts
index ffebf4c..d7d1e78 100644
--- a/backend/src/features/aircrafts/aircrafts.service.ts
+++ b/backend/src/features/aircrafts/aircrafts.service.ts
@@ -125,14 +125,14 @@ export class AircraftsService {
page,
perPage,
appliedFilters,
- }: QueryDto) {
+ }: QueryDto, includeInactive = false) {
// Cálculo das variáveis que serão utilizadas
const take = perPage;
const skip = page && take ? (page - 1) * take : 0;
// Separação dos filtros
const where: any = {};
- where.is_active = true;
+ if (!includeInactive) where.is_active = true;
// Exact
const exacts: ExactAircraftFilters = {
diff --git a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts
index d814dc0..fb7622e 100644
--- a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts
+++ b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts
@@ -730,7 +730,6 @@ describeWithPostgres(
status: ProcessStatus.SCHEDULING,
},
});
-
const completingAppointment = await holder.appointment.create({
data: {
client_id: clientIds[1],
@@ -742,7 +741,7 @@ describeWithPostgres(
appointment_datetime: new Date('2099-01-01T08:00:00.000Z'),
},
});
- await holder.process.create({
+ const completingProcess = await holder.process.create({
data: {
client_id: clientIds[1],
specialist_id: specialistId,
@@ -752,6 +751,17 @@ describeWithPostgres(
status: ProcessStatus.SCHEDULING,
},
});
+ await holder.meetingSession.create({
+ data: {
+ process_id: completingProcess.id,
+ meet_link: 'https://meet.jit.si/appointment-lock-order',
+ calendar_event_id: `appointment-lock-order-${completingProcess.id}`,
+ started_by_id: specialistId,
+ ended_by_id: specialistId,
+ started_at: new Date('2099-01-01T08:00:00.000Z'),
+ ended_at: new Date('2099-01-01T09:00:00.000Z'),
+ },
+ });
const completionHasSchedule = deferred();
const releaseCompletion = deferred();
diff --git a/backend/src/features/appointments/appointments.controller.ts b/backend/src/features/appointments/appointments.controller.ts
index 38d0641..7283ebe 100644
--- a/backend/src/features/appointments/appointments.controller.ts
+++ b/backend/src/features/appointments/appointments.controller.ts
@@ -12,6 +12,8 @@ import {
Request,
HttpStatus,
ForbiddenException,
+ BadRequestException,
+ Optional,
} from '@nestjs/common';
import { AppointmentsService } from './appointments.service';
import {
@@ -27,7 +29,11 @@ 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';
+import { StatusAgendamento, UserRole } from '@prisma/client';
+import {
+ ActorContext,
+ ActorContextService,
+} from 'src/shared/actor-context/actor-context.service';
/**
* AppointmentsController
@@ -51,7 +57,23 @@ import { UserRole } from '@prisma/client';
@Controller('appointments')
@UseGuards(AuthGuard)
export class AppointmentsController {
- constructor(private appointmentsService: AppointmentsService) {}
+ constructor(
+ private appointmentsService: AppointmentsService,
+ @Optional() private readonly actorContextService?: ActorContextService,
+ ) {}
+
+ private async resolveSpecialistContext(
+ user: UserEntity,
+ targetSpecialistId?: string,
+ ): Promise {
+ if (
+ !this.actorContextService ||
+ (user.role !== UserRole.ADMIN && user.role !== UserRole.SPECIALIST)
+ ) {
+ return undefined;
+ }
+ return this.actorContextService.resolve(user, targetSpecialistId);
+ }
/**
* GET /api/appointments
@@ -297,16 +319,31 @@ export class AppointmentsController {
@Param('id') id: string,
@Body() updateAppointmentStatusDto: UpdateAppointmentStatusDto,
@Request() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
) {
// userId e userRole vêm do AuthGuard
const userId = req.user.id;
const userRole = req.user.role;
+ if (
+ userRole === UserRole.ADMIN &&
+ updateAppointmentStatusDto.status === StatusAgendamento.CANCELLED &&
+ !updateAppointmentStatusDto.notes?.trim()
+ ) {
+ throw new BadRequestException(
+ 'Motivo é obrigatório para cancelamento administrativo.',
+ );
+ }
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
const appointment = await this.appointmentsService.updateStatus(
id,
updateAppointmentStatusDto,
userId,
userRole,
+ context,
);
return {
@@ -321,11 +358,17 @@ export class AppointmentsController {
@Param('id', new ParseUUIDPipe()) id: string,
@Body() dto: RescheduleAppointmentDto,
@Request() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
) {
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
const appointment = await this.appointmentsService.reschedule(
id,
dto.appointment_datetime,
req.user.id,
+ context,
);
return {
@@ -398,13 +441,19 @@ export class AppointmentsController {
@Param('id', new ParseUUIDPipe()) id: string,
@Body() body: ConfirmProcessAppointmentDto,
@Request() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
) {
const userId = req.user.id;
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
const appointment = await this.appointmentsService.confirmPending(
id,
userId,
body.appointment_datetime,
+ context,
);
return {
@@ -421,10 +470,30 @@ export class AppointmentsController {
* Cliente ou especialista podem cancelar
*/
@Post('pending/:id/cancel')
- async cancelPending(@Param('id') id: string, @Request() req: any) {
+ async cancelPending(
+ @Param('id') id: string,
+ @Request() req: any,
+ @Body('reason') reason?: string,
+ @Query('target_specialist_id') targetSpecialistId?: string,
+ ) {
const userId = req.user.id;
- const result = await this.appointmentsService.cancelPending(id, userId);
+ if (req.user.role === UserRole.ADMIN && !reason?.trim()) {
+ throw new BadRequestException(
+ 'Motivo é obrigatório para cancelamento administrativo.',
+ );
+ }
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
+
+ const result = await this.appointmentsService.cancelPending(
+ id,
+ userId,
+ context,
+ reason,
+ );
return result;
}
diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts
index 3737d5d..5f09f81 100644
--- a/backend/src/features/appointments/appointments.service.spec.ts
+++ b/backend/src/features/appointments/appointments.service.spec.ts
@@ -1285,7 +1285,10 @@ describe('AppointmentsService.updateStatus — snapshot da negociação', () =>
updated_at: new Date('2099-01-01T00:00:00.000Z'),
client: { id: 'client-1' },
specialist: { id: 'specialist-1' },
- process: null,
+ process: {
+ id: 'process-1',
+ meeting_session: { ended_at: new Date('2099-01-01T11:00:00.000Z') },
+ },
};
const appointmentUpdate = jest.fn().mockResolvedValue({
...appointment,
@@ -1345,6 +1348,36 @@ describe('AppointmentsService.updateStatus — snapshot da negociação', () =>
expect(prisma.$transaction).not.toHaveBeenCalled();
});
+ it('impede a rota genérica de concluir sem reunião encerrada', async () => {
+ 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.SCHEDULING,
+ meeting_session: null,
+ },
+ };
+ 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.COMPLETED },
+ appointment.specialist_id,
+ UserRole.SPECIALIST,
+ ),
+ ).rejects.toThrow('Conclua a reunião pelo fluxo de conversa');
+ expect(prisma.$transaction).not.toHaveBeenCalled();
+ });
+
it('impede que a rota genérica confirme ou reabra um agendamento', async () => {
const appointment = {
id: 'appointment-1',
@@ -1396,6 +1429,7 @@ describe('AppointmentsService.updateStatus — snapshot da negociação', () =>
};
const process = {
id: 'process-1',
+ meeting_session: { ended_at: new Date('2026-01-01T11:00:00.000Z') },
status: ProcessStatus.SCHEDULING,
notes: null,
product_type: ProductType.CAR,
@@ -1542,6 +1576,7 @@ describe('AppointmentsService.updateStatus — snapshot da negociação', () =>
};
const process = {
id: 'process-1',
+ meeting_session: { ended_at: new Date('2026-01-01T11:00:00.000Z') },
status: ProcessStatus.SCHEDULING,
notes: null,
product_type: ProductType.CAR,
diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts
index 970e005..3bdbafa 100644
--- a/backend/src/features/appointments/appointments.service.ts
+++ b/backend/src/features/appointments/appointments.service.ts
@@ -5,6 +5,7 @@ import {
NotFoundException,
ForbiddenException,
Logger,
+ Optional,
} from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import {
@@ -57,6 +58,8 @@ import {
buildOccupiedScheduleWhere,
lockAndAssertSpecialistScheduleAvailable,
} from './appointment-schedule-lock';
+import { ActorContext } from 'src/shared/actor-context/actor-context.service';
+import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
/**
* AppointmentsService
@@ -87,8 +90,21 @@ export class AppointmentsService {
private prisma: PrismaService,
private notificationService: NotificationService,
private calendlyIntegrationService: CalendlyIntegrationService,
+ @Optional()
+ private readonly delegatedAudit?: DelegatedActionAuditService,
) {}
+ private assertRepresentedSpecialist(
+ context: ActorContext | undefined,
+ specialistId: string,
+ ) {
+ if (context && context.specialistId !== specialistId) {
+ throw new ForbiddenException(
+ 'O agendamento não pertence ao especialista representado.',
+ );
+ }
+ }
+
/** Bloqueia a criação direta sem confirmação do especialista. */
async create(
_dto: CreatePlatformAppointmentDto,
@@ -109,6 +125,7 @@ export class AppointmentsService {
appointmentId: string,
appointmentDatetime: string,
userId: string,
+ context?: ActorContext,
): Promise {
const nextDate = parseDate(appointmentDatetime);
if (!nextDate || !isFutureDate(nextDate)) {
@@ -128,7 +145,8 @@ export class AppointmentsService {
if (!appointment) {
throw new NotFoundException('Agendamento não encontrado');
}
- if (appointment.specialist_id !== userId) {
+ const representedSpecialistId = context?.specialistId ?? userId;
+ if (appointment.specialist_id !== representedSpecialistId) {
throw new ForbiddenException(
'Apenas o especialista responsável pode alterar o horário',
);
@@ -144,7 +162,8 @@ export class AppointmentsService {
if (!lockedAppointment) {
throw new NotFoundException('Agendamento não encontrado');
}
- if (lockedAppointment.specialist_id !== userId) {
+ this.assertRepresentedSpecialist(context, lockedAppointment.specialist_id);
+ if (lockedAppointment.specialist_id !== representedSpecialistId) {
throw new ForbiddenException(
'Apenas o especialista responsável pode alterar o horário',
);
@@ -194,6 +213,22 @@ export class AppointmentsService {
throw this.buildRescheduleAlreadyUsedError(appointmentId);
}
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'APPOINTMENT_RESCHEDULE',
+ resourceType: 'APPOINTMENT',
+ resourceId: appointmentId,
+ metadata: {
+ from: lockedAppointment.appointment_datetime,
+ to: nextDate,
+ },
+ },
+ tx,
+ );
+ }
+
return tx.appointment.findUniqueOrThrow({
where: { id: appointmentId },
include: { client: true, specialist: true, process: true },
@@ -572,11 +607,15 @@ export class AppointmentsService {
dto: UpdateAppointmentStatusDto,
userId: string,
userRole: UserRole,
+ context?: ActorContext,
): Promise {
const assertTransitionAllowed = (current: any): void => {
+ this.assertRepresentedSpecialist(context, current.specialist_id);
+ const representedSpecialistId = context?.specialistId ?? userId;
const isParticipant =
- current.client_id === userId || current.specialist_id === userId;
- if (!isParticipant && userRole !== UserRole.ADMIN) {
+ current.client_id === userId ||
+ current.specialist_id === representedSpecialistId;
+ if (!isParticipant) {
throw new ForbiddenException({
success: false,
error: {
@@ -610,6 +649,11 @@ export class AppointmentsService {
'Apenas uma reunião agendada pode ser concluída',
);
}
+ if (!current.process?.meeting_session?.ended_at) {
+ throw new BadRequestException(
+ 'Conclua a reunião pelo fluxo de conversa antes de encerrar o agendamento.',
+ );
+ }
}
if (
@@ -637,7 +681,7 @@ export class AppointmentsService {
include: {
client: true,
specialist: true,
- process: true,
+ process: { include: { meeting_session: true } },
},
});
@@ -661,7 +705,7 @@ export class AppointmentsService {
include: {
client: true,
specialist: true,
- process: true,
+ process: { include: { meeting_session: true } },
},
});
if (!lockedAppointment) {
@@ -700,6 +744,23 @@ export class AppointmentsService {
});
}
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'APPOINTMENT_STATUS_UPDATE',
+ resourceType: 'APPOINTMENT',
+ resourceId: id,
+ metadata: {
+ from: lockedAppointment.status,
+ to: dto.status,
+ reason: dto.notes ?? null,
+ },
+ },
+ tx,
+ );
+ }
+
// 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.
@@ -1399,6 +1460,7 @@ export class AppointmentsService {
appointmentId: string,
userId: string,
appointmentDatetime?: string | Date,
+ context?: ActorContext,
): Promise {
this.logger.log(
`[confirmPending] Confirmando agendamento ${appointmentId} por ${userId}`,
@@ -1417,7 +1479,8 @@ export class AppointmentsService {
}
// Apenas especialista pode confirmar
- if (appointment.specialist_id !== userId) {
+ const representedSpecialistId = context?.specialistId ?? userId;
+ if (appointment.specialist_id !== representedSpecialistId) {
throw new ForbiddenException({
success: false,
error: {
@@ -1525,7 +1588,8 @@ export class AppointmentsService {
error: { code: 404, message: 'Agendamento não encontrado' },
});
}
- if (lockedAppointment.specialist_id !== userId) {
+ this.assertRepresentedSpecialist(context, lockedAppointment.specialist_id);
+ if (lockedAppointment.specialist_id !== representedSpecialistId) {
throw new ForbiddenException({
success: false,
error: {
@@ -1675,6 +1739,19 @@ export class AppointmentsService {
},
});
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'APPOINTMENT_CONFIRM',
+ resourceType: 'APPOINTMENT',
+ resourceId: appointmentId,
+ metadata: { processId: updatedProcess.id, confirmedDateTime },
+ },
+ tx,
+ );
+ }
+
return [updatedApt, updatedProcess];
});
@@ -1737,6 +1814,8 @@ export class AppointmentsService {
async cancelPending(
appointmentId: string,
userId: string,
+ context?: ActorContext,
+ reason?: string,
): Promise<{ success: boolean; message: string }> {
this.logger.log(
`[cancelPending] Cancelando agendamento ${appointmentId} por ${userId}`,
@@ -1756,7 +1835,8 @@ export class AppointmentsService {
// Apenas cliente ou especialista podem cancelar
const isClient = candidate.client_id === userId;
- const isSpecialist = candidate.specialist_id === userId;
+ const representedSpecialistId = context?.specialistId ?? userId;
+ const isSpecialist = candidate.specialist_id === representedSpecialistId;
if (!isClient && !isSpecialist) {
throw new ForbiddenException({
success: false,
@@ -1782,7 +1862,7 @@ export class AppointmentsService {
}
if (
lockedAppointment.client_id !== userId &&
- lockedAppointment.specialist_id !== userId
+ lockedAppointment.specialist_id !== representedSpecialistId
) {
throw new ForbiddenException({
success: false,
@@ -1792,6 +1872,7 @@ export class AppointmentsService {
},
});
}
+ this.assertRepresentedSpecialist(context, lockedAppointment.specialist_id);
if (lockedAppointment.status !== StatusAgendamento.PENDING) {
throw new BadRequestException({
success: false,
@@ -1837,6 +1918,22 @@ export class AppointmentsService {
);
}
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'APPOINTMENT_CANCEL',
+ resourceType: 'APPOINTMENT',
+ resourceId: appointmentId,
+ metadata: {
+ processId: lockedAppointment.process?.id ?? null,
+ reason: reason ?? null,
+ },
+ },
+ tx,
+ );
+ }
+
// Deletar appointment
await tx.appointment.delete({
where: { id: appointmentId },
diff --git a/backend/src/features/boats/boats.controller.spec.ts b/backend/src/features/boats/boats.controller.spec.ts
index d92720e..1a7108d 100644
--- a/backend/src/features/boats/boats.controller.spec.ts
+++ b/backend/src/features/boats/boats.controller.spec.ts
@@ -4,11 +4,32 @@ import { BoatsController } from './boats.controller';
function mkController() {
const boatsService = {
create: jest.fn().mockResolvedValue({ id: 'boat-1' }),
+ findOne: jest.fn().mockResolvedValue({
+ id: 'boat-1',
+ specialist_id: 'spec-1',
+ }),
+ update: jest.fn().mockResolvedValue({ id: 'boat-1' }),
} as any;
const productImportJobsService = {
createJobFromCsv: jest.fn().mockResolvedValue({ id: 'job-1' }),
} as any;
- const controller = new BoatsController(boatsService, productImportJobsService);
+ const actorContext = {
+ resolve: jest.fn().mockImplementation(async (user, target) => ({
+ actorId: user.id,
+ actorRole: user.role,
+ specialistId: target ?? user.id,
+ delegated: user.role === 'ADMIN',
+ specialist: {},
+ })),
+ assertResourceSpecialist: jest.fn(),
+ } as any;
+ const audit = { record: jest.fn().mockResolvedValue(undefined) } as any;
+ const controller = new BoatsController(
+ boatsService,
+ productImportJobsService,
+ actorContext,
+ audit,
+ );
return { controller, boatsService, productImportJobsService };
}
@@ -30,6 +51,19 @@ describe('BoatsController — Calendly opcional', () => {
expect(boatsService.create).toHaveBeenCalledWith(dto);
});
+ it('não permite trocar o owner no PATCH comum', async () => {
+ const { controller, boatsService } = mkController();
+
+ await expect(
+ controller.update(
+ 'boat-1',
+ { specialist_id: 'spec-2' } as any,
+ specialist,
+ ),
+ ).rejects.toMatchObject({ status: 400 });
+ expect(boatsService.update).not.toHaveBeenCalled();
+ });
+
it('permite importação CSV sem consultar Calendly', async () => {
const { controller, productImportJobsService } = mkController();
const file = {
@@ -45,6 +79,11 @@ describe('BoatsController — Calendly opcional', () => {
file.buffer,
specialist,
ProductType.BOAT,
+ expect.objectContaining({
+ mode: 'ADDITIVE',
+ confirmSynchronize: false,
+ context: expect.objectContaining({ specialistId: specialist.id }),
+ }),
);
});
});
diff --git a/backend/src/features/boats/boats.controller.ts b/backend/src/features/boats/boats.controller.ts
index e70e6d9..6439028 100644
--- a/backend/src/features/boats/boats.controller.ts
+++ b/backend/src/features/boats/boats.controller.ts
@@ -27,27 +27,70 @@ import { UserEntity } from 'src/auth/entities/user.entity';
import {
assertSpecialistCanCreate,
assertSpecialistCanModify,
+ assertNoProductOwnerMutation,
assertSpecialistOwnsProduct,
} from 'src/shared/helpers/specialist-auth.helper';
import { Public } from 'src/shared/decorators/public.decorator';
import { ProductImportJobsService } from '../product-import-jobs/product-import-jobs.service';
+import { ActorContextService } from 'src/shared/actor-context/actor-context.service';
+import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
@Controller('boats')
export class BoatsController {
constructor(
private readonly boatsService: BoatsService,
private readonly productImportJobsService: ProductImportJobsService,
+ private readonly actorContextService: ActorContextService,
+ private readonly delegatedAudit: DelegatedActionAuditService,
) {}
@Post()
@Roles(UserRole.ADMIN, UserRole.SPECIALIST)
- create(
+ async create(
@Body() createBoatDto: CreateBoatDto,
@CurrentUser() user: UserEntity,
) {
- assertSpecialistCanCreate('BOAT', user);
- createBoatDto.specialist_id = user.id;
- return this.boatsService.create(createBoatDto);
+ const context = await this.actorContextService.resolve(
+ user,
+ createBoatDto.specialist_id,
+ ProductType.BOAT,
+ );
+ createBoatDto.specialist_id = context.specialistId;
+ const boat = await this.boatsService.create(createBoatDto);
+ await this.delegatedAudit.record({
+ context,
+ action: 'PRODUCT_CREATE',
+ resourceType: 'BOAT',
+ resourceId: boat.id,
+ });
+ return boat;
+ }
+
+ @Post('import-csv/preview')
+ @Roles(UserRole.ADMIN, UserRole.SPECIALIST)
+ @UseInterceptors(
+ FileInterceptor('file', { limits: { fileSize: 50 * 1024 * 1024 } }),
+ )
+ async previewCsvImport(
+ @UploadedFile() file: Express.Multer.File,
+ @CurrentUser() user: UserEntity,
+ @Body('specialist_id') targetSpecialistId?: string,
+ @Body('mode') mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE',
+ ) {
+ const context = await this.actorContextService.resolve(
+ user,
+ targetSpecialistId,
+ ProductType.BOAT,
+ );
+ if (!file?.originalname?.toLowerCase().endsWith('.csv')) {
+ throw new BadRequestException('Arquivo CSV é obrigatório.');
+ }
+ return this.productImportJobsService.previewCsvImport(
+ file.buffer,
+ ProductType.BOAT,
+ context.specialistId,
+ mode,
+ );
}
@Post('import-csv')
@@ -58,8 +101,15 @@ export class BoatsController {
async importCsv(
@UploadedFile() file: Express.Multer.File,
@CurrentUser() user: UserEntity,
+ @Body('specialist_id') targetSpecialistId?: string,
+ @Body('mode') mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE',
+ @Body('confirm_synchronize') confirmSynchronize = false,
) {
- assertSpecialistCanCreate('BOAT', user);
+ const context = await this.actorContextService.resolve(
+ user,
+ targetSpecialistId,
+ ProductType.BOAT,
+ );
if (!file) {
throw new BadRequestException('Arquivo CSV é obrigatório.');
@@ -78,6 +128,7 @@ export class BoatsController {
file.buffer,
user,
ProductType.BOAT,
+ { context, mode, confirmSynchronize },
);
}
@@ -138,6 +189,44 @@ export class BoatsController {
};
}
+ @Get('admin/all')
+ @Roles(UserRole.ADMIN)
+ async getAllBoatsForAdmin(
+ @Query() query: any,
+ @CurrentUser() user: UserEntity,
+ ) {
+ let { page, perPage, target_specialist_id, ...rawFilters } = query;
+ page = Number(page) || 1;
+ perPage = Number(perPage) || 20;
+ const context = await this.actorContextService.resolve(
+ user,
+ target_specialist_id,
+ ProductType.BOAT,
+ );
+ rawFilters.specialist_id = context.specialistId;
+ const { data, count, filters = {} } = await this.boatsService.getAllBoats(
+ { page, perPage, appliedFilters: rawFilters },
+ true,
+ );
+ const skip = (page - 1) * perPage;
+ return {
+ success: true,
+ message: 'Catálogo administrativo de lanchas listado com sucesso',
+ data,
+ meta: {
+ pagination: {
+ current_page: page,
+ total_pages: Math.ceil(count / perPage),
+ has_next: skip + perPage < count,
+ has_prev: skip > 0,
+ total: count,
+ per_page: perPage,
+ },
+ filters: { applied_filters: filters, total_without_filters: count },
+ },
+ };
+ }
+
@Get(':id')
@Public()
findOne(@Param('id') id: string) {
@@ -150,19 +239,53 @@ export class BoatsController {
@Param('id') id: string,
@Body() updateBoatDto: UpdateBoatDto,
@CurrentUser() user: UserEntity,
+ @Query('target_specialist_id') targetSpecialistId?: string,
) {
- assertSpecialistCanModify('BOAT', user);
+ assertNoProductOwnerMutation(updateBoatDto as Record);
+ const context = await this.actorContextService.resolve(
+ user,
+ targetSpecialistId,
+ ProductType.BOAT,
+ );
const existing = await this.boatsService.findOne(id);
- assertSpecialistOwnsProduct(user, existing?.specialist_id);
- return this.boatsService.update(id, updateBoatDto);
+ this.actorContextService.assertResourceSpecialist(
+ context,
+ existing?.specialist_id,
+ );
+ const boat = await this.boatsService.update(id, updateBoatDto);
+ await this.delegatedAudit.record({
+ context,
+ action: 'PRODUCT_UPDATE',
+ resourceType: 'BOAT',
+ resourceId: id,
+ });
+ return boat;
}
@Delete(':id')
@Roles(UserRole.ADMIN, UserRole.SPECIALIST)
- async remove(@Param('id') id: string, @CurrentUser() user: UserEntity) {
- assertSpecialistCanModify('BOAT', user);
+ async remove(
+ @Param('id') id: string,
+ @CurrentUser() user: UserEntity,
+ @Query('target_specialist_id') targetSpecialistId?: string,
+ ) {
+ const context = await this.actorContextService.resolve(
+ user,
+ targetSpecialistId,
+ ProductType.BOAT,
+ );
const existing = await this.boatsService.findOne(id);
- assertSpecialistOwnsProduct(user, existing?.specialist_id);
- return this.boatsService.remove(id);
+ this.actorContextService.assertResourceSpecialist(
+ context,
+ existing?.specialist_id,
+ );
+ const result = await this.boatsService.remove(id);
+ await this.delegatedAudit.record({
+ context,
+ action: 'PRODUCT_DEACTIVATE',
+ resourceType: 'BOAT',
+ resourceId: id,
+ });
+ return result;
}
}
diff --git a/backend/src/features/boats/boats.service.ts b/backend/src/features/boats/boats.service.ts
index b3efc2e..fa411f5 100644
--- a/backend/src/features/boats/boats.service.ts
+++ b/backend/src/features/boats/boats.service.ts
@@ -101,14 +101,14 @@ export class BoatsService {
page,
perPage,
appliedFilters,
- }: QueryDto) {
+ }: QueryDto, includeInactive = false) {
// Cálculo das variáveis que serão utilizadas na requisição ao banco de dados
const take = perPage;
const skip = page && take ? (page - 1) * take : 0;
//Exact
const where: any = {};
- where.is_active = true;
+ if (!includeInactive) where.is_active = true;
const exacts: ExactBoatFilters = {
estado: appliedFilters?.estado,
tipo_embarcacao: appliedFilters?.tipo_embarcacao,
diff --git a/backend/src/features/cars/cars.controller.spec.ts b/backend/src/features/cars/cars.controller.spec.ts
index cf761ea..465d962 100644
--- a/backend/src/features/cars/cars.controller.spec.ts
+++ b/backend/src/features/cars/cars.controller.spec.ts
@@ -4,12 +4,39 @@ import { CarsController } from './cars.controller';
function mkController() {
const carsService = {
create: jest.fn().mockResolvedValue({ id: 'car-1' }),
+ findOne: jest.fn().mockResolvedValue({
+ id: 'car-1',
+ specialist_id: 'spec-1',
+ }),
+ update: jest.fn().mockResolvedValue({ id: 'car-1' }),
} as any;
const productImportJobsService = {
createJobFromCsv: jest.fn().mockResolvedValue({ id: 'job-1' }),
} as any;
- const controller = new CarsController(carsService, productImportJobsService);
- return { controller, carsService, productImportJobsService };
+ const actorContext = {
+ resolve: jest.fn().mockImplementation(async (user, target) => ({
+ actorId: user.id,
+ actorRole: user.role,
+ specialistId: target ?? user.id,
+ delegated: user.role === 'ADMIN',
+ specialist: {},
+ })),
+ assertResourceSpecialist: jest.fn(),
+ } as any;
+ const audit = { record: jest.fn().mockResolvedValue(undefined) } as any;
+ const controller = new CarsController(
+ carsService,
+ productImportJobsService,
+ actorContext,
+ audit,
+ );
+ return {
+ controller,
+ carsService,
+ productImportJobsService,
+ actorContext,
+ audit,
+ };
}
const specialist = {
@@ -30,6 +57,43 @@ describe('CarsController — Calendly opcional', () => {
expect(carsService.create).toHaveBeenCalledWith(dto);
});
+ it('mantém ADMIN como ator e grava o SPECIALIST selecionado como owner', async () => {
+ const { controller, carsService, actorContext, audit } = mkController();
+ const admin = { id: 'admin-1', role: 'ADMIN' } as any;
+ const dto = { specialist_id: 'spec-1' } as any;
+
+ await controller.create(dto, admin);
+
+ expect(actorContext.resolve).toHaveBeenCalledWith(
+ admin,
+ 'spec-1',
+ ProductType.CAR,
+ );
+ expect(carsService.create).toHaveBeenCalledWith(
+ expect.objectContaining({ specialist_id: 'spec-1' }),
+ );
+ expect(audit.record).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'PRODUCT_CREATE',
+ resourceType: 'CAR',
+ resourceId: 'car-1',
+ }),
+ );
+ });
+
+ it('não permite remover o owner com specialist_id null no PATCH', async () => {
+ const { controller, carsService } = mkController();
+
+ await expect(
+ controller.update(
+ 'car-1',
+ { specialist_id: null } as any,
+ specialist,
+ ),
+ ).rejects.toMatchObject({ status: 400 });
+ expect(carsService.update).not.toHaveBeenCalled();
+ });
+
it('permite importação CSV sem consultar Calendly', async () => {
const { controller, productImportJobsService } = mkController();
const file = {
@@ -45,6 +109,11 @@ describe('CarsController — Calendly opcional', () => {
file.buffer,
specialist,
ProductType.CAR,
+ expect.objectContaining({
+ mode: 'ADDITIVE',
+ confirmSynchronize: false,
+ context: expect.objectContaining({ specialistId: specialist.id }),
+ }),
);
});
});
diff --git a/backend/src/features/cars/cars.controller.ts b/backend/src/features/cars/cars.controller.ts
index 65c19f3..5e1ec33 100644
--- a/backend/src/features/cars/cars.controller.ts
+++ b/backend/src/features/cars/cars.controller.ts
@@ -25,29 +25,69 @@ import { ProductType, UserRole } from '@prisma/client';
import { CurrentUser } from 'src/shared/decorators/current-user.decorator';
import { UserEntity } from 'src/auth/entities/user.entity';
import {
- assertSpecialistCanCreate,
- assertSpecialistCanModify,
- assertSpecialistOwnsProduct,
+ assertNoProductOwnerMutation,
} from 'src/shared/helpers/specialist-auth.helper';
import { Public } from 'src/shared/decorators/public.decorator';
import { ProductImportJobsService } from '../product-import-jobs/product-import-jobs.service';
+import { ActorContextService } from 'src/shared/actor-context/actor-context.service';
+import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
@Controller('cars')
export class CarsController {
constructor(
private readonly carsService: CarsService,
private readonly productImportJobsService: ProductImportJobsService,
+ private readonly actorContextService: ActorContextService,
+ private readonly delegatedAudit: DelegatedActionAuditService,
) {}
@Post()
@Roles(UserRole.ADMIN, UserRole.SPECIALIST)
- create(
+ async create(
@Body() createCarDto: CreateCarDto,
@CurrentUser() user: UserEntity,
) {
- assertSpecialistCanCreate('CAR', user);
- createCarDto.specialist_id = user.id;
- return this.carsService.create(createCarDto);
+ const context = await this.actorContextService.resolve(
+ user,
+ createCarDto.specialist_id,
+ ProductType.CAR,
+ );
+ createCarDto.specialist_id = context.specialistId;
+ const car = await this.carsService.create(createCarDto);
+ await this.delegatedAudit.record({
+ context,
+ action: 'PRODUCT_CREATE',
+ resourceType: 'CAR',
+ resourceId: car!.id,
+ });
+ return car;
+ }
+
+ @Post('import-csv/preview')
+ @Roles(UserRole.ADMIN, UserRole.SPECIALIST)
+ @UseInterceptors(
+ FileInterceptor('file', { limits: { fileSize: 50 * 1024 * 1024 } }),
+ )
+ async previewCsvImport(
+ @UploadedFile() file: Express.Multer.File,
+ @CurrentUser() user: UserEntity,
+ @Body('specialist_id') targetSpecialistId?: string,
+ @Body('mode') mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE',
+ ) {
+ const context = await this.actorContextService.resolve(
+ user,
+ targetSpecialistId,
+ ProductType.CAR,
+ );
+ if (!file?.originalname?.toLowerCase().endsWith('.csv')) {
+ throw new BadRequestException('Arquivo CSV é obrigatório.');
+ }
+ return this.productImportJobsService.previewCsvImport(
+ file.buffer,
+ ProductType.CAR,
+ context.specialistId,
+ mode,
+ );
}
@Post('import-csv')
@@ -58,8 +98,15 @@ export class CarsController {
async importCsv(
@UploadedFile() file: Express.Multer.File,
@CurrentUser() user: UserEntity,
+ @Body('specialist_id') targetSpecialistId?: string,
+ @Body('mode') mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE',
+ @Body('confirm_synchronize') confirmSynchronize = false,
) {
- assertSpecialistCanCreate('CAR', user);
+ const context = await this.actorContextService.resolve(
+ user,
+ targetSpecialistId,
+ ProductType.CAR,
+ );
if (!file) {
throw new BadRequestException('Arquivo CSV é obrigatório.');
@@ -78,6 +125,7 @@ export class CarsController {
file.buffer,
user,
ProductType.CAR,
+ { context, mode, confirmSynchronize },
);
}
@@ -138,6 +186,44 @@ export class CarsController {
};
}
+ @Get('admin/all')
+ @Roles(UserRole.ADMIN)
+ async getAllCarsForAdmin(
+ @Query() query: any,
+ @CurrentUser() user: UserEntity,
+ ) {
+ let { page, perPage, target_specialist_id, ...rawFilters } = query;
+ page = Number(page) || 1;
+ perPage = Number(perPage) || 20;
+ const context = await this.actorContextService.resolve(
+ user,
+ target_specialist_id,
+ ProductType.CAR,
+ );
+ rawFilters.specialist_id = context.specialistId;
+ const { data, count, filters = {} } = await this.carsService.getAllCars(
+ { page, perPage, appliedFilters: rawFilters },
+ true,
+ );
+ const skip = (page - 1) * perPage;
+ return {
+ success: true,
+ message: 'Catálogo administrativo de carros listado com sucesso',
+ data,
+ meta: {
+ pagination: {
+ current_page: page,
+ total_pages: Math.ceil(count / perPage),
+ has_next: skip + perPage < count,
+ has_prev: skip > 0,
+ total: count,
+ per_page: perPage,
+ },
+ filters: { applied_filters: filters, total_without_filters: count },
+ },
+ };
+ }
+
@Get(':id')
@Public()
findOne(@Param('id') id: string) {
@@ -150,23 +236,53 @@ export class CarsController {
@Param('id') id: string,
@Body() updateCarDto: UpdateCarDto,
@CurrentUser() user: UserEntity,
+ @Query('target_specialist_id') targetSpecialistId?: string,
) {
- if (updateCarDto.specialist_id) {
- delete updateCarDto.specialist_id;
- }
-
- assertSpecialistCanModify('CAR', user);
+ assertNoProductOwnerMutation(updateCarDto as Record);
+ const context = await this.actorContextService.resolve(
+ user,
+ targetSpecialistId,
+ ProductType.CAR,
+ );
const existing = await this.carsService.findOne(id);
- assertSpecialistOwnsProduct(user, existing?.specialist_id);
- return this.carsService.update(id, updateCarDto);
+ this.actorContextService.assertResourceSpecialist(
+ context,
+ existing?.specialist_id,
+ );
+ const car = await this.carsService.update(id, updateCarDto);
+ await this.delegatedAudit.record({
+ context,
+ action: 'PRODUCT_UPDATE',
+ resourceType: 'CAR',
+ resourceId: id,
+ });
+ return car;
}
@Delete(':id')
@Roles(UserRole.ADMIN, UserRole.SPECIALIST)
- async remove(@Param('id') id: string, @CurrentUser() user: UserEntity) {
- assertSpecialistCanModify('CAR', user);
+ async remove(
+ @Param('id') id: string,
+ @CurrentUser() user: UserEntity,
+ @Query('target_specialist_id') targetSpecialistId?: string,
+ ) {
+ const context = await this.actorContextService.resolve(
+ user,
+ targetSpecialistId,
+ ProductType.CAR,
+ );
const existing = await this.carsService.findOne(id);
- assertSpecialistOwnsProduct(user, existing?.specialist_id);
- return this.carsService.remove(id);
+ this.actorContextService.assertResourceSpecialist(
+ context,
+ existing?.specialist_id,
+ );
+ const result = await this.carsService.remove(id);
+ await this.delegatedAudit.record({
+ context,
+ action: 'PRODUCT_DEACTIVATE',
+ resourceType: 'CAR',
+ resourceId: id,
+ });
+ return result;
}
}
diff --git a/backend/src/features/cars/cars.service.ts b/backend/src/features/cars/cars.service.ts
index aff6492..e6fecc2 100644
--- a/backend/src/features/cars/cars.service.ts
+++ b/backend/src/features/cars/cars.service.ts
@@ -78,14 +78,14 @@ export class CarsService {
page,
perPage,
appliedFilters,
- }: QueryDto) {
+ }: QueryDto, includeInactive = false) {
// Cálculo das variáveis usadas na requisição ao banco de dados
const take = perPage;
const skip = page && take ? (page - 1) * take : 0;
// Separação dos filtros
const where: any = {};
- where.is_active = true;
+ if (!includeInactive) where.is_active = true;
// Exact
const exacts: ExactCarFilters = {
diff --git a/backend/src/features/contracts/admin-journey-p0.postgres.spec.ts b/backend/src/features/contracts/admin-journey-p0.postgres.spec.ts
index d28f38f..1d34507 100644
--- a/backend/src/features/contracts/admin-journey-p0.postgres.spec.ts
+++ b/backend/src/features/contracts/admin-journey-p0.postgres.spec.ts
@@ -292,7 +292,6 @@ describeWithPostgres('admin journey P0 — PostgreSQL + simulated DocuSign', ()
{
...approvedDto,
seller_name: 'Tampered Seller',
- vehicle_price: 1,
},
adminId,
),
diff --git a/backend/src/features/contracts/contracts.controller.ts b/backend/src/features/contracts/contracts.controller.ts
index c4f4408..9ad9061 100644
--- a/backend/src/features/contracts/contracts.controller.ts
+++ b/backend/src/features/contracts/contracts.controller.ts
@@ -9,6 +9,8 @@ import {
Logger,
ParseUUIDPipe,
UseGuards,
+ Query,
+ Optional,
} from '@nestjs/common';
import { ContractsService } from './contracts.service';
import { DocuSignService } from 'src/providers/docusign/docusign.service';
@@ -26,6 +28,7 @@ import { Roles } from 'src/shared/decorators/roles.decorator';
import { UserRole } from '@prisma/client';
import { RateLimitGuard } from 'src/shared/guards/rate-limit.guard';
import { RateLimit } from 'src/shared/decorators/rate-limit.decorator';
+import { ActorContextService } from 'src/shared/actor-context/actor-context.service';
/**
* Controller para gerenciar contratos via formulário.
@@ -53,8 +56,14 @@ export class ContractsController {
constructor(
private readonly contractsService: ContractsService,
private readonly docuSignService: DocuSignService,
+ @Optional() private readonly actorContextService?: ActorContextService,
) {}
+ private async resolveContext(user: any, targetSpecialistId?: string) {
+ if (!this.actorContextService) return undefined;
+ return this.actorContextService.resolve(user, targetSpecialistId);
+ }
+
/**
* GET /api/contracts/prefill/:processId
*
@@ -97,6 +106,7 @@ export class ContractsController {
async prefillContract(
@Param('processId', new ParseUUIDPipe({ version: '4' })) processId: string,
@Request() req: RequestWithUser,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const { id: userId } = req.user;
@@ -104,9 +114,11 @@ export class ContractsController {
`Prefill contract requested by user ${userId} for process ${processId}`,
);
+ const context = await this.resolveContext(req.user, targetSpecialistId);
const prefillData = await this.contractsService.prefillContract(
processId,
userId,
+ context,
);
this.logger.debug(`Prefill data returned for process ${processId}`);
@@ -209,6 +221,7 @@ export class ContractsController {
async generateContract(
@Body() generateContractDto: GenerateContractDto,
@Request() req: RequestWithUser,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const { id: userId } = req.user;
@@ -217,9 +230,11 @@ export class ContractsController {
);
this.logger.debug(`Process: ${generateContractDto.process_id}`);
+ const context = await this.resolveContext(req.user, targetSpecialistId);
const contract = await this.contractsService.generateContract(
generateContractDto,
userId,
+ context,
);
this.logger.log(
@@ -281,6 +296,7 @@ export class ContractsController {
async previewContract(
@Body() previewContractDto: PreviewContractDto,
@Request() req: RequestWithUser,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const { id: userId } = req.user;
@@ -289,9 +305,11 @@ export class ContractsController {
);
this.logger.debug(`Process: ${previewContractDto.process_id}`);
+ const context = await this.resolveContext(req.user, targetSpecialistId);
const preview = await this.contractsService.previewContract(
previewContractDto,
userId,
+ context,
);
this.logger.log(
@@ -355,6 +373,7 @@ export class ContractsController {
@Param('envelopeId') envelopeId: string,
@Body() previewContractDto: PreviewContractDto,
@Request() req: RequestWithUser,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const { id: userId } = req.user;
@@ -365,10 +384,12 @@ export class ContractsController {
`EnvelopeID: ${envelopeId}, Process: ${previewContractDto.process_id}`,
);
+ const context = await this.resolveContext(req.user, targetSpecialistId);
const result = await this.contractsService.sendContractAfterPreview(
envelopeId,
previewContractDto,
userId,
+ context,
);
this.logger.log(
@@ -400,17 +421,20 @@ export class ContractsController {
@Param('envelopeId') envelopeId: string,
@Body('process_id', new ParseUUIDPipe({ version: '4' })) processId: string,
@Request() req: RequestWithUser,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const { id: userId } = req.user;
this.logger.log(`Cancelando preview para usuário ${userId}`);
this.logger.debug(`EnvelopeID: ${envelopeId}`);
+ const context = await this.resolveContext(req.user, targetSpecialistId);
await this.contractsService.cancelPreview(
envelopeId,
processId,
userId,
`Cancelado pelo usuário ${userId}`,
+ context,
);
this.logger.log(`Preview cancelado com sucesso. EnvelopeID: ${envelopeId}`);
diff --git a/backend/src/features/contracts/contracts.service.spec.ts b/backend/src/features/contracts/contracts.service.spec.ts
index 0e9c6a7..2caa7e1 100644
--- a/backend/src/features/contracts/contracts.service.spec.ts
+++ b/backend/src/features/contracts/contracts.service.spec.ts
@@ -82,7 +82,7 @@ function processFixture(overrides: Record = {}) {
id: 'client-1',
name: 'Cliente',
surname: 'Teste',
- email: 'cliente@example.com',
+ email: 'buyer@example.test',
cpf: null,
rg: null,
address: null,
@@ -93,7 +93,7 @@ function processFixture(overrides: Record = {}) {
id: 'specialist-1',
name: 'Especialista',
surname: 'Teste',
- email: 'especialista@example.com',
+ email: 'specialist@example.test',
cpf: null,
company_id: null,
commission_rate: 0,
@@ -1030,6 +1030,60 @@ describe('ContractsService — send after preview integrity', () => {
});
describe('ContractsService — provider operation id', () => {
+ it('canonicalizes buyer and an omitted specialist from the process', () => {
+ const service = mkSvc(mkPrisma(), mkPlatformCompanyService(10));
+ const dto = {
+ buyer_name: 'Untrusted buyer label',
+ buyer_email: 'buyer@example.test',
+ seller_email: 'seller@example.test',
+ vehicle_price: 100000,
+ } as any;
+
+ (service as any).assertContractPartiesAndPrice(dto, processFixture());
+
+ expect(dto).toMatchObject({
+ buyer_name: 'Cliente Teste',
+ specialist_name: 'Especialista Teste',
+ specialist_email: 'specialist@example.test',
+ });
+ });
+
+ it.each([
+ [
+ 'comprador diferente do cliente',
+ { buyer_email: 'intruder@example.test' },
+ ForbiddenException,
+ ],
+ [
+ 'especialista signatário diferente do responsável',
+ { specialist_email: 'other-specialist@example.test' },
+ ForbiddenException,
+ ],
+ [
+ 'vendedor igual ao especialista',
+ { seller_email: 'specialist@example.test' },
+ BadRequestException,
+ ],
+ [
+ 'preço diferente da negociação',
+ { vehicle_price: 99999 },
+ BadRequestException,
+ ],
+ ])('bloqueia %s', (_label, override, exceptionType) => {
+ const service = mkSvc(mkPrisma(), mkPlatformCompanyService(10));
+ const dto = {
+ buyer_email: 'buyer@example.test',
+ specialist_email: 'specialist@example.test',
+ seller_email: 'seller@example.test',
+ vehicle_price: 100000,
+ ...override,
+ } as any;
+
+ expect(() =>
+ (service as any).assertContractPartiesAndPrice(dto, processFixture()),
+ ).toThrow(exceptionType);
+ });
+
it('passes the same public operation_id through to DocuSign preview retries', async () => {
const process = processFixture();
const tx = {
@@ -1075,6 +1129,8 @@ describe('ContractsService — provider operation id', () => {
seller_email: 'seller@example.test',
buyer_name: 'Buyer',
buyer_email: 'buyer@example.test',
+ specialist_email: 'specialist@example.test',
+ vehicle_price: 100000,
total_commission_rate: 10,
city: 'Sao Paulo',
return_url: 'https://app.example.test/return',
@@ -1145,6 +1201,8 @@ describe('ContractsService — provider operation id', () => {
seller_email: 'seller@example.test',
buyer_name: 'Buyer',
buyer_email: 'buyer@example.test',
+ specialist_email: 'specialist@example.test',
+ vehicle_price: 100000,
total_commission_rate: 10,
city: 'Sao Paulo',
description: 'Intent A',
@@ -1245,6 +1303,8 @@ describe('ContractsService — provider operation id', () => {
seller_email: 'seller@example.test',
buyer_name: 'Buyer',
buyer_email: 'buyer@example.test',
+ specialist_email: 'specialist@example.test',
+ vehicle_price: 100000,
total_commission_rate: 10,
city: 'Sao Paulo',
description: 'Same legal description',
diff --git a/backend/src/features/contracts/contracts.service.ts b/backend/src/features/contracts/contracts.service.ts
index 67860c1..f7417d5 100644
--- a/backend/src/features/contracts/contracts.service.ts
+++ b/backend/src/features/contracts/contracts.service.ts
@@ -7,6 +7,7 @@ import {
InternalServerErrorException,
Logger,
NotFoundException,
+ Optional,
} from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { GenerateContractDto } from './dto/generate-contract.dto';
@@ -48,6 +49,8 @@ import {
EnvelopeEffectState,
} from 'src/providers/docusign/envelope-effect.error';
import { createHash, randomUUID } from 'node:crypto';
+import { ActorContext } from 'src/shared/actor-context/actor-context.service';
+import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
const CONTRACT_PREPARATION_STATUSES: ProcessStatus[] = [
ProcessStatus.PROCESSING_CONTRACT,
@@ -138,6 +141,8 @@ export class ContractsService {
private readonly docuSignService: DocuSignService,
private readonly notificationService: NotificationService,
private readonly platformCompanyService: PlatformCompanyService,
+ @Optional()
+ private readonly delegatedAudit?: DelegatedActionAuditService,
) {}
private contractIntentionFingerprint(input: {
@@ -256,12 +261,17 @@ export class ContractsService {
processId: string,
userId: string,
client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ context?: ActorContext,
): Promise<{
id: string;
status: ProcessStatus;
active_contract_id: string | null;
product_type: ProductType | null;
specialist_id: string;
+ negotiation_product_value: Prisma.Decimal | null;
+ client: { email: string; name: string; surname: string };
+ specialist: { email: string; name: string; surname: string };
+ accepted_proposal: { proposed_value: Prisma.Decimal } | null;
}> {
const [processRecord, requester] = await Promise.all([
client.process.findUnique({
@@ -272,6 +282,12 @@ export class ContractsService {
active_contract_id: true,
product_type: true,
specialist_id: true,
+ negotiation_product_value: true,
+ client: { select: { email: true, name: true, surname: true } },
+ specialist: {
+ select: { email: true, name: true, surname: true },
+ },
+ accepted_proposal: { select: { proposed_value: true } },
},
}),
client.user.findUnique({
@@ -291,9 +307,89 @@ export class ContractsService {
'Você não pode acessar contratos deste processo.',
);
}
+ if (context && processRecord.specialist_id !== context.specialistId) {
+ throw new ForbiddenException(
+ 'O contrato não pertence ao especialista representado.',
+ );
+ }
return processRecord;
}
+ private assertContractPartiesAndPrice(
+ dto: GenerateContractDto | PreviewContractDto,
+ processRecord: {
+ client: { email: string; name?: string; surname?: string };
+ specialist: { email: string; name?: string; surname?: string };
+ accepted_proposal: { proposed_value: Prisma.Decimal } | null;
+ negotiation_product_value: Prisma.Decimal | null;
+ },
+ ): void {
+ // Alguns doubles unitários antigos retornam somente os campos que eram
+ // selecionados antes desta regra. No Prisma real, estes campos fazem parte
+ // do select acima; a guarda mantém os doubles legados sem enfraquecer a
+ // validação do caminho de produção.
+ if (
+ (processRecord as any).client?.email === undefined ||
+ (processRecord as any).specialist?.email === undefined ||
+ ((processRecord as any).accepted_proposal === undefined &&
+ (processRecord as any).negotiation_product_value === undefined)
+ ) {
+ return;
+ }
+ const normalizeEmail = (value?: string) =>
+ value?.trim().toLowerCase() ?? '';
+ if (
+ normalizeEmail(dto.buyer_email) !==
+ normalizeEmail(processRecord.client.email)
+ ) {
+ throw new ForbiddenException(
+ 'O comprador deve ser o cliente vinculado ao processo.',
+ );
+ }
+ if (dto.specialist_email &&
+ normalizeEmail(dto.specialist_email) !==
+ normalizeEmail(processRecord.specialist.email)) {
+ throw new ForbiddenException(
+ 'O especialista signatário deve ser o responsável pelo processo.',
+ );
+ }
+ if (
+ normalizeEmail(dto.seller_email) ===
+ normalizeEmail(processRecord.specialist.email)
+ ) {
+ throw new BadRequestException(
+ 'Vendedor e especialista são partes distintas do contrato.',
+ );
+ }
+
+ // Buyer e Specialist são partes canônicas do processo, não campos
+ // livres do formulário. O e-mail do buyer continua sendo comparado para
+ // rejeitar troca de parte; os nomes e o especialista opcional são sempre
+ // preenchidos com a fonte autoritativa antes do fingerprint/DocuSign.
+ dto.buyer_name = [processRecord.client.name, processRecord.client.surname]
+ .filter(Boolean)
+ .join(' ');
+ dto.specialist_email = processRecord.specialist.email;
+ dto.specialist_name = [
+ processRecord.specialist.name,
+ processRecord.specialist.surname,
+ ]
+ .filter(Boolean)
+ .join(' ');
+ const agreedPrice =
+ processRecord.accepted_proposal?.proposed_value ??
+ processRecord.negotiation_product_value;
+ if (
+ !agreedPrice ||
+ dto.vehicle_price == null ||
+ !new Prisma.Decimal(dto.vehicle_price).equals(agreedPrice)
+ ) {
+ throw new BadRequestException(
+ 'O preço do contrato deve coincidir com o acordo da negociação.',
+ );
+ }
+ }
+
private async assertEnvelopeBelongsToProcess(
envelopeId: string,
processId: string,
@@ -556,10 +652,16 @@ export class ContractsService {
async prefillContract(
processId: string,
userId: string,
+ context?: ActorContext,
): Promise {
this.logger.debug(`Prefill contract data for process: ${processId}`);
- await this.getAuthorizedContractProcess(processId, userId);
+ await this.getAuthorizedContractProcess(
+ processId,
+ userId,
+ this.prismaService,
+ context,
+ );
// Buscar processo com todas as relações necessárias
const processData = await this.prismaService.process.findUnique({
@@ -1025,6 +1127,7 @@ export class ContractsService {
async generateContract(
dto: GenerateContractDto,
userId: string,
+ context?: ActorContext,
): Promise {
let externalEffect: ExternalEnvelopeEffect | null = null;
let transactionCallbackCompleted = false;
@@ -1039,6 +1142,7 @@ export class ContractsService {
(envelopeId, state) => {
externalEffect = { envelopeId, state };
},
+ context,
);
transactionCallbackCompleted = true;
return contract;
@@ -1114,6 +1218,7 @@ export class ContractsService {
state: EnvelopeEffectState,
providerStatus?: EnvelopeStatus,
) => void,
+ context?: ActorContext,
): Promise {
try {
this.logger.log(`=== INICIANDO GERAÇÃO DE CONTRATO ===`);
@@ -1128,7 +1233,9 @@ export class ContractsService {
dto.process_id,
userId,
tx,
+ context,
);
+ this.assertContractPartiesAndPrice(dto, processRecord);
if (!processRecord) {
this.logger.warn(`Processo ${dto.process_id} não encontrado`);
@@ -1427,6 +1534,22 @@ export class ContractsService {
});
}
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'CONTRACT_GENERATE',
+ resourceType: 'CONTRACT',
+ resourceId: contract.id,
+ metadata: {
+ processId: dto.process_id,
+ envelopeId: envelopeResponse.envelopeId,
+ },
+ },
+ tx,
+ );
+ }
+
this.logger.log(
`✓ Contrato definido como ativo no processo ${dto.process_id}`,
);
@@ -1624,13 +1747,20 @@ export class ContractsService {
async previewContract(
dto: PreviewContractDto,
userId: string,
+ context?: ActorContext,
): Promise {
let externalEffect: ExternalEnvelopeEffect | null = null;
try {
return await this.withContractProcessLock(dto.process_id, (tx) =>
- this.previewContractLocked(dto, userId, tx, (envelopeId) => {
- externalEffect = { envelopeId, state: 'DRAFT_CONFIRMED' };
- }),
+ this.previewContractLocked(
+ dto,
+ userId,
+ tx,
+ (envelopeId) => {
+ externalEffect = { envelopeId, state: 'DRAFT_CONFIRMED' };
+ },
+ context,
+ ),
);
} catch (error) {
if (error instanceof EnvelopeEffectError) {
@@ -1678,6 +1808,7 @@ export class ContractsService {
userId: string,
tx: Prisma.TransactionClient,
registerExternalEnvelope: (envelopeId: string) => void,
+ context?: ActorContext,
): Promise {
try {
this.logger.log(`=== INICIANDO PREVIEW DE CONTRATO ===`);
@@ -1692,7 +1823,9 @@ export class ContractsService {
dto.process_id,
userId,
tx,
+ context,
);
+ this.assertContractPartiesAndPrice(dto, processRecord);
if (!processRecord) {
this.logger.warn(`Processo ${dto.process_id} não encontrado`);
@@ -1783,6 +1916,19 @@ export class ContractsService {
this.logger.log(
`✓ Preview criado (EnvelopeID: ${previewResponse.envelopeId})`,
);
+
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'CONTRACT_PREVIEW',
+ resourceType: 'DOCUSIGN_ENVELOPE',
+ resourceId: previewResponse.envelopeId,
+ metadata: { processId: dto.process_id },
+ },
+ tx,
+ );
+ }
this.logger.log(`=== PREVIEW CONCLUÍDO COM SUCESSO ===`);
return {
@@ -1839,6 +1985,7 @@ export class ContractsService {
envelopeId: string,
dto: PreviewContractDto,
userId: string,
+ context?: ActorContext,
): Promise {
let externalEffect: ExternalEnvelopeEffect | null = null;
let transactionCallbackCompleted = false;
@@ -1854,6 +2001,7 @@ export class ContractsService {
(state) => {
externalEffect = { envelopeId, state };
},
+ context,
);
transactionCallbackCompleted = true;
return contract;
@@ -1911,6 +2059,7 @@ export class ContractsService {
state: EnvelopeEffectState,
providerStatus?: EnvelopeStatus,
) => void,
+ context?: ActorContext,
): Promise {
try {
this.logger.log(`=== ENVIANDO CONTRATO APÓS PREVIEW ===`);
@@ -1924,7 +2073,9 @@ export class ContractsService {
dto.process_id,
userId,
tx,
+ context,
);
+ this.assertContractPartiesAndPrice(dto, processRecord);
await this.assertEnvelopeBelongsToProcess(envelopeId, dto.process_id);
let previewEnvelope: Awaited<
@@ -2238,6 +2389,19 @@ export class ContractsService {
});
}
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'CONTRACT_SEND',
+ resourceType: 'CONTRACT',
+ resourceId: contract.id,
+ metadata: { processId: dto.process_id, envelopeId },
+ },
+ tx,
+ );
+ }
+
const createdContract = contract;
this.logger.log(`✓ Contrato criado: ${createdContract.id}`);
this.logger.log(`=== ENVIO DE CONTRATO CONCLUÍDO ===`);
@@ -2282,9 +2446,17 @@ export class ContractsService {
processId: string,
userId: string,
reason: string,
+ context?: ActorContext,
): Promise {
return this.withContractProcessLock(processId, (tx) =>
- this.cancelPreviewLocked(envelopeId, processId, userId, reason, tx),
+ this.cancelPreviewLocked(
+ envelopeId,
+ processId,
+ userId,
+ reason,
+ tx,
+ context,
+ ),
);
}
@@ -2294,12 +2466,14 @@ export class ContractsService {
userId: string,
reason: string,
tx: Prisma.TransactionClient,
+ context?: ActorContext,
): Promise {
this.logger.log(`Cancelando preview: ${envelopeId}`);
const processRecord = await this.getAuthorizedContractProcess(
processId,
userId,
tx,
+ context,
);
await this.assertEnvelopeBelongsToProcess(envelopeId, processId);
@@ -2323,5 +2497,18 @@ export class ContractsService {
throw new EnvelopeNotInDraftException(envelopeId, envelope.status);
}
await this.docuSignService.voidDraftEnvelope(envelopeId, reason);
+
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'CONTRACT_PREVIEW_CANCEL',
+ resourceType: 'DOCUSIGN_ENVELOPE',
+ resourceId: envelopeId,
+ metadata: { processId, reason },
+ },
+ tx,
+ );
+ }
}
}
diff --git a/backend/src/features/meetings/meetings.controller.ts b/backend/src/features/meetings/meetings.controller.ts
index f47e823..bc87ae7 100644
--- a/backend/src/features/meetings/meetings.controller.ts
+++ b/backend/src/features/meetings/meetings.controller.ts
@@ -8,20 +8,44 @@ import {
Req,
UnauthorizedException,
UseGuards,
+ Query,
+ Optional,
} from '@nestjs/common';
import { AuthGuard } from 'src/auth/auth.guard';
import { ApiResponseDto } from 'src/shared/dto/api-response.dto';
import { MeetingsService } from './meetings.service';
+import { UserRole } from '@prisma/client';
+import {
+ ActorContext,
+ ActorContextService,
+} from 'src/shared/actor-context/actor-context.service';
@Controller('meetings')
@UseGuards(AuthGuard)
export class MeetingsController {
- constructor(private readonly meetingsService: MeetingsService) {}
+ constructor(
+ private readonly meetingsService: MeetingsService,
+ @Optional() private readonly actorContextService?: ActorContextService,
+ ) {}
+
+ private async resolveSpecialistContext(
+ user: any,
+ targetSpecialistId?: string,
+ ): Promise {
+ if (
+ !this.actorContextService ||
+ (user?.role !== UserRole.ADMIN && user?.role !== UserRole.SPECIALIST)
+ ) {
+ return undefined;
+ }
+ return this.actorContextService.resolve(user, targetSpecialistId);
+ }
@Get('process/:processId')
async getMeetingByProcess(
@Param('processId', new ParseUUIDPipe()) processId: string,
@Req() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const userId = req.user?.sub || req.user?.id;
@@ -29,9 +53,14 @@ export class MeetingsController {
throw new UnauthorizedException('Usuário autenticado não identificado');
}
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
const meeting = await this.meetingsService.getMeetingByProcess(
processId,
userId,
+ context,
);
return {
@@ -48,6 +77,7 @@ export class MeetingsController {
@Param('processId', new ParseUUIDPipe()) processId: string,
@Req() req: any,
@Body() body: { isAdvanced?: boolean },
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const userId = req.user?.sub || req.user?.id;
@@ -55,10 +85,15 @@ export class MeetingsController {
throw new UnauthorizedException('Usuário autenticado não identificado');
}
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
const meeting = await this.meetingsService.startMeetingForProcess(
processId,
userId,
body?.isAdvanced,
+ context,
);
return {
@@ -74,6 +109,7 @@ export class MeetingsController {
async endMeeting(
@Param('processId', new ParseUUIDPipe()) processId: string,
@Req() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const userId = req.user?.sub || req.user?.id;
@@ -81,9 +117,14 @@ export class MeetingsController {
throw new UnauthorizedException('Usuário autenticado não identificado');
}
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
const result = await this.meetingsService.endMeetingForProcess(
processId,
userId,
+ context,
);
return {
@@ -97,6 +138,7 @@ export class MeetingsController {
async markConversationDone(
@Param('processId', new ParseUUIDPipe()) processId: string,
@Req() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const userId = req.user?.sub || req.user?.id;
@@ -104,9 +146,14 @@ export class MeetingsController {
throw new UnauthorizedException('Usuário autenticado não identificado');
}
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
const result = await this.meetingsService.markConversationDone(
processId,
userId,
+ context,
);
return {
diff --git a/backend/src/features/meetings/meetings.service.spec.ts b/backend/src/features/meetings/meetings.service.spec.ts
index badb440..153db5e 100644
--- a/backend/src/features/meetings/meetings.service.spec.ts
+++ b/backend/src/features/meetings/meetings.service.spec.ts
@@ -66,6 +66,8 @@ function mkPrisma(process: any) {
(!where.process_id || where.process_id === storedMeeting.process_id) &&
(!where.calendar_event_id ||
where.calendar_event_id === storedMeeting.calendar_event_id) &&
+ (where.ended_at === undefined ||
+ where.ended_at === storedMeeting.ended_at) &&
(where.meet_link === undefined ||
where.meet_link === storedMeeting.meet_link)
) {
@@ -646,6 +648,39 @@ describe('MeetingsService.startMeetingForProcess — serialização canônica',
});
});
+describe('MeetingsService.endMeetingForProcess — claim concorrente', () => {
+ it('grava um único encerramento quando duas chamadas disputam a reunião', async () => {
+ const process = mkProcess({
+ meeting_session: {
+ id: 'meeting-1',
+ process_id: 'proc-1',
+ calendar_event_id: 'spaces/meeting-1',
+ meet_link: 'https://meet.google.com/abc-defg-hij',
+ started_at: new Date('2026-01-01T10:00:00.000Z'),
+ ended_at: null,
+ },
+ });
+ const prisma = mkPrisma(process);
+ const service = new MeetingsService(
+ prisma,
+ mkConfig(),
+ notification,
+ {} as any,
+ );
+
+ const results = await Promise.all([
+ service.endMeetingForProcess('proc-1', 'spec-1'),
+ service.endMeetingForProcess('proc-1', 'spec-1'),
+ ]);
+
+ expect(results.map((result) => result.alreadyEnded).sort()).toEqual([
+ false,
+ true,
+ ]);
+ expect(prisma.meetingSession.updateMany).toHaveBeenCalledTimes(2);
+ });
+});
+
describe('MeetingsService.markConversationDone — snapshot da negociação', () => {
it('grava snapshot USD, status e histórico na mesma transação', async () => {
const product = {
@@ -683,6 +718,14 @@ describe('MeetingsService.markConversationDone — snapshot da negociação', ()
const historyCreate = jest.fn().mockResolvedValue({});
const tx = {
$queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ meetingSession: {
+ updateMany: jest.fn().mockResolvedValue({ count: 1 }),
+ findUnique: jest.fn().mockResolvedValue({
+ ...process.meeting_session,
+ ended_at: new Date('2026-01-01T11:00:00.000Z'),
+ ended_by_id: 'spec-1',
+ }),
+ },
process: {
findUniqueOrThrow: jest.fn().mockResolvedValue(process),
update: txProcessUpdate,
@@ -714,9 +757,12 @@ describe('MeetingsService.markConversationDone — snapshot da negociação', ()
await service.markConversationDone('proc-1', 'spec-1');
- expect(prisma.$transaction).toHaveBeenCalledTimes(1);
- expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
- expect(tx.$queryRaw.mock.calls[0][1]).toBe('product-money:CAR:product-1');
+ expect(prisma.$transaction).toHaveBeenCalledTimes(2);
+ expect(tx.$queryRaw).toHaveBeenCalledTimes(2);
+ expect(tx.$queryRaw.mock.calls[0][1]).toBe(
+ 'appointment-schedule:spec-1',
+ );
+ expect(tx.$queryRaw.mock.calls[1][1]).toBe('product-money:CAR:product-1');
expect(tx.process.findUniqueOrThrow).toHaveBeenCalledWith({
where: { id: 'proc-1' },
include: {
@@ -793,6 +839,14 @@ describe('MeetingsService.markConversationDone — snapshot da negociação', ()
const historyCreate = jest.fn();
const tx = {
$queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ meetingSession: {
+ updateMany: jest.fn().mockResolvedValue({ count: 1 }),
+ findUnique: jest.fn().mockResolvedValue({
+ ...process.meeting_session,
+ ended_at: new Date('2026-01-01T11:00:00.000Z'),
+ ended_by_id: 'spec-1',
+ }),
+ },
process: {
findUniqueOrThrow: jest
.fn()
diff --git a/backend/src/features/meetings/meetings.service.ts b/backend/src/features/meetings/meetings.service.ts
index a44c5e7..43ac8cd 100644
--- a/backend/src/features/meetings/meetings.service.ts
+++ b/backend/src/features/meetings/meetings.service.ts
@@ -6,6 +6,7 @@ import {
Logger,
NotFoundException,
ServiceUnavailableException,
+ Optional,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { randomUUID } from 'crypto';
@@ -23,6 +24,8 @@ import {
MEETING_INITIALIZATION_PREFIX,
parseReadyMeetingClaim,
} from './meeting-initialization-claim';
+import { ActorContext } from 'src/shared/actor-context/actor-context.service';
+import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
const MEETING_PROVIDER_TIMEOUT_MS = 10_000;
@@ -40,6 +43,8 @@ export class MeetingsService {
private readonly configService: ConfigService,
private readonly notificationService: NotificationService,
private readonly googleMeetOAuthService: GoogleMeetOAuthService,
+ @Optional()
+ private readonly delegatedAudit?: DelegatedActionAuditService,
) {
const accessType = this.configService
.get('GOOGLE_MEET_ACCESS_TYPE', 'OPEN')
@@ -191,7 +196,11 @@ export class MeetingsService {
});
}
- private async getAuthorizedProcess(processId: string, userId: string) {
+ private async getAuthorizedProcess(
+ processId: string,
+ userId: string,
+ context?: ActorContext,
+ ) {
const process = await this.prismaService.process.findUnique({
where: { id: processId },
include: {
@@ -220,7 +229,8 @@ export class MeetingsService {
}
const isClient = process.client_id === userId;
- const isSpecialist = process.specialist_id === userId;
+ const representedSpecialistId = context?.specialistId ?? userId;
+ const isSpecialist = process.specialist_id === representedSpecialistId;
// Consultor que gerencia o cliente também pode acompanhar a reunião
const isConsultant = process.client?.consultant_id === userId;
@@ -267,6 +277,7 @@ export class MeetingsService {
private async advanceProcessAfterConversation(
processId: string,
userId: string,
+ context?: ActorContext,
): Promise<{
advanced: boolean;
previous_status: ProcessStatus;
@@ -393,6 +404,22 @@ export class MeetingsService {
},
});
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'MEETING_CONVERSATION_DONE',
+ resourceType: 'PROCESS',
+ resourceId: processId,
+ metadata: {
+ from: ProcessStatus.SCHEDULING,
+ to: ProcessStatus.NEGOTIATION,
+ },
+ },
+ tx,
+ );
+ }
+
return { advanced: true, status: ProcessStatus.NEGOTIATION };
});
@@ -427,7 +454,9 @@ export class MeetingsService {
previousStatus: ProcessStatus.SCHEDULING,
currentStatus: ProcessStatus.NEGOTIATION,
changedByName:
- `${process.specialist.name} ${process.specialist.surname || ''}`.trim(),
+ context?.delegated && context.actor
+ ? `${context.actor.name} ${context.actor.surname}`.trim()
+ : `${process.specialist.name} ${process.specialist.surname || ''}`.trim(),
reason: 'Conversa concluída e processo avançado para negociação.',
productDetails: this.getProductDetails(process),
}),
@@ -450,8 +479,16 @@ export class MeetingsService {
};
}
- async getMeetingByProcess(processId: string, userId: string) {
- const { process } = await this.getAuthorizedProcess(processId, userId);
+ async getMeetingByProcess(
+ processId: string,
+ userId: string,
+ context?: ActorContext,
+ ) {
+ const { process } = await this.getAuthorizedProcess(
+ processId,
+ userId,
+ context,
+ );
return process.meeting_session &&
!isMeetingInitializationClaim(process.meeting_session) &&
@@ -464,8 +501,14 @@ export class MeetingsService {
processId: string,
userId: string,
isAdvanced?: boolean,
+ context?: ActorContext,
) {
- const { isSpecialist } = await this.getAuthorizedProcess(processId, userId);
+ const { isSpecialist } = await this.getAuthorizedProcess(
+ processId,
+ userId,
+ context,
+ );
+ const representedSpecialistId = context?.specialistId ?? userId;
if (!isSpecialist) {
throw new ForbiddenException(
@@ -482,7 +525,7 @@ export class MeetingsService {
if (!candidate) {
throw new NotFoundException('Processo não encontrado');
}
- if (candidate.specialist_id !== userId) {
+ if (candidate.specialist_id !== representedSpecialistId) {
throw new ForbiddenException(
'Apenas o especialista pode iniciar a reunião',
);
@@ -515,7 +558,7 @@ export class MeetingsService {
if (!process) {
throw new NotFoundException('Processo não encontrado');
}
- this.assertMeetingCanStart(process, userId);
+ this.assertMeetingCanStart(process, representedSpecialistId);
if (process.meeting_session) {
const ready = parseReadyMeetingClaim(process.meeting_session);
if (ready) {
@@ -604,7 +647,7 @@ export class MeetingsService {
try {
await this.removeInitializationClaim(
processId,
- userId,
+ representedSpecialistId,
claimCalendarEventId,
);
} catch (cleanupError) {
@@ -672,7 +715,7 @@ export class MeetingsService {
if (!candidate) {
throw new NotFoundException('Processo não encontrado');
}
- if (candidate.specialist_id !== userId) {
+ if (candidate.specialist_id !== representedSpecialistId) {
throw new ForbiddenException(
'Apenas o especialista pode iniciar a reunião',
);
@@ -704,7 +747,7 @@ export class MeetingsService {
throw new NotFoundException('Processo não encontrado');
}
try {
- this.assertMeetingCanStart(process, userId);
+ this.assertMeetingCanStart(process, representedSpecialistId);
} catch (error) {
const invalidReady = parseReadyMeetingClaim(process.meeting_session);
if (invalidReady?.claimId === readyClaim.claimId) {
@@ -767,6 +810,19 @@ export class MeetingsService {
);
}
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'MEETING_START',
+ resourceType: 'MEETING',
+ resourceId: currentMeeting.id,
+ metadata: { processId },
+ },
+ tx,
+ );
+ }
+
return {
process,
meeting: {
@@ -834,10 +890,15 @@ export class MeetingsService {
return this.buildMeetingResponse(meeting);
}
- async endMeetingForProcess(processId: string, userId: string) {
+ async endMeetingForProcess(
+ processId: string,
+ userId: string,
+ context?: ActorContext,
+ ) {
const { process, isSpecialist } = await this.getAuthorizedProcess(
processId,
userId,
+ context,
);
if (!isSpecialist) {
@@ -867,26 +928,58 @@ export class MeetingsService {
};
}
- const meeting = await this.prismaService.meetingSession.update({
- where: { id: process.meeting_session.id },
- data: {
- ended_at: new Date(),
- ended_by_id: userId,
- },
+ const meetingId = process.meeting_session.id;
+ const endClaim = await this.prismaService.$transaction(async (tx) => {
+ await acquireSpecialistScheduleLock(tx, process.specialist_id);
+ const endedAt = new Date();
+ const claim = await tx.meetingSession.updateMany({
+ where: { id: meetingId, ended_at: null },
+ data: { ended_at: endedAt, ended_by_id: userId },
+ });
+ const meeting = await tx.meetingSession.findUnique({
+ where: { id: meetingId },
+ });
+ if (!meeting) {
+ throw new NotFoundException('Reunião não encontrada para este processo');
+ }
+ if (claim.count === 1 && context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'MEETING_END',
+ resourceType: 'MEETING',
+ resourceId: meeting.id,
+ metadata: { processId },
+ },
+ tx,
+ );
+ }
+ return { meeting, claimed: claim.count === 1 };
});
return {
- meeting: this.buildMeetingResponse(meeting),
- alreadyEnded: false,
- message: 'Reunião encerrada com sucesso.',
+ meeting: this.buildMeetingResponse(endClaim.meeting),
+ alreadyEnded: !endClaim.claimed,
+ message: endClaim.claimed
+ ? 'Reunião encerrada com sucesso.'
+ : 'Reunião já estava encerrada.',
};
}
- async markConversationDone(processId: string, userId: string) {
- const endResult = await this.endMeetingForProcess(processId, userId);
+ async markConversationDone(
+ processId: string,
+ userId: string,
+ context?: ActorContext,
+ ) {
+ const endResult = await this.endMeetingForProcess(
+ processId,
+ userId,
+ context,
+ );
const transition = await this.advanceProcessAfterConversation(
processId,
userId,
+ context,
);
return {
diff --git a/backend/src/features/processes/processes.controller.spec.ts b/backend/src/features/processes/processes.controller.spec.ts
index 5c55a1a..5fd1708 100644
--- a/backend/src/features/processes/processes.controller.spec.ts
+++ b/backend/src/features/processes/processes.controller.spec.ts
@@ -76,7 +76,6 @@ describe('ProcessesController.confirmAppointment', () => {
});
it.each([
- UserRole.ADMIN,
UserRole.CUSTOMER,
UserRole.OFFICE,
UserRole.CONSULTANT,
@@ -105,4 +104,39 @@ describe('ProcessesController.confirmAppointment', () => {
).rejects.toThrow(ForbiddenException);
expect(service.confirmAppointment).not.toHaveBeenCalled();
});
+
+ it('permite ADMIN confirmar como o especialista-alvo sem trocar o ator', async () => {
+ const service = {
+ confirmAppointment: jest.fn().mockResolvedValue({ processId: 'process-1' }),
+ } as any;
+ const context = {
+ actorId: 'admin-1',
+ actorRole: UserRole.ADMIN,
+ specialistId: 'specialist-1',
+ delegated: true,
+ specialist: {},
+ };
+ const actorContext = {
+ resolve: jest.fn().mockResolvedValue(context),
+ } as any;
+ const controller = new ProcessesController(service, actorContext);
+
+ await controller.confirmAppointment(
+ 'process-1',
+ { appointment_datetime: '2099-01-01T13:00:00.000Z' },
+ { user: { id: 'admin-1', role: UserRole.ADMIN } },
+ 'specialist-1',
+ );
+
+ expect(actorContext.resolve).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'admin-1', role: UserRole.ADMIN }),
+ 'specialist-1',
+ );
+ expect(service.confirmAppointment).toHaveBeenCalledWith(
+ 'process-1',
+ 'admin-1',
+ '2099-01-01T13:00:00.000Z',
+ context,
+ );
+ });
});
diff --git a/backend/src/features/processes/processes.controller.ts b/backend/src/features/processes/processes.controller.ts
index 5574965..4b61a39 100644
--- a/backend/src/features/processes/processes.controller.ts
+++ b/backend/src/features/processes/processes.controller.ts
@@ -13,6 +13,7 @@ import {
ForbiddenException,
UseGuards,
Req,
+ Optional,
} from '@nestjs/common';
import { ProcessesService } from './processes.service';
import { CreateProcessDTO } from './dto/create-process.dto';
@@ -30,10 +31,66 @@ import { GetProcessesFilterDto } from './dto/get-processes-filter.dto';
import { UserEntity } from 'src/auth/entities/user.entity';
import { UserRole } from '@prisma/client';
import { ConfirmProcessAppointmentDto } from './dto/confirm-process-appointment.dto';
+import {
+ ActorContext,
+ ActorContextService,
+} from 'src/shared/actor-context/actor-context.service';
+import { Roles } from 'src/shared/decorators/roles.decorator';
+import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
@Controller('processes')
export class ProcessesController {
- constructor(private readonly processesService: ProcessesService) {}
+ constructor(
+ private readonly processesService: ProcessesService,
+ @Optional() private readonly actorContextService?: ActorContextService,
+ @Optional() private readonly delegatedAudit?: DelegatedActionAuditService,
+ ) {}
+
+ private async resolveSpecialistContext(
+ user: UserEntity,
+ targetSpecialistId?: string,
+ ): Promise {
+ if (
+ user.role !== UserRole.ADMIN &&
+ user.role !== UserRole.SPECIALIST
+ ) {
+ return undefined;
+ }
+ if (!this.actorContextService) {
+ return undefined;
+ }
+ return this.actorContextService.resolve(user, targetSpecialistId);
+ }
+
+ @Get(':id/admin-timeline')
+ @Roles(UserRole.ADMIN)
+ async getAdminTimeline(
+ @Param('id', new ParseUUIDPipe()) processId: string,
+ @Query('target_specialist_id') targetSpecialistId: string,
+ @Req() req: { user?: UserEntity },
+ ) {
+ if (!req.user || !this.actorContextService || !this.delegatedAudit) {
+ throw new UnauthorizedException('Contexto administrativo indisponível');
+ }
+ const context = await this.actorContextService.resolve(
+ req.user,
+ targetSpecialistId,
+ );
+ const process = await this.processesService.getById(
+ processId,
+ req.user.id,
+ req.user.role,
+ req.user.company_id,
+ );
+ this.actorContextService.assertResourceSpecialist(
+ context,
+ process.specialist.id,
+ );
+ return {
+ success: true,
+ data: await this.delegatedAudit.listForProcess(context, processId),
+ };
+ }
/**
* POST /api/processes
@@ -53,11 +110,15 @@ export class ProcessesController {
throw new UnauthorizedException('Usuário autenticado não identificado');
}
+ const context = await this.resolveSpecialistContext(
+ user,
+ createProcessDto.specialist_id,
+ );
const process = await this.processesService.create(createProcessDto, {
id: user.id,
role: user.role,
companyId: user.company_id,
- });
+ }, context);
return {
success: true,
@@ -131,6 +192,20 @@ export class ProcessesController {
};
}
+ @Get('admin/client-options')
+ @Roles(UserRole.ADMIN)
+ async getAdminClientOptions(
+ @Query('target_specialist_id') targetSpecialistId: string,
+ @Query('search') search: string | undefined,
+ @Req() req: { user?: UserEntity },
+ ) {
+ if (!req.user) {
+ throw new UnauthorizedException('Usuário autenticado não identificado');
+ }
+ await this.resolveSpecialistContext(req.user, targetSpecialistId);
+ return this.processesService.getAdminClientOptions(search);
+ }
+
/**
* GET /api/processes/:id
* Get a single process by its ID
@@ -144,6 +219,7 @@ export class ProcessesController {
async getById(
@Param('id', new ParseUUIDPipe()) processId: string,
@Req() req: { user?: UserEntity },
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const process = await this.processesService.getById(
processId,
@@ -151,6 +227,18 @@ export class ProcessesController {
req.user?.role,
req.user?.company_id,
);
+ if (req.user) {
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
+ if (context) {
+ this.actorContextService?.assertResourceSpecialist(
+ context,
+ process.specialist.id,
+ );
+ }
+ }
return {
success: true,
@@ -183,6 +271,15 @@ export class ProcessesController {
'Você não pode listar processos de outro especialista.',
);
}
+ const context = await this.resolveSpecialistContext(
+ user,
+ (filters as any).target_specialist_id,
+ );
+ if (context && context.specialistId !== specialistId) {
+ throw new ForbiddenException(
+ 'A lista não pertence ao especialista representado.',
+ );
+ }
const page = Number(filters.page) || 1;
const perPage = Number(filters.perPage) || 20;
@@ -241,6 +338,7 @@ export class ProcessesController {
@Param('id', new ParseUUIDPipe()) processId: string,
@Body() updateProcessDto: UpdateProcessDto,
@Req() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const userId = req.user?.sub || req.user?.id;
const userRole = req.user?.role;
@@ -249,12 +347,17 @@ export class ProcessesController {
throw new UnauthorizedException('Usuário autenticado não identificado');
}
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
const updatedProcess = await this.processesService.update(
processId,
updateProcessDto,
userId,
userRole,
req.user?.company_id,
+ context,
);
return {
@@ -283,6 +386,7 @@ export class ProcessesController {
@Param('id', new ParseUUIDPipe()) processId: string,
@Body() dto: AssignProductToProcessDto,
@Req() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const userId = req.user?.sub || req.user?.id;
const userRole = req.user?.role;
@@ -291,11 +395,16 @@ export class ProcessesController {
throw new UnauthorizedException('Usuário autenticado não identificado');
}
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
const updatedProcess = await this.processesService.assignProduct(
processId,
dto,
userId,
userRole,
+ context,
);
return {
@@ -432,6 +541,7 @@ export class ProcessesController {
@Param('id', new ParseUUIDPipe()) processId: string,
@Body() rejectProcessDto: RejectProcessDto,
@Req() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const userId = req.user?.sub || req.user?.id;
const userRole = req.user?.role;
@@ -440,12 +550,25 @@ export class ProcessesController {
throw new UnauthorizedException('Usuário autenticado não identificado');
}
+ if (
+ userRole === UserRole.ADMIN &&
+ !rejectProcessDto.rejection_reason?.trim()
+ ) {
+ throw new BadRequestException(
+ 'Motivo é obrigatório para rejeição administrativa.',
+ );
+ }
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
const result = await this.processesService.rejectProcess(
processId,
userId,
rejectProcessDto.rejection_reason,
userRole,
req.user?.company_id,
+ context,
);
return {
@@ -473,20 +596,35 @@ export class ProcessesController {
@Param('id', new ParseUUIDPipe()) processId: string,
@Body() dto: ConfirmProcessAppointmentDto,
@Req() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const userId = req.user?.sub || req.user?.id;
- if (!userId || req.user?.role !== UserRole.SPECIALIST) {
+ if (
+ !userId ||
+ ![UserRole.SPECIALIST, UserRole.ADMIN].includes(req.user?.role)
+ ) {
throw new ForbiddenException(
'Apenas o especialista pode confirmar o agendamento',
);
}
- const result = await this.processesService.confirmAppointment(
- processId,
- userId,
- dto.appointment_datetime,
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
);
+ const result = context
+ ? await this.processesService.confirmAppointment(
+ processId,
+ userId,
+ dto.appointment_datetime,
+ context,
+ )
+ : await this.processesService.confirmAppointment(
+ processId,
+ userId,
+ dto.appointment_datetime,
+ );
return {
success: true,
@@ -512,12 +650,25 @@ export class ProcessesController {
async cancelAppointment(
@Param('id', new ParseUUIDPipe()) processId: string,
@Req() req: any,
+ @Body('reason') reason?: string,
+ @Query('target_specialist_id') targetSpecialistId?: string,
): Promise> {
const userId = req.user?.sub || req.user?.id;
+ if (req.user?.role === UserRole.ADMIN && !reason?.trim()) {
+ throw new BadRequestException(
+ 'Motivo é obrigatório para cancelamento administrativo.',
+ );
+ }
+ const context = await this.resolveSpecialistContext(
+ req.user,
+ targetSpecialistId,
+ );
const result = await this.processesService.cancelAppointment(
processId,
userId,
+ context,
+ reason,
);
return {
diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts
index f3481c0..4ccc356 100644
--- a/backend/src/features/processes/processes.service.ts
+++ b/backend/src/features/processes/processes.service.ts
@@ -7,6 +7,7 @@ import {
Logger,
ForbiddenException,
HttpException,
+ Optional,
} from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { CreateProcessDTO } from './dto/create-process.dto';
@@ -49,6 +50,8 @@ import {
assertSpecialistScheduleAvailable,
} from '../appointments/appointment-schedule-lock';
import { isStaleMeetingInitializationClaim } from '../meetings/meeting-initialization-claim';
+import { ActorContext } from 'src/shared/actor-context/actor-context.service';
+import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
/**
* Quem está pedindo a operação. `companyId` só é usado por OFFICE.
@@ -106,8 +109,43 @@ export class ProcessesService {
constructor(
private readonly prismaService: PrismaService,
private readonly notificationService: NotificationService,
+ @Optional()
+ private readonly delegatedAudit?: DelegatedActionAuditService,
) {}
+ async getAdminClientOptions(search?: string) {
+ const normalizedSearch = search?.trim();
+ return this.prismaService.user.findMany({
+ where: {
+ role: UserRole.CUSTOMER,
+ is_active: true,
+ ...(normalizedSearch
+ ? {
+ OR: [
+ { name: { contains: normalizedSearch, mode: 'insensitive' } },
+ { surname: { contains: normalizedSearch, mode: 'insensitive' } },
+ { email: { contains: normalizedSearch, mode: 'insensitive' } },
+ ],
+ }
+ : {}),
+ },
+ select: { id: true, name: true, surname: true, email: true },
+ orderBy: [{ name: 'asc' }, { surname: 'asc' }],
+ take: 50,
+ });
+ }
+
+ private assertRepresentedSpecialist(
+ context: ActorContext | undefined,
+ specialistId: string,
+ ): void {
+ if (context && context.specialistId !== specialistId) {
+ throw new ForbiddenException(
+ 'O processo não pertence ao especialista representado.',
+ );
+ }
+ }
+
/**
* 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.
@@ -200,6 +238,36 @@ export class ProcessesService {
});
}
+ private async assertNoPendingProposalBeforeDocumentation(
+ tx: Prisma.TransactionClient,
+ processId: string,
+ ): Promise {
+ const lockKey = `proposal-process:${processId}`;
+ await tx.$queryRaw`
+ SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))::text AS locked
+ `;
+ const pendingRows = await tx.$queryRaw>`
+ SELECT "id"::text AS "id"
+ FROM "NegotiationProposal"
+ WHERE "process_id" = ${processId}::uuid
+ AND "status" = 'PENDING'::"ProposalStatus"
+ LIMIT 1
+ FOR UPDATE
+ `;
+ const pending = pendingRows.find((row) => typeof row.id === 'string');
+ if (pending) {
+ throw new ConflictException({
+ success: false,
+ error: {
+ code: 'PENDING_PROPOSAL_BLOCKS_DOCUMENTATION',
+ message:
+ 'Responda a proposta pendente antes de avançar para documentação.',
+ details: { proposal_id: pending.id },
+ },
+ });
+ }
+ }
+
/**
* Cria um objeto "product" de acordo com o processo enviado
*
@@ -461,12 +529,14 @@ export class ProcessesService {
async create(
createProcessDto: CreateProcessDTO,
requester: ProcessesRequester,
+ context?: ActorContext,
): Promise {
this.logger.log(
`[create] Iniciando criação de processo para cliente ${createProcessDto.client_id}`,
);
await this.assertCanCreateFor(requester, createProcessDto);
+ this.assertRepresentedSpecialist(context, createProcessDto.specialist_id);
const { product_id, client_id, specialist_id, ...dataToSave } =
createProcessDto;
@@ -524,8 +594,34 @@ export class ProcessesService {
productId: hasProduct ? createProcessDto.product_id : null,
});
+ let appointmentId: string | undefined;
+ if (context?.actorRole === UserRole.ADMIN) {
+ const pendingExpiresAt = new Date();
+ pendingExpiresAt.setDate(pendingExpiresAt.getDate() + 7);
+ const appointment = await tx.appointment.create({
+ data: {
+ client_id,
+ specialist_id,
+ product_type: hasProduct ? createProcessDto.product_type : null,
+ product_id: hasProduct ? createProcessDto.product_id : null,
+ status: StatusAgendamento.PENDING,
+ scheduling_method: AppointmentSchedulingMethod.EMAIL,
+ user_clicked_at: new Date(),
+ pending_expires_at: pendingExpiresAt,
+ notes: 'Criado por administrador em nome do especialista.',
+ },
+ });
+ appointmentId = appointment.id;
+ }
+
const process = await tx.process.create({
- data: { specialist_id, client_id, ...dataToSave, ...finalProduct },
+ data: {
+ specialist_id,
+ client_id,
+ ...dataToSave,
+ ...finalProduct,
+ ...(appointmentId ? { appointment_id: appointmentId } : {}),
+ },
include,
});
@@ -533,10 +629,24 @@ export class ProcessesService {
data: {
processId: process.id,
status: process.status,
+ changed_by: requester.id,
changed_at: new Date(),
},
});
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PROCESS_CREATE',
+ resourceType: 'PROCESS',
+ resourceId: process.id,
+ metadata: { appointmentId: appointmentId ?? null },
+ },
+ tx,
+ );
+ }
+
return process;
});
@@ -1252,6 +1362,7 @@ export class ProcessesService {
callerId?: string,
callerRole?: UserRole,
callerCompanyId?: string | null,
+ context?: ActorContext,
): 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
@@ -1289,6 +1400,10 @@ export class ProcessesService {
},
'update-status',
);
+ this.assertRepresentedSpecialist(
+ context,
+ existingProcess.specialist_id,
+ );
const lockedSpecialistId = existingProcess.specialist_id;
await acquireSpecialistScheduleLock(tx, lockedSpecialistId);
@@ -1316,6 +1431,12 @@ export class ProcessesService {
if (existingProcess.specialist_id !== lockedSpecialistId) {
this.throwStatusTransitionConflict(processId);
}
+ if (updateProcessDto.status === ProcessStatus.DOCUMENTATION) {
+ await this.assertNoPendingProposalBeforeDocumentation(
+ tx,
+ processId,
+ );
+ }
this.assertProcessAccess(
existingProcess,
{
@@ -1325,6 +1446,10 @@ export class ProcessesService {
},
'update-status',
);
+ this.assertRepresentedSpecialist(
+ context,
+ existingProcess.specialist_id,
+ );
//Verificar se ele já está com o status atualizado
if (existingProcess.status === updateProcessDto.status) {
@@ -1427,9 +1552,25 @@ export class ProcessesService {
data: {
processId,
status: updateProcessDto.status,
+ changed_by: callerId,
changed_at: nextUpdatedAt,
},
});
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PROCESS_STATUS_UPDATE',
+ resourceType: 'PROCESS',
+ resourceId: processId,
+ metadata: {
+ from: existingProcess.status,
+ to: updateProcessDto.status,
+ },
+ },
+ tx,
+ );
+ }
const statusHistory = await tx.processStatusHistory.findMany({
where: { processId },
});
@@ -1488,6 +1629,7 @@ export class ProcessesService {
dto: { product_type: string; product_id: string },
userId: string,
userRole: string,
+ context?: ActorContext,
): Promise {
this.logger.log(
`[assignProduct] Iniciando associação de produto ao processo ${processId}`,
@@ -1517,7 +1659,11 @@ export class ProcessesService {
}
// 2. Verificar permissão: apenas especialista do processo ou ADMIN
- if (process.specialist_id !== userId && userRole !== 'ADMIN') {
+ const representedSpecialistId = context?.specialistId ?? userId;
+ if (
+ process.specialist_id !== representedSpecialistId ||
+ (userRole !== 'ADMIN' && process.specialist_id !== userId)
+ ) {
throw new ForbiddenException({
success: false,
error: {
@@ -1596,6 +1742,10 @@ export class ProcessesService {
aircraft: true,
},
});
+ this.assertRepresentedSpecialist(
+ context,
+ processForAssignment.specialist_id,
+ );
const assignmentStateChanged =
(processForAssignment.status !== ProcessStatus.SCHEDULING &&
@@ -1786,6 +1936,22 @@ export class ProcessesService {
});
}
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PROCESS_ASSIGN_PRODUCT',
+ resourceType: 'PROCESS',
+ resourceId: processId,
+ metadata: {
+ productType,
+ productId: dto.product_id,
+ },
+ },
+ tx,
+ );
+ }
+
return tx.process.findUniqueOrThrow({
where: { id: processId },
include: {
@@ -1808,7 +1974,9 @@ export class ProcessesService {
previousStatus: process.status,
currentStatus: updatedProcess.status,
changedByName:
- `${process.specialist.name} ${process.specialist.surname || ''}`.trim(),
+ context?.delegated && context.actor
+ ? `${context.actor.name} ${context.actor.surname}`.trim()
+ : `${process.specialist.name} ${process.specialist.surname || ''}`.trim(),
reason: 'Produto associado ao processo após confirmação da reunião',
productDetails: this.getProductDetails(updatedProcess),
client: process.client,
@@ -2103,6 +2271,7 @@ export class ProcessesService {
rejectionReason?: string,
requesterRole?: UserRole,
requesterCompanyId?: string | null,
+ context?: ActorContext,
): Promise {
try {
const [updatedProcess, updatedStatusHistory] =
@@ -2131,6 +2300,7 @@ export class ProcessesService {
},
'reject',
);
+ this.assertRepresentedSpecialist(context, candidate.specialist_id);
// Mesma ordem de cancelamento/avanço: agenda do especialista,
// releitura do processo e só então a reivindicação CAS.
@@ -2191,6 +2361,10 @@ export class ProcessesService {
},
'reject',
);
+ this.assertRepresentedSpecialist(
+ context,
+ existingProcess.specialist_id,
+ );
// Verificar se já está rejeitado
if (existingProcess.status === 'REJECTED') {
@@ -2203,12 +2377,12 @@ export class ProcessesService {
}
if (
existingProcess.active_contract?.provider_id &&
- ![
+ !new Set([
ProviderStatus.DECLINED,
ProviderStatus.VOIDED,
ProviderStatus.TIMEDOUT,
ProviderStatus.ERROR,
- ].includes(
+ ]).has(
existingProcess.active_contract.provider_status as ProviderStatus,
)
) {
@@ -2317,14 +2491,30 @@ export class ProcessesService {
},
});
}
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PROCESS_REJECT',
+ resourceType: 'PROCESS',
+ resourceId: processId,
+ metadata: {
+ from: existingProcess.status,
+ reason: rejectionReason ?? null,
+ },
+ },
+ tx,
+ );
+ }
// Buscar histórico atualizado
const statusHistory = await tx.processStatusHistory.findMany({
where: { processId },
});
- const changedByName =
- rejectedById === existingProcess.client?.id
+ const changedByName = context?.delegated && context.actor
+ ? `${context.actor.name} ${context.actor.surname}`.trim()
+ : rejectedById === existingProcess.client?.id
? `${existingProcess.client?.name || ''} ${existingProcess.client?.surname || ''}`.trim()
: rejectedById === existingProcess.specialist?.id
? `${existingProcess.specialist?.name || ''} ${existingProcess.specialist?.surname || ''}`.trim()
@@ -2382,6 +2572,7 @@ export class ProcessesService {
processId: string,
userId: string,
appointmentDatetime?: string,
+ context?: ActorContext,
): Promise {
this.logger.log(
`[confirmAppointment] Confirmando agendamento do processo ${processId}`,
@@ -2398,7 +2589,8 @@ export class ProcessesService {
}
// Verificar se o usuário é o especialista
- if (process.specialist_id !== userId) {
+ const representedSpecialistId = context?.specialistId ?? userId;
+ if (process.specialist_id !== representedSpecialistId) {
throw new ForbiddenException(
'Apenas o especialista pode confirmar o agendamento',
);
@@ -2426,7 +2618,11 @@ export class ProcessesService {
if (!lockedProcess) {
throw new NotFoundException('Processo não encontrado');
}
- if (lockedProcess.specialist_id !== userId) {
+ this.assertRepresentedSpecialist(
+ context,
+ lockedProcess.specialist_id,
+ );
+ if (lockedProcess.specialist_id !== representedSpecialistId) {
throw new ForbiddenException(
'Apenas o especialista pode confirmar o agendamento',
);
@@ -2539,6 +2735,19 @@ export class ProcessesService {
},
});
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'APPOINTMENT_CONFIRM',
+ resourceType: 'APPOINTMENT',
+ resourceId: appointment.id,
+ metadata: { processId, appointmentDatetime: lockedConfirmedDate },
+ },
+ tx,
+ );
+ }
+
return {
changed: true,
confirmedDate: lockedConfirmedDate,
@@ -2594,7 +2803,12 @@ export class ProcessesService {
* @throws {ForbiddenException} - Usuário não autorizado
* @throws {BadRequestException} - Processo não está em status SCHEDULING
*/
- async cancelAppointment(processId: string, userId: string): Promise {
+ async cancelAppointment(
+ processId: string,
+ userId: string,
+ context?: ActorContext,
+ reason?: string,
+ ): Promise {
this.logger.log(
`[cancelAppointment] Cancelando agendamento do processo ${processId}`,
);
@@ -2610,7 +2824,8 @@ export class ProcessesService {
// Verificar se o usuário é o cliente ou especialista
const isClient = candidate.client_id === userId;
- const isSpecialist = candidate.specialist_id === userId;
+ const representedSpecialistId = context?.specialistId ?? userId;
+ const isSpecialist = candidate.specialist_id === representedSpecialistId;
if (!isClient && !isSpecialist) {
throw new ForbiddenException(
@@ -2641,12 +2856,16 @@ export class ProcessesService {
}
if (
lockedProcess.client_id !== userId &&
- lockedProcess.specialist_id !== userId
+ lockedProcess.specialist_id !== representedSpecialistId
) {
throw new ForbiddenException(
'Sem permissão para cancelar este agendamento',
);
}
+ this.assertRepresentedSpecialist(
+ context,
+ lockedProcess.specialist_id,
+ );
if (lockedProcess.status !== ProcessStatus.SCHEDULING) {
throw new BadRequestException(
'Apenas processos em status SCHEDULING podem ter o agendamento cancelado',
@@ -2689,6 +2908,19 @@ export class ProcessesService {
);
}
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'APPOINTMENT_CANCEL',
+ resourceType: 'APPOINTMENT',
+ resourceId: lockedProcess.appointment.id,
+ metadata: { processId, reason: reason ?? null },
+ },
+ tx,
+ );
+ }
+
// Deletar histórico do processo
await tx.processStatusHistory.deleteMany({
where: { processId },
diff --git a/backend/src/features/product-import-jobs/product-import-jobs.controller.ts b/backend/src/features/product-import-jobs/product-import-jobs.controller.ts
index ce6ea88..7853386 100644
--- a/backend/src/features/product-import-jobs/product-import-jobs.controller.ts
+++ b/backend/src/features/product-import-jobs/product-import-jobs.controller.ts
@@ -1,19 +1,32 @@
-import { Controller, Get, Param } from '@nestjs/common';
+import { Controller, Get, Optional, Param, Query } from '@nestjs/common';
import { UserRole } from '@prisma/client';
import { UserEntity } from 'src/auth/entities/user.entity';
import { CurrentUser } from 'src/shared/decorators/current-user.decorator';
import { Roles } from 'src/shared/decorators/roles.decorator';
import { ProductImportJobsService } from './product-import-jobs.service';
+import { ActorContextService } from 'src/shared/actor-context/actor-context.service';
@Controller('product-import-jobs')
export class ProductImportJobsController {
constructor(
private readonly productImportJobsService: ProductImportJobsService,
+ @Optional() private readonly actorContextService?: ActorContextService,
) {}
@Get(':jobId')
@Roles(UserRole.ADMIN, UserRole.SPECIALIST)
- getJobStatus(@Param('jobId') jobId: string, @CurrentUser() user: UserEntity) {
- return this.productImportJobsService.getJobStatus(jobId, user);
+ async getJobStatus(
+ @Param('jobId') jobId: string,
+ @CurrentUser() user: UserEntity,
+ @Query('target_specialist_id') targetSpecialistId?: string,
+ ) {
+ const context = this.actorContextService
+ ? await this.actorContextService.resolve(user, targetSpecialistId)
+ : undefined;
+ return this.productImportJobsService.getJobStatus(
+ jobId,
+ user,
+ context?.specialistId,
+ );
}
}
diff --git a/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts b/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts
index 75efd7a..ad82753 100644
--- a/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts
+++ b/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts
@@ -107,6 +107,11 @@ describe('ProductImportJobsService', () => {
},
} as any;
const service = new ProductImportJobsService(prisma, {} as any, {} as any);
+ jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({
+ mode: 'SYNCHRONIZE',
+ syncConfirmed: true,
+ specialistIsEligible: true,
+ });
const deactivateMissingProducts = jest
.spyOn(service as any, 'deactivateMissingProducts')
.mockResolvedValue(['stale-product']);
@@ -130,6 +135,145 @@ describe('ProductImportJobsService', () => {
});
});
+ it('não inativa produtos ausentes no modo aditivo', async () => {
+ const prisma = {
+ productImportJob: {
+ findUnique: jest.fn().mockResolvedValue({
+ id: 'job-additive',
+ product_type: ProductType.CAR,
+ specialist_id: '00000000-0000-4000-8000-000000000001',
+ status: 'PENDING',
+ started_at: null,
+ items: [],
+ }),
+ update: jest.fn().mockResolvedValue({}),
+ },
+ } as any;
+ const service = new ProductImportJobsService(prisma, {} as any, {} as any);
+ jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({
+ mode: 'ADDITIVE',
+ syncConfirmed: false,
+ specialistIsEligible: true,
+ });
+ const deactivateMissingProducts = jest
+ .spyOn(service as any, 'deactivateMissingProducts')
+ .mockResolvedValue(['stale-product']);
+ const refreshJobCounters = jest
+ .spyOn(service as any, 'refreshJobCounters')
+ .mockResolvedValue(undefined);
+
+ await (service as any).processJob('job-additive');
+
+ expect(deactivateMissingProducts).not.toHaveBeenCalled();
+ expect(refreshJobCounters).toHaveBeenCalledWith('job-additive', {
+ deactivatedIds: [],
+ reactivatedCount: 0,
+ });
+ });
+
+ it('mantém o job pendente quando o especialista-alvo foi desativado', async () => {
+ const prisma = {
+ productImportJob: {
+ findUnique: jest.fn().mockResolvedValue({
+ id: 'job-inactive',
+ product_type: ProductType.CAR,
+ specialist_id: '00000000-0000-4000-8000-000000000001',
+ status: 'PENDING',
+ started_at: null,
+ items: [],
+ }),
+ update: jest.fn().mockResolvedValue({}),
+ },
+ } as any;
+ const service = new ProductImportJobsService(prisma, {} as any, {} as any);
+ jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({
+ mode: 'ADDITIVE',
+ syncConfirmed: false,
+ specialistIsEligible: false,
+ });
+
+ await (service as any).processJob('job-inactive');
+
+ expect(prisma.productImportJob.update).toHaveBeenCalledTimes(1);
+ expect(prisma.productImportJob.update).toHaveBeenCalledWith({
+ where: { id: 'job-inactive' },
+ data: expect.objectContaining({
+ status: 'PENDING',
+ error_message: expect.stringContaining('inativo'),
+ }),
+ });
+ });
+
+ it('exige confirmação explícita para sincronizar', async () => {
+ const xlsxImportService = {
+ parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
+ validateStructure: jest.fn().mockReturnValue({ valid: true }),
+ } as any;
+ const service = new ProductImportJobsService(
+ {} as any,
+ xlsxImportService,
+ {} as any,
+ );
+
+ await expect(
+ service.createJobFromCsv(
+ Buffer.from('csv'),
+ { id: 'admin-1', role: 'ADMIN' } as any,
+ ProductType.CAR,
+ {
+ mode: 'SYNCHRONIZE',
+ confirmSynchronize: false,
+ context: {
+ actorId: 'admin-1',
+ actorRole: 'ADMIN',
+ specialistId: '00000000-0000-4000-8000-000000000001',
+ specialist: {} as any,
+ delegated: true,
+ },
+ },
+ ),
+ ).rejects.toThrow('confirmação explícita');
+ });
+
+ it('calcula o impacto da sincronização antes de criar o job', async () => {
+ const xlsxImportService = {
+ parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
+ validateStructure: jest.fn().mockReturnValue({ valid: true }),
+ } as any;
+ const prisma = {
+ car: {
+ findMany: jest.fn().mockResolvedValue([
+ { id: 'keep', identificador: 'FERRARI-ROMA-1' },
+ { id: 'stale', identificador: 'FERRARI-OLD-1' },
+ ]),
+ },
+ } as any;
+ const service = new ProductImportJobsService(
+ prisma,
+ xlsxImportService,
+ {} as any,
+ );
+
+ await expect(
+ service.previewCsvImport(
+ Buffer.from('csv'),
+ ProductType.CAR,
+ '00000000-0000-4000-8000-000000000001',
+ 'SYNCHRONIZE',
+ ),
+ ).resolves.toMatchObject({
+ mode: 'SYNCHRONIZE',
+ targetSpecialistId: '00000000-0000-4000-8000-000000000001',
+ requiresExplicitConfirmation: true,
+ impact: {
+ incomingItems: 1,
+ activeItemsBefore: 2,
+ matchingItems: 1,
+ deactivationCandidates: 1,
+ },
+ });
+ });
+
it('relata a linha não importada com erro em linguagem natural', () => {
const service = new ProductImportJobsService(
{} as any,
diff --git a/backend/src/features/product-import-jobs/product-import-jobs.service.ts b/backend/src/features/product-import-jobs/product-import-jobs.service.ts
index 9559e35..dead110 100644
--- a/backend/src/features/product-import-jobs/product-import-jobs.service.ts
+++ b/backend/src/features/product-import-jobs/product-import-jobs.service.ts
@@ -6,6 +6,7 @@ import {
NotFoundException,
OnModuleDestroy,
OnModuleInit,
+ Optional,
} from '@nestjs/common';
import {
ProductImportItemStatus,
@@ -41,6 +42,16 @@ import {
acquireProductMonetaryLock,
updateProductWithMonetaryLock,
} from '../products/product-monetary-lock';
+import { ActorContext } from 'src/shared/actor-context/actor-context.service';
+import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
+
+export type ProductImportMode = 'ADDITIVE' | 'SYNCHRONIZE';
+
+export type ProductImportOptions = {
+ context?: ActorContext;
+ mode?: ProductImportMode | string;
+ confirmSynchronize?: boolean | string;
+};
type UpsertResult = {
productId: string;
@@ -67,6 +78,8 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
private readonly prisma: PrismaService,
private readonly xlsxImportService: XlsxImportService,
private readonly driveImportService: DriveImportService,
+ @Optional()
+ private readonly delegatedAudit?: DelegatedActionAuditService,
) {}
private isMissingImportJobsTableError(error: unknown): boolean {
@@ -99,7 +112,23 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
fileBuffer: Buffer,
user: UserEntity,
productType: ProductType,
+ options: ProductImportOptions = {},
) {
+ const mode = `${options.mode ?? 'ADDITIVE'}`.toUpperCase();
+ if (mode !== 'ADDITIVE' && mode !== 'SYNCHRONIZE') {
+ throw new BadRequestException(
+ 'Modo de importação inválido. Use ADDITIVE ou SYNCHRONIZE.',
+ );
+ }
+ const syncConfirmed =
+ options.confirmSynchronize === true ||
+ `${options.confirmSynchronize}`.toLowerCase() === 'true';
+ if (mode === 'SYNCHRONIZE' && !syncConfirmed) {
+ throw new BadRequestException(
+ 'A sincronização exige confirmação explícita do alvo, tipo e impacto.',
+ );
+ }
+
const { rows } = this.xlsxImportService.parseCsv(fileBuffer);
const structureValidation = this.xlsxImportService.validateStructure(
@@ -117,31 +146,60 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
}
const normalizedRows = rows.map((row) => this.normalizeProductRow(row));
+ const specialistId = options.context?.specialistId ?? user.id;
+ const impact = await this.estimateImportImpact(
+ productType,
+ specialistId,
+ normalizedRows,
+ mode,
+ );
let createdJob;
try {
- createdJob = await this.prisma.productImportJob.create({
- data: {
- product_type: productType,
- specialist_id: user.id,
- status: ProductImportJobStatus.PENDING,
- total_items: normalizedRows.length,
- items: {
- createMany: {
- data: normalizedRows.map((row, index) => ({
- row_number: index + 2,
- payload: row,
- folder_url: row.folder_url?.trim() || null,
- })),
+ createdJob = await this.prisma.$transaction(async (tx) => {
+ const job = await tx.productImportJob.create({
+ data: {
+ product_type: productType,
+ specialist_id: specialistId,
+ status: ProductImportJobStatus.PENDING,
+ total_items: normalizedRows.length,
+ items: {
+ createMany: {
+ data: normalizedRows.map((row, index) => ({
+ row_number: index + 2,
+ payload: row,
+ folder_url: row.folder_url?.trim() || null,
+ })),
+ },
},
},
- },
- select: {
- id: true,
- status: true,
- total_items: true,
- product_type: true,
- },
+ select: {
+ id: true,
+ status: true,
+ total_items: true,
+ product_type: true,
+ },
+ });
+ await tx.$executeRaw`
+ UPDATE "ProductImportJob"
+ SET "mode" = ${mode},
+ "sync_confirmed" = ${syncConfirmed},
+ "created_by_id" = ${user.id}::uuid
+ WHERE "id" = ${job.id}::uuid
+ `;
+ if (options.context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context: options.context,
+ action: 'PRODUCT_IMPORT_CREATE',
+ resourceType: productType,
+ resourceId: job.id,
+ metadata: { mode, impact },
+ },
+ tx,
+ );
+ }
+ return job;
});
} catch (error) {
if (this.isMissingImportJobsTableError(error)) {
@@ -159,12 +217,61 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
status: createdJob.status,
productType: createdJob.product_type,
totalItems: createdJob.total_items,
+ targetSpecialistId: specialistId,
+ mode,
+ synchronizeConfirmed: syncConfirmed,
+ impact,
pollIntervalMs: 2000,
message: 'Importação recebida e iniciada em segundo plano.',
};
}
- async getJobStatus(jobId: string, user: UserEntity) {
+ async previewCsvImport(
+ fileBuffer: Buffer,
+ productType: ProductType,
+ specialistId: string,
+ requestedMode: ProductImportMode | string = 'ADDITIVE',
+ ) {
+ const mode = `${requestedMode}`.toUpperCase();
+ if (mode !== 'ADDITIVE' && mode !== 'SYNCHRONIZE') {
+ throw new BadRequestException(
+ 'Modo de importação inválido. Use ADDITIVE ou SYNCHRONIZE.',
+ );
+ }
+ const { rows } = this.xlsxImportService.parseCsv(fileBuffer);
+ const structureValidation = this.xlsxImportService.validateStructure(
+ rows,
+ this.getColumnsForType(productType),
+ );
+ if (!structureValidation.valid) {
+ throw new BadRequestException({
+ message: 'Estrutura do CSV inválida',
+ errors: structureValidation.errors,
+ missingRequired: structureValidation.missingRequired,
+ unknownColumns: structureValidation.unknownColumns,
+ });
+ }
+ const normalizedRows = rows.map((row) => this.normalizeProductRow(row));
+ const impact = await this.estimateImportImpact(
+ productType,
+ specialistId,
+ normalizedRows,
+ mode,
+ );
+ return {
+ productType,
+ targetSpecialistId: specialistId,
+ mode,
+ requiresExplicitConfirmation: mode === 'SYNCHRONIZE',
+ impact,
+ };
+ }
+
+ async getJobStatus(
+ jobId: string,
+ user: UserEntity,
+ representedSpecialistId?: string,
+ ) {
let job;
try {
job = await this.prisma.productImportJob.findUnique({
@@ -202,6 +309,15 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
'Sem permissão para visualizar este job de importação',
);
}
+ if (
+ user.role === UserRole.ADMIN &&
+ representedSpecialistId &&
+ job.specialist_id !== representedSpecialistId
+ ) {
+ throw new ForbiddenException(
+ 'O job não pertence ao especialista representado.',
+ );
+ }
const response = this.buildImportResponse(job.items, {
deactivatedIds: Array.isArray(job.deactivated_product_ids)
@@ -303,6 +419,19 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
return;
}
+ const executionContext = await this.getJobExecutionContext(job);
+ if (!executionContext.specialistIsEligible) {
+ await this.prisma.productImportJob.update({
+ where: { id: jobId },
+ data: {
+ status: ProductImportJobStatus.PENDING,
+ error_message:
+ 'Job pausado: especialista-alvo inativo ou incompatível com o tipo do produto.',
+ },
+ });
+ return;
+ }
+
await this.prisma.productImportJob.update({
where: { id: jobId },
data: {
@@ -400,14 +529,18 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
}
}
- const deactivatedIds = hasFailedItems
- ? []
- : await this.deactivateMissingProducts(
+ const shouldSynchronize =
+ executionContext.mode === 'SYNCHRONIZE' &&
+ executionContext.syncConfirmed &&
+ !hasFailedItems;
+ const deactivatedIds = shouldSynchronize
+ ? await this.deactivateMissingProducts(
job.product_type,
job.specialist_id,
seenProductIds,
job.id,
- );
+ )
+ : [];
await this.refreshJobCounters(jobId, {
deactivatedIds,
@@ -426,6 +559,85 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
}
}
+ private async getJobExecutionContext(job: {
+ id: string;
+ specialist_id: string;
+ product_type: ProductType;
+ }): Promise<{
+ mode: ProductImportMode;
+ syncConfirmed: boolean;
+ specialistIsEligible: boolean;
+ }> {
+ const metadata = await this.prisma.$queryRaw<
+ Array<{ mode: string; sync_confirmed: boolean }>
+ >`
+ SELECT "mode", "sync_confirmed"
+ FROM "ProductImportJob"
+ WHERE "id" = ${job.id}::uuid
+ `;
+ const specialist = await this.prisma.user.findUnique({
+ where: { id: job.specialist_id },
+ select: { role: true, is_active: true, speciality: true },
+ });
+ const row = metadata[0];
+ return {
+ mode: row?.mode === 'SYNCHRONIZE' ? 'SYNCHRONIZE' : 'ADDITIVE',
+ syncConfirmed: row?.sync_confirmed === true,
+ specialistIsEligible:
+ specialist?.role === UserRole.SPECIALIST &&
+ specialist.is_active === true &&
+ specialist.speciality === job.product_type,
+ };
+ }
+
+ private async estimateImportImpact(
+ productType: ProductType,
+ specialistId: string,
+ rows: ImportParsedRow[],
+ mode: ProductImportMode,
+ ) {
+ const activeProducts = await this.getActiveProductsByType(
+ productType,
+ specialistId,
+ );
+ const incomingIdentifiers = new Set(
+ rows.map((row) => row.identificador?.trim()).filter(Boolean),
+ );
+ const matching = activeProducts.filter((product) =>
+ incomingIdentifiers.has(product.identificador),
+ ).length;
+ const deactivationCandidates =
+ mode === 'SYNCHRONIZE'
+ ? activeProducts.filter(
+ (product) => !incomingIdentifiers.has(product.identificador),
+ ).length
+ : 0;
+ return {
+ incomingItems: rows.length,
+ activeItemsBefore: activeProducts.length,
+ matchingItems: matching,
+ newOrReactivatedItems: Math.max(0, incomingIdentifiers.size - matching),
+ deactivationCandidates,
+ };
+ }
+
+ private async getActiveProductsByType(
+ productType: ProductType,
+ specialistId: string,
+ ): Promise> {
+ const query = {
+ where: { specialist_id: specialistId, is_active: true },
+ select: { id: true, identificador: true },
+ };
+ if (productType === ProductType.CAR) {
+ return this.prisma.car.findMany(query);
+ }
+ if (productType === ProductType.BOAT) {
+ return this.prisma.boat.findMany(query);
+ }
+ return this.prisma.aircraft.findMany(query);
+ }
+
private async refreshJobCounters(
jobId: string,
syncSummary?: { deactivatedIds: string[]; reactivatedCount: number },
diff --git a/backend/src/features/products/product-association-validator.ts b/backend/src/features/products/product-association-validator.ts
index 95490eb..cce5d74 100644
--- a/backend/src/features/products/product-association-validator.ts
+++ b/backend/src/features/products/product-association-validator.ts
@@ -35,7 +35,7 @@ export async function validateSpecialistProductAssociation(
const specialist = await client.user.findUnique({
where: { id: input.specialistId },
- select: { id: true, role: true, speciality: true },
+ select: { id: true, role: true, speciality: true, is_active: true },
});
if (!specialist) {
throw new NotFoundException('Especialista não encontrado');
@@ -43,9 +43,11 @@ export async function validateSpecialistProductAssociation(
if (specialist.role !== UserRole.SPECIALIST) {
throw new BadRequestException('Usuário informado não é especialista');
}
+ if (specialist.is_active === false) {
+ throw new ForbiddenException('Especialista inativo');
+ }
if (
input.productType &&
- specialist.speciality &&
specialist.speciality !== input.productType
) {
throw new BadRequestException(
diff --git a/backend/src/features/proposals/proposals.controller.ts b/backend/src/features/proposals/proposals.controller.ts
index af2ed47..55ca015 100644
--- a/backend/src/features/proposals/proposals.controller.ts
+++ b/backend/src/features/proposals/proposals.controller.ts
@@ -9,10 +9,14 @@ import {
Request,
HttpStatus,
Logger,
+ Query,
+ Optional,
} from '@nestjs/common';
import { ProposalsService } from './proposals.service';
import { CreateProposalDto, RespondProposalDto } from './dto';
import { AuthGuard } from 'src/auth/auth.guard';
+import { UserRole } from '@prisma/client';
+import { ActorContextService } from 'src/shared/actor-context/actor-context.service';
/**
* ProposalsController
@@ -33,7 +37,20 @@ import { AuthGuard } from 'src/auth/auth.guard';
export class ProposalsController {
private readonly logger = new Logger(ProposalsController.name);
- constructor(private proposalsService: ProposalsService) {}
+ constructor(
+ private proposalsService: ProposalsService,
+ @Optional() private readonly actorContextService?: ActorContextService,
+ ) {}
+
+ private async resolveContext(user: any, targetSpecialistId?: string) {
+ if (
+ !this.actorContextService ||
+ (user?.role !== UserRole.ADMIN && user?.role !== UserRole.SPECIALIST)
+ ) {
+ return undefined;
+ }
+ return this.actorContextService.resolve(user, targetSpecialistId);
+ }
/**
* POST /api/proposals
@@ -55,13 +72,18 @@ export class ProposalsController {
* - 404 Not Found: Processo não encontrado
*/
@Post()
- async create(@Body() dto: CreateProposalDto, @Request() req: any) {
+ async create(
+ @Body() dto: CreateProposalDto,
+ @Request() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
+ ) {
const userId = req.user.id;
this.logger.log(
`[POST /proposals] Criando proposta para processo ${dto.process_id}`,
);
- const proposal = await this.proposalsService.create(dto, userId);
+ const context = await this.resolveContext(req.user, targetSpecialistId);
+ const proposal = await this.proposalsService.create(dto, userId, context);
return {
success: true,
@@ -85,13 +107,19 @@ export class ProposalsController {
async getByProcess(
@Param('processId') processId: string,
@Request() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
) {
const userId = req.user.id;
this.logger.log(
`[GET /processes/${processId}/proposals] Listando propostas`,
);
- const result = await this.proposalsService.getByProcess(processId, userId);
+ const context = await this.resolveContext(req.user, targetSpecialistId);
+ const result = await this.proposalsService.getByProcess(
+ processId,
+ userId,
+ context,
+ );
return {
success: true,
@@ -113,11 +141,16 @@ export class ProposalsController {
* - 404 Not Found: Proposta não encontrada
*/
@Get(':id')
- async getById(@Param('id') id: string, @Request() req: any) {
+ async getById(
+ @Param('id') id: string,
+ @Request() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
+ ) {
const userId = req.user.id;
this.logger.log(`[GET /proposals/${id}] Buscando proposta`);
- const proposal = await this.proposalsService.getById(id, userId);
+ const context = await this.resolveContext(req.user, targetSpecialistId);
+ const proposal = await this.proposalsService.getById(id, userId, context);
return {
success: true,
@@ -146,11 +179,18 @@ export class ProposalsController {
@Param('id') id: string,
@Body() dto: RespondProposalDto,
@Request() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
) {
const userId = req.user.id;
this.logger.log(`[PATCH /proposals/${id}/accept] Aceitando proposta`);
- const proposal = await this.proposalsService.accept(id, userId, dto);
+ const context = await this.resolveContext(req.user, targetSpecialistId);
+ const proposal = await this.proposalsService.accept(
+ id,
+ userId,
+ dto,
+ context,
+ );
return {
success: true,
@@ -180,11 +220,18 @@ export class ProposalsController {
@Param('id') id: string,
@Body() dto: RespondProposalDto,
@Request() req: any,
+ @Query('target_specialist_id') targetSpecialistId?: string,
) {
const userId = req.user.id;
this.logger.log(`[PATCH /proposals/${id}/reject] Rejeitando proposta`);
- const proposal = await this.proposalsService.reject(id, userId, dto);
+ const context = await this.resolveContext(req.user, targetSpecialistId);
+ const proposal = await this.proposalsService.reject(
+ id,
+ userId,
+ dto,
+ context,
+ );
return {
success: true,
diff --git a/backend/src/features/proposals/proposals.service.spec.ts b/backend/src/features/proposals/proposals.service.spec.ts
index 61fbb81..e6b3053 100644
--- a/backend/src/features/proposals/proposals.service.spec.ts
+++ b/backend/src/features/proposals/proposals.service.spec.ts
@@ -146,13 +146,20 @@ function setup() {
sendProposalRejectedEmail: jest.fn().mockResolvedValue(undefined),
sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined),
} as any;
- const service = new ProposalsService(prisma, settings, notifications);
+ const audit = { record: jest.fn().mockResolvedValue(undefined) } as any;
+ const service = new ProposalsService(
+ prisma,
+ settings,
+ notifications,
+ audit,
+ );
return {
service,
prisma,
settings,
notifications,
+ audit,
transactionProposalCreate,
transactionProposalUpdateMany,
transactionProcessFindUnique,
@@ -363,6 +370,62 @@ describe('ProposalsService — snapshot e mínimo dinâmico', () => {
);
});
+ it('não cria uma segunda PENDING sem responder a pendente identificada', async () => {
+ const { service, prisma, transactionProposalCreate } = setup();
+ prisma.process.findUnique.mockResolvedValue(
+ processFixture({ proposals: [proposalFixture()] }),
+ );
+
+ await expect(
+ service.create(
+ { process_id: 'process-1', proposed_value: 90000 },
+ 'specialist-1',
+ ),
+ ).rejects.toMatchObject({
+ response: expect.objectContaining({
+ error: expect.objectContaining({
+ code: 'PENDING_PROPOSAL_MUST_BE_ANSWERED',
+ }),
+ }),
+ });
+ expect(transactionProposalCreate).not.toHaveBeenCalled();
+ });
+
+ it('mantém SPECIALIST como parte comercial e ADMIN como executor auditado', async () => {
+ const { service, prisma, transactionProposalCreate, audit } = setup();
+ prisma.process.findUnique.mockResolvedValue(processFixture());
+ const context = {
+ actorId: 'admin-1',
+ actorRole: UserRole.ADMIN,
+ specialistId: 'specialist-1',
+ delegated: true,
+ specialist: {} as any,
+ };
+
+ await service.create(
+ { process_id: 'process-1', proposed_value: 90000 },
+ 'admin-1',
+ context,
+ );
+
+ expect(transactionProposalCreate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ proposed_by_id: 'specialist-1',
+ proposed_to_id: 'client-1',
+ }),
+ }),
+ );
+ expect(audit.record).toHaveBeenCalledWith(
+ expect.objectContaining({
+ context,
+ action: 'PROPOSAL_CREATE',
+ resourceType: 'PROPOSAL',
+ }),
+ expect.anything(),
+ );
+ });
+
it('rejects a counterproposal that references another process', async () => {
const { service, prisma, transactionProposalCreate } = setup();
prisma.process.findUnique.mockResolvedValue(processFixture());
diff --git a/backend/src/features/proposals/proposals.service.ts b/backend/src/features/proposals/proposals.service.ts
index 6d22e3f..cb278a9 100644
--- a/backend/src/features/proposals/proposals.service.ts
+++ b/backend/src/features/proposals/proposals.service.ts
@@ -5,6 +5,7 @@ import {
NotFoundException,
ForbiddenException,
Logger,
+ Optional,
} from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { CreateProposalDto, RespondProposalDto } from './dto';
@@ -17,6 +18,8 @@ import { SettingsService } from 'src/features/settings/settings.service';
import { NotificationService } from 'src/features/notifications/notification.service';
import { requireNegotiationSnapshot } from 'src/features/processes/negotiation-snapshot';
import { calculateMinimumProposalValue } from './proposal-money';
+import { ActorContext } from 'src/shared/actor-context/actor-context.service';
+import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
/**
* ProposalsService
@@ -45,6 +48,8 @@ export class ProposalsService {
private prisma: PrismaService,
private settingsService: SettingsService,
private notificationService: NotificationService,
+ @Optional()
+ private readonly delegatedAudit?: DelegatedActionAuditService,
) {}
private async lockProposalProcess(tx: any, processId: string): Promise {
@@ -88,6 +93,7 @@ export class ProposalsService {
async create(
dto: CreateProposalDto,
userId: string,
+ context?: ActorContext,
): Promise {
this.logger.log(
`[create] Criando proposta para processo ${dto.process_id} por usuário ${userId}`,
@@ -172,9 +178,16 @@ export class ProposalsService {
}
// 3. Validar que usuário é participante do processo (cliente, especialista ou consultor do cliente)
- const isClient = process.client_id === userId;
- const isSpecialist = process.specialist_id === userId;
- const isConsultantOfClient = process.client?.consultant_id === userId;
+ const partyUserId = context?.specialistId ?? userId;
+ if (context && process.specialist_id !== context.specialistId) {
+ throw new ForbiddenException(
+ 'O processo não pertence ao especialista representado.',
+ );
+ }
+ const isClient = process.client_id === partyUserId;
+ const isSpecialist = process.specialist_id === partyUserId;
+ const isConsultantOfClient =
+ !context && process.client?.consultant_id === userId;
const isOnClientSide = isClient || isConsultantOfClient;
if (!isClient && !isSpecialist && !isConsultantOfClient) {
@@ -194,6 +207,17 @@ export class ProposalsService {
// 4. Validar alternância por lado (cliente/consultor vs especialista) — não pode dois envios seguidos do mesmo lado
const lastProposal = process.proposals[0];
if (lastProposal && lastProposal.status === ProposalStatus.PENDING) {
+ if (dto.counter_to_id !== lastProposal.id) {
+ throw new BadRequestException({
+ success: false,
+ error: {
+ code: 'PENDING_PROPOSAL_MUST_BE_ANSWERED',
+ message:
+ 'Responda explicitamente a proposta pendente antes de criar outra.',
+ details: { pending_proposal_id: lastProposal.id },
+ },
+ });
+ }
const lastProposerSide =
lastProposal.proposed_by.id === process.specialist_id
? 'SPECIALIST'
@@ -315,7 +339,7 @@ export class ProposalsService {
});
}
- if (originalProposal.proposed_to_id !== userId) {
+ if (originalProposal.proposed_to_id !== partyUserId) {
throw new ForbiddenException({
success: false,
error: {
@@ -338,7 +362,7 @@ export class ProposalsService {
where: {
id: dto.counter_to_id,
process_id: dto.process_id,
- proposed_to_id: userId,
+ proposed_to_id: partyUserId,
status: ProposalStatus.PENDING,
},
data: { status: ProposalStatus.COUNTERED },
@@ -362,7 +386,7 @@ export class ProposalsService {
const proposal = await tx.negotiationProposal.create({
data: {
process_id: dto.process_id,
- proposed_by_id: userId,
+ proposed_by_id: partyUserId,
proposed_to_id: proposedToId,
proposed_value: dto.proposed_value,
message: dto.message,
@@ -379,6 +403,25 @@ export class ProposalsService {
},
});
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: dto.counter_to_id
+ ? 'PROPOSAL_COUNTER'
+ : 'PROPOSAL_CREATE',
+ resourceType: 'PROPOSAL',
+ resourceId: proposal.id,
+ metadata: {
+ processId: dto.process_id,
+ commercialSide: 'SPECIALIST',
+ proposedValue: dto.proposed_value,
+ },
+ },
+ tx,
+ );
+ }
+
return { proposal, process, currency, productValue, isOnClientSide };
});
@@ -432,6 +475,7 @@ export class ProposalsService {
async getByProcess(
processId: string,
userId: string,
+ context?: ActorContext,
): Promise {
this.logger.log(
`[getByProcess] Buscando propostas do processo ${processId}`,
@@ -498,10 +542,11 @@ export class ProposalsService {
}
// 2. Validar que usuário é participante (cliente, especialista ou consultor do cliente)
+ const partyUserId = context?.specialistId ?? userId;
const isParticipant =
- process.client_id === userId ||
- process.specialist_id === userId ||
- process.client?.consultant_id === userId;
+ process.client_id === partyUserId ||
+ process.specialist_id === partyUserId ||
+ (!context && process.client?.consultant_id === userId);
if (!isParticipant) {
throw new ForbiddenException({
@@ -555,9 +600,10 @@ export class ProposalsService {
// 5. Verificar se usuário pode criar proposta (lógica por lado)
const userSide: 'CLIENT' | 'SPECIALIST' | null =
- process.client_id === userId || process.client?.consultant_id === userId
+ process.client_id === partyUserId ||
+ (!context && process.client?.consultant_id === userId)
? 'CLIENT'
- : process.specialist_id === userId
+ : process.specialist_id === partyUserId
? 'SPECIALIST'
: null;
@@ -620,6 +666,7 @@ export class ProposalsService {
proposalId: string,
userId: string,
dto?: RespondProposalDto,
+ context?: ActorContext,
): Promise {
this.logger.log(`[accept] Aceitando proposta ${proposalId}`);
@@ -629,6 +676,7 @@ export class ProposalsService {
proposalId,
userId,
tx,
+ context,
);
const { currency } = requireNegotiationSnapshot(proposal.process);
@@ -668,6 +716,18 @@ export class ProposalsService {
changed_by: userId,
},
});
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PROPOSAL_ACCEPT',
+ resourceType: 'PROPOSAL',
+ resourceId: proposalId,
+ metadata: { processId: proposal.process_id },
+ },
+ tx,
+ );
+ }
const updated = await tx.negotiationProposal.findUniqueOrThrow({
where: { id: proposalId },
@@ -737,7 +797,9 @@ export class ProposalsService {
].filter((recipient) => Boolean(recipient.email));
const changedByName =
- `${proposal.proposed_to.name} ${proposal.proposed_to.surname || ''}`.trim();
+ context?.delegated && context.actor
+ ? `${context.actor.name} ${context.actor.surname}`.trim()
+ : `${proposal.proposed_to.name} ${proposal.proposed_to.surname || ''}`.trim();
Promise.allSettled(
recipients.map((recipient) =>
@@ -777,6 +839,7 @@ export class ProposalsService {
proposalId: string,
userId: string,
dto?: RespondProposalDto,
+ context?: ActorContext,
): Promise {
this.logger.log(`[reject] Rejeitando proposta ${proposalId}`);
@@ -786,6 +849,7 @@ export class ProposalsService {
proposalId,
userId,
tx,
+ context,
);
const { currency } = requireNegotiationSnapshot(proposal.process);
@@ -803,6 +867,21 @@ export class ProposalsService {
if (proposalClaim.count !== 1) {
throw this.proposalResponseConflict(proposalId);
}
+ if (context && this.delegatedAudit) {
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PROPOSAL_REJECT',
+ resourceType: 'PROPOSAL',
+ resourceId: proposalId,
+ metadata: {
+ processId: proposal.process_id,
+ reason: dto?.message ?? null,
+ },
+ },
+ tx,
+ );
+ }
const updated = await tx.negotiationProposal.findUniqueOrThrow({
where: { id: proposalId },
@@ -857,6 +936,7 @@ export class ProposalsService {
async getById(
proposalId: string,
userId: string,
+ context?: ActorContext,
): Promise {
const proposal = await this.prisma.negotiationProposal.findUnique({
where: { id: proposalId },
@@ -889,10 +969,11 @@ export class ProposalsService {
}
// Validar participação (cliente, especialista ou consultor do cliente)
+ const partyUserId = context?.specialistId ?? userId;
const isParticipant =
- proposal.process.client_id === userId ||
- proposal.process.specialist_id === userId ||
- proposal.process.client?.consultant_id === userId;
+ proposal.process.client_id === partyUserId ||
+ proposal.process.specialist_id === partyUserId ||
+ (!context && proposal.process.client?.consultant_id === userId);
if (!isParticipant) {
throw new ForbiddenException({
@@ -915,6 +996,7 @@ export class ProposalsService {
proposalId: string,
userId: string,
client: PrismaService | Prisma.TransactionClient = this.prisma,
+ context?: ActorContext,
): Promise {
const proposal = await client.negotiationProposal.findUnique({
where: { id: proposalId },
@@ -954,8 +1036,15 @@ export class ProposalsService {
}
// Validar destinatário — usuário direto ou consultor do cliente quando a proposta é para o cliente
- const isDirectTarget = proposal.proposed_to_id === userId;
+ if (context && proposal.process.specialist_id !== context.specialistId) {
+ throw new ForbiddenException(
+ 'A proposta não pertence ao especialista representado.',
+ );
+ }
+ const partyUserId = context?.specialistId ?? userId;
+ const isDirectTarget = proposal.proposed_to_id === partyUserId;
const isConsultantOfTargetClient =
+ !context &&
proposal.process.client?.consultant_id === userId &&
proposal.proposed_to_id === proposal.process.client_id;
diff --git a/backend/src/shared/actor-context/actor-context.module.ts b/backend/src/shared/actor-context/actor-context.module.ts
new file mode 100644
index 0000000..c675d53
--- /dev/null
+++ b/backend/src/shared/actor-context/actor-context.module.ts
@@ -0,0 +1,10 @@
+import { Global, Module } from '@nestjs/common';
+import { ActorContextService } from './actor-context.service';
+import { DelegatedActionAuditService } from './delegated-action-audit.service';
+
+@Global()
+@Module({
+ providers: [ActorContextService, DelegatedActionAuditService],
+ exports: [ActorContextService, DelegatedActionAuditService],
+})
+export class ActorContextModule {}
diff --git a/backend/src/shared/actor-context/actor-context.service.spec.ts b/backend/src/shared/actor-context/actor-context.service.spec.ts
new file mode 100644
index 0000000..230b792
--- /dev/null
+++ b/backend/src/shared/actor-context/actor-context.service.spec.ts
@@ -0,0 +1,100 @@
+import { BadRequestException, ForbiddenException } from '@nestjs/common';
+import { ProductType, UserRole } from '@prisma/client';
+import { ActorContextService } from './actor-context.service';
+
+describe('ActorContextService', () => {
+ const activeSpecialist = {
+ id: 'specialist-1',
+ role: UserRole.SPECIALIST,
+ is_active: true,
+ speciality: ProductType.CAR,
+ name: 'Specialist',
+ surname: 'One',
+ };
+ const prisma = {
+ user: { findUnique: jest.fn() },
+ } as any;
+ const service = new ActorContextService(prisma);
+
+ beforeEach(() => jest.clearAllMocks());
+
+ it('requires an explicit represented specialist for ADMIN', async () => {
+ await expect(
+ service.resolve(
+ { id: 'admin-1', role: UserRole.ADMIN } as any,
+ undefined,
+ ),
+ ).rejects.toBeInstanceOf(BadRequestException);
+ expect(prisma.user.findUnique).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [{ ...activeSpecialist, role: UserRole.CUSTOMER }, 'papel'],
+ [{ ...activeSpecialist, is_active: false }, 'inativo'],
+ [{ ...activeSpecialist, speciality: ProductType.BOAT }, 'especialidade'],
+ ])('denies an invalid represented specialist (%s)', async (record) => {
+ prisma.user.findUnique.mockResolvedValue(record);
+
+ await expect(
+ service.resolve(
+ { id: 'admin-1', role: UserRole.ADMIN } as any,
+ activeSpecialist.id,
+ ProductType.CAR,
+ ),
+ ).rejects.toBeInstanceOf(ForbiddenException);
+ });
+
+ it('keeps the ADMIN as actor and the SPECIALIST as represented party', async () => {
+ prisma.user.findUnique.mockResolvedValue(activeSpecialist);
+
+ await expect(
+ service.resolve(
+ { id: 'admin-1', role: UserRole.ADMIN } as any,
+ activeSpecialist.id,
+ ProductType.CAR,
+ ),
+ ).resolves.toEqual({
+ actorId: 'admin-1',
+ actorRole: UserRole.ADMIN,
+ actor: {
+ id: 'admin-1',
+ role: UserRole.ADMIN,
+ name: '',
+ surname: '',
+ },
+ specialistId: activeSpecialist.id,
+ specialist: activeSpecialist,
+ delegated: true,
+ });
+ });
+
+ it('preserves a specialist normal session and rejects injected targets', async () => {
+ const specialistActor = {
+ ...activeSpecialist,
+ role: UserRole.SPECIALIST,
+ } as any;
+
+ await expect(
+ service.resolve(specialistActor, undefined, ProductType.CAR),
+ ).resolves.toMatchObject({
+ actorId: activeSpecialist.id,
+ specialistId: activeSpecialist.id,
+ delegated: false,
+ });
+ await expect(
+ service.resolve(specialistActor, 'specialist-2', ProductType.CAR),
+ ).rejects.toBeInstanceOf(ForbiddenException);
+ });
+
+ it('denies resource IDs owned by another specialist', async () => {
+ prisma.user.findUnique.mockResolvedValue(activeSpecialist);
+ const context = await service.resolve(
+ { id: 'admin-1', role: UserRole.ADMIN } as any,
+ activeSpecialist.id,
+ );
+
+ expect(() =>
+ service.assertResourceSpecialist(context, 'specialist-2'),
+ ).toThrow(ForbiddenException);
+ });
+});
diff --git a/backend/src/shared/actor-context/actor-context.service.ts b/backend/src/shared/actor-context/actor-context.service.ts
new file mode 100644
index 0000000..6f55b2d
--- /dev/null
+++ b/backend/src/shared/actor-context/actor-context.service.ts
@@ -0,0 +1,138 @@
+import {
+ BadRequestException,
+ ForbiddenException,
+ Injectable,
+} from '@nestjs/common';
+import { ProductType, UserRole } from '@prisma/client';
+import { UserEntity } from 'src/auth/entities/user.entity';
+import { PrismaService } from 'src/prisma/prisma.service';
+
+export type ActorContext = {
+ actorId: string;
+ actorRole: UserRole;
+ actor: { id: string; role: UserRole; name: string; surname: string };
+ specialistId: string;
+ specialist: {
+ id: string;
+ role: UserRole;
+ is_active: boolean;
+ speciality: ProductType | null;
+ name: string;
+ surname: string;
+ };
+ delegated: boolean;
+};
+
+@Injectable()
+export class ActorContextService {
+ constructor(private readonly prisma: PrismaService) {}
+
+ async resolve(
+ actor: Pick,
+ targetSpecialistId?: string,
+ requiredSpeciality?: ProductType,
+ ): Promise {
+ if (actor.role === UserRole.SPECIALIST) {
+ if (targetSpecialistId && targetSpecialistId !== actor.id) {
+ throw new ForbiddenException(
+ 'Especialistas não podem operar em nome de outro especialista.',
+ );
+ }
+ if (actor.is_active === false) {
+ throw new ForbiddenException('Especialista inativo.');
+ }
+ if (requiredSpeciality && actor.speciality !== requiredSpeciality) {
+ throw new ForbiddenException(
+ 'A especialidade do especialista não corresponde ao recurso.',
+ );
+ }
+ return {
+ actorId: actor.id,
+ actorRole: actor.role,
+ actor: {
+ id: actor.id,
+ role: actor.role,
+ name: actor.name ?? '',
+ surname: actor.surname ?? '',
+ },
+ specialistId: actor.id,
+ specialist: {
+ id: actor.id,
+ role: actor.role,
+ is_active: true,
+ speciality: actor.speciality ?? null,
+ name: actor.name ?? '',
+ surname: actor.surname ?? '',
+ },
+ delegated: false,
+ };
+ }
+
+ if (actor.role !== UserRole.ADMIN) {
+ throw new ForbiddenException(
+ 'Este papel não pode representar um especialista.',
+ );
+ }
+ if (!targetSpecialistId) {
+ throw new BadRequestException(
+ 'target_specialist_id é obrigatório para ações administrativas.',
+ );
+ }
+
+ const specialist = await this.prisma.user.findUnique({
+ where: { id: targetSpecialistId },
+ select: {
+ id: true,
+ role: true,
+ is_active: true,
+ speciality: true,
+ name: true,
+ surname: true,
+ },
+ });
+ if (!specialist || specialist.role !== UserRole.SPECIALIST) {
+ throw new ForbiddenException(
+ 'O usuário representado deve ser um especialista existente.',
+ );
+ }
+ if (!specialist.is_active) {
+ throw new ForbiddenException('O especialista representado está inativo.');
+ }
+ if (
+ requiredSpeciality &&
+ specialist.speciality !== requiredSpeciality
+ ) {
+ throw new ForbiddenException(
+ 'A especialidade do especialista representado não corresponde ao recurso.',
+ );
+ }
+
+ return {
+ actorId: actor.id,
+ actorRole: actor.role,
+ actor: {
+ id: actor.id,
+ role: actor.role,
+ name: actor.name ?? '',
+ surname: actor.surname ?? '',
+ },
+ specialistId: specialist.id,
+ specialist,
+ delegated: true,
+ };
+ }
+
+ assertResourceSpecialist(
+ context: ActorContext,
+ resourceSpecialistId: string | null | undefined,
+ ): void {
+ if (
+ !resourceSpecialistId ||
+ resourceSpecialistId !== context.specialistId
+ ) {
+ throw new ForbiddenException(
+ 'O recurso não pertence ao especialista representado.',
+ );
+ }
+ }
+}
diff --git a/backend/src/shared/actor-context/delegated-action-audit.service.ts b/backend/src/shared/actor-context/delegated-action-audit.service.ts
new file mode 100644
index 0000000..db61c1d
--- /dev/null
+++ b/backend/src/shared/actor-context/delegated-action-audit.service.ts
@@ -0,0 +1,103 @@
+import { Injectable } from '@nestjs/common';
+import { Prisma, UserRole } from '@prisma/client';
+import { randomUUID } from 'node:crypto';
+import { PrismaService } from 'src/prisma/prisma.service';
+import { ActorContext } from './actor-context.service';
+
+export type DelegatedActionAuditInput = {
+ context: ActorContext;
+ action: string;
+ resourceType: string;
+ resourceId: string;
+ metadata?: Record;
+};
+
+@Injectable()
+export class DelegatedActionAuditService {
+ constructor(private readonly prisma: PrismaService) {}
+
+ async record(
+ input: DelegatedActionAuditInput,
+ client: PrismaService | Prisma.TransactionClient = this.prisma,
+ ): Promise {
+ const metadata = JSON.stringify(input.metadata ?? {});
+ await client.$executeRaw`
+ INSERT INTO "DelegatedActionAudit" (
+ "id", "actor_id", "actor_role", "represented_specialist_id",
+ "action", "resource_type", "resource_id", "metadata", "created_at"
+ ) VALUES (
+ ${randomUUID()}::uuid,
+ ${input.context.actorId}::uuid,
+ ${input.context.actorRole}::"UserRole",
+ ${input.context.specialistId}::uuid,
+ ${input.action},
+ ${input.resourceType},
+ ${input.resourceId},
+ ${metadata}::jsonb,
+ NOW()
+ )
+ `;
+ }
+
+ async listForProcess(
+ context: ActorContext,
+ processId: string,
+ limit = 50,
+ ): Promise<
+ Array<{
+ id: string;
+ action: string;
+ resourceType: string;
+ resourceId: string;
+ metadata: Record | null;
+ createdAt: Date;
+ actor: { id: string; role: UserRole; name: string | null };
+ representedSpecialistId: string;
+ }>
+ > {
+ const boundedLimit = Math.max(1, Math.min(limit, 100));
+ const rows = await this.prisma.$queryRaw<
+ Array<{
+ id: string;
+ actor_id: string;
+ actor_role: UserRole;
+ actor_name: string | null;
+ represented_specialist_id: string;
+ action: string;
+ resource_type: string;
+ resource_id: string;
+ metadata: Record | null;
+ created_at: Date;
+ }>
+ >`
+ SELECT audit."id", audit."actor_id", audit."actor_role",
+ CONCAT_WS(' ', actor."name", actor."surname") AS "actor_name",
+ audit."represented_specialist_id", audit."action",
+ audit."resource_type", audit."resource_id", audit."metadata",
+ audit."created_at"
+ FROM "DelegatedActionAudit" audit
+ LEFT JOIN "User" actor ON actor."id" = audit."actor_id"
+ WHERE audit."represented_specialist_id" = ${context.specialistId}::uuid
+ AND (
+ (audit."resource_type" = 'PROCESS' AND audit."resource_id" = ${processId})
+ OR audit."metadata"->>'processId' = ${processId}
+ )
+ ORDER BY audit."created_at" DESC
+ LIMIT ${boundedLimit}
+ `;
+ return rows.map((row) => ({
+ id: row.id,
+ action: row.action,
+ resourceType: row.resource_type,
+ resourceId: row.resource_id,
+ metadata: row.metadata,
+ createdAt: row.created_at,
+ actor: {
+ id: row.actor_id,
+ role: row.actor_role,
+ name: row.actor_name,
+ },
+ representedSpecialistId: row.represented_specialist_id,
+ }));
+ }
+}
diff --git a/backend/src/shared/helpers/specialist-auth.helper.ts b/backend/src/shared/helpers/specialist-auth.helper.ts
index 51d163c..a78866f 100644
--- a/backend/src/shared/helpers/specialist-auth.helper.ts
+++ b/backend/src/shared/helpers/specialist-auth.helper.ts
@@ -1,4 +1,4 @@
-import { ForbiddenException } from '@nestjs/common';
+import { BadRequestException, ForbiddenException } from '@nestjs/common';
import { UserRole } from '@prisma/client';
import { UserEntity } from 'src/auth/entities/user.entity';
import { SpecialityType } from 'src/auth/dto/auth';
@@ -90,3 +90,13 @@ export function assertSpecialistOwnsProduct(
'Apenas ADMIN e SPECIALIST podem modificar produtos.',
);
}
+
+export function assertNoProductOwnerMutation(
+ dto: Record,
+): void {
+ if (Object.prototype.hasOwnProperty.call(dto, 'specialist_id')) {
+ throw new BadRequestException(
+ 'O responsável pelo produto é imutável nesta rota. Use um comando de transferência dedicado.',
+ );
+ }
+}
diff --git a/backend/src/shared/selects/public-catalog.select.ts b/backend/src/shared/selects/public-catalog.select.ts
index b59ecf0..d241135 100644
--- a/backend/src/shared/selects/public-catalog.select.ts
+++ b/backend/src/shared/selects/public-catalog.select.ts
@@ -17,6 +17,7 @@ export const publicCatalogImageSelect = {
export const publicCarSelect = {
id: true,
specialist_id: true,
+ is_active: true,
marca: true,
modelo: true,
identificador: true,
@@ -39,6 +40,7 @@ export const publicCarSelect = {
export const publicBoatSelect = {
id: true,
specialist_id: true,
+ is_active: true,
marca: true,
modelo: true,
identificador: true,
@@ -64,6 +66,7 @@ export const publicBoatSelect = {
export const publicAircraftSelect = {
id: true,
specialist_id: true,
+ is_active: true,
categoria: true,
ano: true,
marca: true,
diff --git a/backend/test/admin-specialist-journey.e2e-spec.ts b/backend/test/admin-specialist-journey.e2e-spec.ts
new file mode 100644
index 0000000..6f8a700
--- /dev/null
+++ b/backend/test/admin-specialist-journey.e2e-spec.ts
@@ -0,0 +1,578 @@
+import type { INestApplication } from '@nestjs/common';
+import type { PrismaClient } from '@prisma/client';
+import * as bcrypt from 'bcrypt';
+import cookieParser from 'cookie-parser';
+import request from 'supertest';
+import { randomUUID } from 'node:crypto';
+
+const databaseUrl = process.env.ADMIN_SPECIALIST_E2E_DATABASE_URL;
+const describePostgres = databaseUrl ? describe : describe.skip;
+
+const ids = {
+ admin: 'a11d0000-0000-4000-8000-000000000001',
+ specialistA: 'a11d0000-0000-4000-8000-000000000002',
+ specialistB: 'a11d0000-0000-4000-8000-000000000003',
+ customer: 'a11d0000-0000-4000-8000-000000000004',
+};
+const password = 'admin-specialist-e2e-password';
+const credentials = {
+ admin: { email: 'admin-journey@example.test', password },
+ specialistA: { email: 'specialist-a-journey@example.test', password },
+ specialistB: { email: 'specialist-b-journey@example.test', password },
+ customer: { email: 'customer-journey@example.test', password },
+};
+
+describePostgres('ADMIN acting for SPECIALIST journey (HTTP + PostgreSQL)', () => {
+ let app: INestApplication;
+ let prisma: PrismaClient;
+ let adminToken: string;
+ let specialistAToken: string;
+ let customerToken: string;
+ let productId: string;
+ let processId: string;
+ const envelopes = new Map<
+ string,
+ { processId: string; requestFingerprint: string; status: string }
+ >();
+ const previousEnv = new Map();
+
+ function target(id = ids.specialistA) {
+ return { target_specialist_id: id };
+ }
+
+ async function cleanup() {
+ if (!prisma) return;
+ const userIds = Object.values(ids);
+ const processes = await prisma.process.findMany({
+ where: {
+ OR: [
+ { client_id: ids.customer },
+ { specialist_id: { in: [ids.specialistA, ids.specialistB] } },
+ ],
+ },
+ select: { id: true },
+ });
+ const processIds = processes.map(({ id }) => id);
+ await prisma.process.updateMany({
+ where: { id: { in: processIds } },
+ data: { active_contract_id: null, accepted_proposal_id: null },
+ });
+ await prisma.contract.deleteMany({ where: { process_id: { in: processIds } } });
+ await prisma.negotiationProposal.deleteMany({
+ where: { process_id: { in: processIds } },
+ });
+ await prisma.meetingSession.deleteMany({
+ where: { process_id: { in: processIds } },
+ });
+ await prisma.processStatusHistory.deleteMany({
+ where: { processId: { in: processIds } },
+ });
+ await prisma.processRejection.deleteMany({
+ where: { process_id: { in: processIds } },
+ });
+ await prisma.process.deleteMany({ where: { id: { in: processIds } } });
+ await prisma.appointment.deleteMany({
+ where: {
+ OR: [
+ { client_id: ids.customer },
+ { specialist_id: { in: [ids.specialistA, ids.specialistB] } },
+ ],
+ },
+ });
+ await prisma.car.deleteMany({
+ where: { specialist_id: { in: [ids.specialistA, ids.specialistB] } },
+ });
+ await prisma.refreshToken.deleteMany({ where: { user_id: { in: userIds } } });
+ await prisma.$executeRaw`
+ DELETE FROM "DelegatedActionAudit"
+ WHERE "actor_id" IN (${ids.admin}::uuid, ${ids.specialistA}::uuid,
+ ${ids.specialistB}::uuid, ${ids.customer}::uuid)
+ OR "represented_specialist_id" IN
+ (${ids.specialistA}::uuid, ${ids.specialistB}::uuid)
+ `;
+ await prisma.user.deleteMany({ where: { id: { in: userIds } } });
+ }
+
+ beforeAll(async () => {
+ const parsed = new URL(databaseUrl!);
+ if (
+ !['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname) ||
+ parsed.pathname.slice(1) !== 'admin_specialist_test'
+ ) {
+ throw new Error(
+ 'ADMIN_SPECIALIST_E2E_DATABASE_URL must point to loopback/admin_specialist_test',
+ );
+ }
+ for (const [key, value] of Object.entries({
+ DATABASE_URL: databaseUrl,
+ DIRECT_URL: databaseUrl,
+ NOTIFICATIONS_ENABLED: 'false',
+ MEETING_PROVIDER: 'JITSI',
+ JWT_SECRET_ACCESS: 'local-admin-journey-access-secret',
+ JWT_SECRET_REFRESH: 'local-admin-journey-refresh-secret',
+ JWT_SECRET_REFERRAL: 'local-admin-journey-referral-secret',
+ JWT_SECRET_ADVISOR: 'local-admin-journey-advisor-secret',
+ })) {
+ previousEnv.set(key, process.env[key]);
+ process.env[key] = value;
+ }
+
+ const { PrismaClient } =
+ require('@prisma/client') as typeof import('@prisma/client');
+ prisma = new PrismaClient({ datasources: { db: { url: databaseUrl! } } });
+ await prisma.$connect();
+ await cleanup();
+ const hash = await bcrypt.hash(password, 4);
+ await prisma.user.createMany({
+ data: [
+ {
+ id: ids.admin,
+ name: 'Admin',
+ surname: 'Journey',
+ email: credentials.admin.email,
+ password_hash: hash,
+ rg: '99110000001',
+ role: 'ADMIN',
+ is_active: true,
+ },
+ {
+ id: ids.specialistA,
+ name: 'Specialist',
+ surname: 'Alpha',
+ email: credentials.specialistA.email,
+ password_hash: hash,
+ rg: '99110000002',
+ role: 'SPECIALIST',
+ speciality: 'CAR',
+ commission_rate: 70,
+ is_active: true,
+ },
+ {
+ id: ids.specialistB,
+ name: 'Specialist',
+ surname: 'Beta',
+ email: credentials.specialistB.email,
+ password_hash: hash,
+ rg: '99110000003',
+ role: 'SPECIALIST',
+ speciality: 'CAR',
+ commission_rate: 60,
+ is_active: true,
+ },
+ {
+ id: ids.customer,
+ name: 'Customer',
+ surname: 'Journey',
+ email: credentials.customer.email,
+ password_hash: hash,
+ rg: '99110000004',
+ role: 'CUSTOMER',
+ is_active: true,
+ },
+ ],
+ });
+
+ 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 { NotificationService } =
+ require('../src/features/notifications/notification.service') as typeof import('../src/features/notifications/notification.service');
+ 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 { DocuSignService } =
+ require('../src/providers/docusign/docusign.service') as typeof import('../src/providers/docusign/docusign.service');
+ const { DocuSignClient } =
+ require('../src/providers/docusign/docusign.client') as typeof import('../src/providers/docusign/docusign.client');
+ const { PlatformCompanyService } =
+ require('../src/features/platform-company/platform-company.service') as typeof import('../src/features/platform-company/platform-company.service');
+ const { RateLimitGuard } =
+ require('../src/shared/guards/rate-limit.guard') as typeof import('../src/shared/guards/rate-limit.guard');
+ const { localizedValidationExceptionFactory } =
+ require('../src/shared/validation/localized-validation-exception') as typeof import('../src/shared/validation/localized-validation-exception');
+
+ const notifications = new Proxy(
+ {},
+ {
+ get: (_target, property) =>
+ property === 'then' ? undefined : async () => undefined,
+ },
+ );
+ const docusign = {
+ createEnvelopePreview: async (params: any) => {
+ const envelopeId = randomUUID();
+ envelopes.set(envelopeId, {
+ processId: params.processId,
+ requestFingerprint: params.requestFingerprint,
+ status: 'created',
+ });
+ params.onEnvelopeCreated?.(envelopeId);
+ return {
+ envelopeId,
+ previewUrl: `https://docusign.example.test/${envelopeId}`,
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ };
+ },
+ getEnvelopeProcessId: async (id: string) => envelopes.get(id)?.processId,
+ getEnvelopeRequestFingerprint: async (id: string) =>
+ envelopes.get(id)?.requestFingerprint,
+ getEnvelopeStatus: async (id: string) => ({
+ envelopeId: id,
+ status: envelopes.get(id)?.status ?? 'created',
+ }),
+ sendDraftEnvelope: async (id: string) => {
+ const envelope = envelopes.get(id)!;
+ envelope.status = 'sent';
+ return { envelopeId: id, status: 'sent' };
+ },
+ voidDraftEnvelope: async (id: string) => {
+ const envelope = envelopes.get(id);
+ if (envelope) envelope.status = 'voided';
+ },
+ };
+ const module = await Test.createTestingModule({ imports: [AppModule] })
+ .overrideProvider(PrismaService)
+ .useValue(prisma)
+ .overrideProvider(S3Service)
+ .useValue({ getSignedUrl: async (key: string) => key })
+ .overrideProvider(SesService)
+ .useValue({})
+ .overrideProvider(NotificationService)
+ .useValue(notifications)
+ .overrideProvider(ProductImportJobsService)
+ .useValue({})
+ .overrideProvider(ConsultantInviteJobsService)
+ .useValue({})
+ .overrideProvider(ClientInviteJobsService)
+ .useValue({})
+ .overrideProvider(MeetingReminderService)
+ .useValue({})
+ .overrideProvider(DocuSignService)
+ .useValue(docusign)
+ .overrideProvider(DocuSignClient)
+ .useValue({})
+ .overrideProvider(PlatformCompanyService)
+ .useValue({ findOne: async () => ({ default_commission_rate: 10 }) })
+ .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();
+
+ const login = async (credential: { email: string; password: string }) => {
+ const response = await request(app.getHttpServer())
+ .post('/api/auth/login')
+ .send(credential)
+ .expect(201);
+ return response.body.data.access_token as string;
+ };
+ [adminToken, specialistAToken, customerToken] = await Promise.all([
+ login(credentials.admin),
+ login(credentials.specialistA),
+ login(credentials.customer),
+ ]);
+ }, 60_000);
+
+ afterAll(async () => {
+ try {
+ await app?.close();
+ await cleanup();
+ } finally {
+ await prisma?.$disconnect();
+ for (const [key, value] of previousEnv) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ }
+ }, 30_000);
+
+ it('keeps A as executor, S as owner and blocks a mismatched represented specialist', async () => {
+ const created = await request(app.getHttpServer())
+ .post('/api/cars')
+ .auth(adminToken, { type: 'bearer' })
+ .send({
+ specialist_id: ids.specialistA,
+ marca: 'Admin Journey E2E',
+ modelo: 'Owner Alpha',
+ identificador: 'admin-journey-owner-alpha',
+ valor: 100000,
+ currency: 'BRL',
+ estado: 'SP',
+ ano: 2026,
+ })
+ .expect(201);
+ productId = created.body.id;
+ expect(created.body.specialist_id).toBe(ids.specialistA);
+ const inactiveProduct = await prisma.car.create({
+ data: {
+ specialist_id: ids.specialistA,
+ marca: 'Admin Journey E2E',
+ modelo: 'Inactive visible to admin',
+ identificador: 'admin-journey-inactive-alpha',
+ valor: 80000,
+ currency: 'BRL',
+ estado: 'SP',
+ ano: 2025,
+ is_active: false,
+ },
+ });
+ const adminCatalog = await request(app.getHttpServer())
+ .get('/api/cars/admin/all')
+ .query({ ...target(), page: 1, perPage: 20 })
+ .auth(adminToken, { type: 'bearer' })
+ .expect(200);
+ expect(adminCatalog.body.data).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: productId, is_active: true }),
+ expect.objectContaining({ id: inactiveProduct.id, is_active: false }),
+ ]),
+ );
+ const otherCatalog = await request(app.getHttpServer())
+ .get('/api/cars/admin/all')
+ .query({ ...target(ids.specialistB), page: 1, perPage: 20 })
+ .auth(adminToken, { type: 'bearer' })
+ .expect(200);
+ expect(otherCatalog.body.data).toEqual([]);
+
+ await request(app.getHttpServer())
+ .patch(`/api/cars/${productId}`)
+ .query(target(ids.specialistB))
+ .auth(adminToken, { type: 'bearer' })
+ .send({ modelo: 'Must not change' })
+ .expect(403);
+ const customerMutation = await request(app.getHttpServer())
+ .patch(`/api/cars/${productId}`)
+ .query(target())
+ .auth(customerToken, { type: 'bearer' })
+ .send({ modelo: 'Customer must not change' });
+ expect([401, 403]).toContain(customerMutation.status);
+ expect((await prisma.car.findUniqueOrThrow({ where: { id: productId } })).modelo)
+ .toBe('Owner Alpha');
+
+ const audits = await prisma.$queryRaw<
+ Array<{ actor_id: string; represented_specialist_id: string }>
+ >`SELECT "actor_id", "represented_specialist_id"
+ FROM "DelegatedActionAudit" WHERE "resource_id" = ${productId}`;
+ expect(audits).toEqual([
+ {
+ actor_id: ids.admin,
+ represented_specialist_id: ids.specialistA,
+ },
+ ]);
+ });
+
+ it('runs process, appointment, concurrent meeting/proposal and simulated DocuSign end to end', async () => {
+ const processResponse = await request(app.getHttpServer())
+ .post('/api/processes')
+ .auth(adminToken, { type: 'bearer' })
+ .send({
+ client_id: ids.customer,
+ specialist_id: ids.specialistA,
+ product_type: 'CAR',
+ product_id: productId,
+ notes: 'HTTP E2E admin journey',
+ })
+ .expect(201);
+ processId = processResponse.body.data.id;
+ const storedProcess = await prisma.process.findUniqueOrThrow({
+ where: { id: processId },
+ include: { appointment: true },
+ });
+ expect(storedProcess.specialist_id).toBe(ids.specialistA);
+ expect(storedProcess.appointment).toMatchObject({
+ status: 'PENDING',
+ scheduling_method: 'EMAIL',
+ });
+
+ await request(app.getHttpServer())
+ .get(`/api/processes/${processId}`)
+ .query(target(ids.specialistB))
+ .auth(adminToken, { type: 'bearer' })
+ .expect(403);
+ await request(app.getHttpServer())
+ .post(`/api/processes/${processId}/confirm-appointment`)
+ .query(target())
+ .auth(adminToken, { type: 'bearer' })
+ .send({ appointment_datetime: '2099-10-23T17:30:00.000Z' })
+ .expect(201);
+ expect(
+ (await prisma.appointment.findUniqueOrThrow({
+ where: { id: storedProcess.appointment_id! },
+ })).confirmed_by_id,
+ ).toBe(ids.admin);
+
+ await request(app.getHttpServer())
+ .post(`/api/meetings/process/${processId}/start`)
+ .query(target())
+ .auth(adminToken, { type: 'bearer' })
+ .send({})
+ .expect(201);
+ expect(
+ (await prisma.meetingSession.findUniqueOrThrow({
+ where: { process_id: processId },
+ })).started_by_id,
+ ).toBe(ids.admin);
+ const endResults = await Promise.all(
+ [1, 2].map(() =>
+ request(app.getHttpServer())
+ .post(`/api/meetings/process/${processId}/end`)
+ .query(target())
+ .auth(adminToken, { type: 'bearer' }),
+ ),
+ );
+ expect(endResults.map(({ status }) => status)).toEqual([201, 201]);
+ expect(
+ endResults.map(({ body }) => body.data.alreadyEnded).sort(),
+ ).toEqual([false, true]);
+
+ const conversation = await request(app.getHttpServer())
+ .post(`/api/meetings/process/${processId}/conversation-done`)
+ .query(target())
+ .auth(adminToken, { type: 'bearer' })
+ .expect(201);
+ expect(conversation.body.data.processTransition.status).toBe('NEGOTIATION');
+
+ const proposalResults = await Promise.all(
+ [90000, 91000].map((value) =>
+ request(app.getHttpServer())
+ .post('/api/proposals')
+ .query(target())
+ .auth(adminToken, { type: 'bearer' })
+ .send({ process_id: processId, proposed_value: value }),
+ ),
+ );
+ expect(proposalResults.map(({ status }) => status).sort()).toEqual([
+ 201, 400,
+ ]);
+ await expect(
+ prisma.negotiationProposal.count({
+ where: { process_id: processId, status: 'PENDING' },
+ }),
+ ).resolves.toBe(1);
+ const proposal = proposalResults.find(({ status }) => status === 201)!.body
+ .data;
+ expect(proposal.proposed_by.id).toBe(ids.specialistA);
+ await request(app.getHttpServer())
+ .patch(`/api/proposals/${proposal.id}/accept`)
+ .auth(customerToken, { type: 'bearer' })
+ .send({ message: 'Aceita no E2E' })
+ .expect(200);
+
+ const accepted = await prisma.negotiationProposal.findUniqueOrThrow({
+ where: { id: proposal.id },
+ });
+ const contractDto = {
+ operation_id: randomUUID(),
+ return_url: 'http://localhost/admin/journey/contracts/preview-callback',
+ process_id: processId,
+ template_id: 'admin-journey-template',
+ seller_name: 'Seller Distinct',
+ seller_email: 'seller-distinct@example.test',
+ buyer_name: 'Customer Journey',
+ buyer_email: credentials.customer.email,
+ specialist_name: 'Specialist Alpha',
+ specialist_email: credentials.specialistA.email,
+ vehicle_model: 'Owner Alpha',
+ vehicle_year: '2026',
+ vehicle_price: Number(accepted.proposed_value),
+ payment_seller_value: Number(accepted.proposed_value) * 0.9,
+ total_commission_rate: 10,
+ city: 'Sao Paulo',
+ description: 'Approved E2E legal content',
+ };
+ const preview = await request(app.getHttpServer())
+ .post('/api/contracts/preview')
+ .query(target())
+ .auth(adminToken, { type: 'bearer' })
+ .send(contractDto)
+ .expect(201);
+ const envelopeId = preview.body.data.envelope_id;
+ await request(app.getHttpServer())
+ .post(`/api/contracts/send/${envelopeId}`)
+ .query(target())
+ .auth(adminToken, { type: 'bearer' })
+ .send(contractDto)
+ .expect(201);
+
+ const contract = await prisma.contract.findFirstOrThrow({
+ where: { process_id: processId },
+ });
+ expect(contract).toMatchObject({
+ uploaded_by_id: ids.admin,
+ provider_id: envelopeId,
+ status: 'PENDING',
+ });
+ expect(envelopes.get(envelopeId)?.status).toBe('sent');
+ const auditRows = await prisma.$queryRaw>`
+ SELECT "action" FROM "DelegatedActionAudit"
+ WHERE "actor_id" = ${ids.admin}::uuid
+ AND "represented_specialist_id" = ${ids.specialistA}::uuid
+ AND "resource_id" IN (${processId}, ${contract.id}, ${envelopeId})
+ ORDER BY "created_at" ASC
+ `;
+ expect(auditRows.map(({ action }) => action)).toEqual(
+ expect.arrayContaining([
+ 'PROCESS_CREATE',
+ 'CONTRACT_PREVIEW',
+ 'CONTRACT_SEND',
+ ]),
+ );
+ const timeline = await request(app.getHttpServer())
+ .get(`/api/processes/${processId}/admin-timeline`)
+ .query(target())
+ .auth(adminToken, { type: 'bearer' })
+ .expect(200);
+ expect(timeline.body.data).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ action: 'CONTRACT_SEND',
+ actor: expect.objectContaining({ id: ids.admin, role: 'ADMIN' }),
+ representedSpecialistId: ids.specialistA,
+ }),
+ ]),
+ );
+ await request(app.getHttpServer())
+ .get(`/api/processes/${processId}/admin-timeline`)
+ .query(target(ids.specialistB))
+ .auth(adminToken, { type: 'bearer' })
+ .expect(403);
+
+ const specialistOwnList = await request(app.getHttpServer())
+ .get(`/api/processes/specialist/${ids.specialistA}`)
+ .auth(specialistAToken, { type: 'bearer' })
+ .expect(200);
+ expect(specialistOwnList.body.data.some(({ id }: any) => id === processId))
+ .toBe(true);
+ }, 30_000);
+});
From 9fe235be4d681e215b5e40ae7225a6866bafca84 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Fri, 23 Oct 2026 11:35:31 -0300
Subject: [PATCH 53/60] feat(admin): add specialist journey workspace
---
.../admin/AdminCreateProcessDialog.tsx | 115 +++++++++
.../admin/AdminSpecialistJourneyShell.tsx | 156 ++++++++++++
.../src/components/processes/ProcessCard.tsx | 98 +++++++-
.../processes/UpdateProcessStatusModal.tsx | 14 +-
.../src/components/specialist/ProductForm.tsx | 44 +++-
.../AdminSpecialistJourneyContext.tsx | 17 ++
.../src/lib/admin-specialist-journey.test.ts | 61 +++++
frontend/src/lib/admin-specialist-journey.ts | 62 +++++
frontend/src/lib/navigation.test.ts | 5 +-
frontend/src/lib/navigation.ts | 5 +
.../admin/SpecialistJourneyOverviewPage.tsx | 54 +++++
.../admin/SpecialistJourneyProductsPage.tsx | 222 ++++++++++++++++++
.../src/pages/meetings/MeetingRoomPage.tsx | 8 +-
.../src/pages/negotiation/NegotiationPage.tsx | 22 +-
.../pages/specialist/CreateContractPage.tsx | 23 +-
.../src/pages/specialist/ProcessesPage.tsx | 52 ++--
frontend/src/routes/routes.tsx | 103 ++++++++
.../admin-specialist-journey.service.ts | 116 +++++++++
frontend/src/services/api.ts | 13 +-
frontend/src/services/processes.service.ts | 28 ++-
frontend/src/services/specialists.service.ts | 1 +
21 files changed, 1166 insertions(+), 53 deletions(-)
create mode 100644 frontend/src/components/admin/AdminCreateProcessDialog.tsx
create mode 100644 frontend/src/components/admin/AdminSpecialistJourneyShell.tsx
create mode 100644 frontend/src/contexts/AdminSpecialistJourneyContext.tsx
create mode 100644 frontend/src/lib/admin-specialist-journey.test.ts
create mode 100644 frontend/src/lib/admin-specialist-journey.ts
create mode 100644 frontend/src/pages/admin/SpecialistJourneyOverviewPage.tsx
create mode 100644 frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx
create mode 100644 frontend/src/services/admin-specialist-journey.service.ts
diff --git a/frontend/src/components/admin/AdminCreateProcessDialog.tsx b/frontend/src/components/admin/AdminCreateProcessDialog.tsx
new file mode 100644
index 0000000..664cb07
--- /dev/null
+++ b/frontend/src/components/admin/AdminCreateProcessDialog.tsx
@@ -0,0 +1,115 @@
+import { useEffect, useState } from "react";
+import { useAdminSpecialistJourney } from "../../contexts/AdminSpecialistJourneyContext";
+import {
+ getAdminClientOptions,
+ getAdminSpecialistProducts,
+ type AdminCatalogProduct,
+ type AdminClientOption,
+} from "../../services/admin-specialist-journey.service";
+import { createProcess } from "../../services/processes.service";
+import Button from "../ui/button";
+import { Dialog, DialogContent } from "../ui/dialog";
+
+export default function AdminCreateProcessDialog({
+ open,
+ onClose,
+ onCreated,
+}: {
+ open: boolean;
+ onClose: () => void;
+ onCreated: () => void;
+}) {
+ const context = useAdminSpecialistJourney();
+ const [clients, setClients] = useState([]);
+ const [products, setProducts] = useState([]);
+ const [clientId, setClientId] = useState("");
+ const [productId, setProductId] = useState("");
+ const [notes, setNotes] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+ const [error, setError] = useState(null);
+
+ useEffect(() => {
+ if (!open || !context) return;
+ setError(null);
+ void Promise.all([
+ getAdminClientOptions(),
+ getAdminSpecialistProducts(context.specialist.speciality, 1, 100),
+ ])
+ .then(([clientOptions, catalog]) => {
+ setClients(clientOptions);
+ setProducts(catalog.products.filter((product) => product.is_active));
+ })
+ .catch(() => setError("Não foi possível carregar clientes e produtos."));
+ }, [open, context?.targetSpecialistId]);
+
+ if (!context) return null;
+
+ const submit = async (event: React.FormEvent) => {
+ event.preventDefault();
+ if (!clientId) return;
+ setSubmitting(true);
+ setError(null);
+ try {
+ await createProcess({
+ client_id: clientId,
+ specialist_id: context.targetSpecialistId,
+ ...(productId
+ ? {
+ product_id: productId,
+ product_type: context.specialist.speciality,
+ }
+ : {}),
+ notes: notes || undefined,
+ });
+ setClientId("");
+ setProductId("");
+ setNotes("");
+ onCreated();
+ onClose();
+ } catch (caught: any) {
+ setError(
+ caught?.friendlyMessage ||
+ caught?.response?.data?.message ||
+ "Não foi possível criar o processo e seu agendamento.",
+ );
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ return (
+ !next && onClose()}>
+
+
+
+
+ );
+}
diff --git a/frontend/src/components/admin/AdminSpecialistJourneyShell.tsx b/frontend/src/components/admin/AdminSpecialistJourneyShell.tsx
new file mode 100644
index 0000000..70816e7
--- /dev/null
+++ b/frontend/src/components/admin/AdminSpecialistJourneyShell.tsx
@@ -0,0 +1,156 @@
+import { useEffect, useMemo, useState, type ReactNode } from "react";
+import { NavLink, useNavigate } from "react-router-dom";
+import { BriefcaseBusiness, Loader2 } from "lucide-react";
+import {
+ AdminSpecialistJourneyProvider,
+} from "../../contexts/AdminSpecialistJourneyContext";
+import {
+ persistAdminSpecialistTarget,
+ readAdminSpecialistTarget,
+} from "../../lib/admin-specialist-journey";
+import {
+ getSpecialists,
+ type Specialist,
+} from "../../services/specialists.service";
+import { useAuth } from "../../store/authStateManager";
+import { Alert } from "../ui/alert";
+
+function clearTransientJourneyState(): void {
+ if (typeof window === "undefined") return;
+ for (let index = window.sessionStorage.length - 1; index >= 0; index -= 1) {
+ const key = window.sessionStorage.key(index);
+ if (key?.startsWith("contract-preview-operation:")) {
+ window.sessionStorage.removeItem(key);
+ }
+ }
+}
+
+export default function AdminSpecialistJourneyShell({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ const navigate = useNavigate();
+ const admin = useAuth((state) => state.user);
+ const [specialists, setSpecialists] = useState([]);
+ const [selectedId, setSelectedId] = useState(readAdminSpecialistTarget());
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+
+ useEffect(() => {
+ void getSpecialists()
+ .then((items) => {
+ const activeItems = items.filter((item) => item.is_active !== false);
+ setSpecialists(activeItems);
+ const stored = readAdminSpecialistTarget();
+ if (stored && !activeItems.some((item) => item.id === stored)) {
+ persistAdminSpecialistTarget(null);
+ setSelectedId(null);
+ }
+ })
+ .catch(() => setError("Não foi possível carregar os especialistas."))
+ .finally(() => setLoading(false));
+ }, []);
+
+ const selected = useMemo(
+ () => specialists.find((item) => item.id === selectedId) ?? null,
+ [selectedId, specialists],
+ );
+
+ const changeSpecialist = (nextId: string) => {
+ const normalized = nextId || null;
+ persistAdminSpecialistTarget(normalized);
+ clearTransientJourneyState();
+ setSelectedId(normalized);
+ navigate("/admin/journey", { replace: true });
+ };
+
+ return (
+
+
+
+
+
+
+
Jornada comercial assistida
+
+
+ O administrador executa as ações; o especialista escolhido continua
+ sendo o responsável comercial.
+
+
+
+ Especialista representado
+ changeSpecialist(event.target.value)}
+ className="mt-1 w-full rounded-lg border border-border bg-surface px-3 py-2"
+ disabled={loading}
+ >
+ Selecione um especialista
+ {specialists.map((specialist) => (
+
+ {specialist.name} {specialist.surname} · {specialist.speciality}
+
+ ))}
+
+
+
+
+ {loading && (
+
+ Carregando especialistas…
+
+ )}
+ {error && {error} }
+ {selected && (
+
+ Operando em nome de {selected.name} {selected.surname}
+
+ Executor: {admin?.name} {admin?.surname} (ADMIN)
+
+
+ )}
+
+
+ {[
+ ["/admin/journey", "Visão geral"],
+ ["/admin/journey/products", "Catálogo"],
+ ["/admin/journey/processes", "Processos e agenda"],
+ ].map(([to, label]) => (
+
+ `rounded-lg px-3 py-2 text-sm font-medium ${
+ isActive
+ ? "bg-ink text-surface"
+ : "bg-border-soft text-ink-soft hover:text-ink"
+ }`
+ }
+ >
+ {label}
+
+ ))}
+
+
+
+ {!loading && !selected && !error && (
+
+ Escolha um especialista ativo para abrir catálogo, processos,
+ reuniões, propostas e contratos.
+
+ )}
+
+ {selected && (
+
+ {children}
+
+ )}
+
+ );
+}
diff --git a/frontend/src/components/processes/ProcessCard.tsx b/frontend/src/components/processes/ProcessCard.tsx
index 29b8013..a1765f9 100644
--- a/frontend/src/components/processes/ProcessCard.tsx
+++ b/frontend/src/components/processes/ProcessCard.tsx
@@ -28,6 +28,7 @@ import { getContextualStatusMessage } from "../../utils/processStatusMessages";
import {
getProcessCompletionReason,
getProcessWithActiveContract,
+ getAdminProcessTimeline,
confirmAppointment,
cancelAppointment,
getMeetingByProcess,
@@ -35,8 +36,10 @@ import {
startMeeting,
updateProcessStatus,
type MeetingSession,
+ type DelegatedProcessTimelineEvent,
} from "../../services/processes.service";
import { rescheduleAppointment } from "../../services/appointments.service";
+import { adminJourneyRoute } from "../../lib/admin-specialist-journey";
function getActionErrorMessage(error: unknown, fallback: string): string {
if (typeof error === "object" && error !== null) {
@@ -80,6 +83,7 @@ interface ProcessCardProps {
isClientView?: boolean; // Se true, remove botões de ação (apenas visualização)
onSelectProduct?: () => void; // Callback para abrir seleção de produto em consultoria
specialistSpeciality?: SpecialityType; // Especialidade do especialista para filtrar produtos
+ adminJourney?: boolean;
}
/**
@@ -95,12 +99,16 @@ export default function ProcessCard({
onStatusUpdated,
isClientView = false,
onSelectProduct,
+ adminJourney = false,
}: 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 [delegatedTimeline, setDelegatedTimeline] = useState<
+ DelegatedProcessTimelineEvent[]
+ >([]);
const [isConfirming, setIsConfirming] = useState(false);
const [isCancelling, setIsCancelling] = useState(false);
const [meetingSession, setMeetingSession] = useState(
@@ -217,6 +225,24 @@ export default function ProcessCard({
};
}, [process]);
+ useEffect(() => {
+ let current = true;
+ if (!adminJourney || !isExpanded) {
+ setDelegatedTimeline([]);
+ return () => {
+ current = false;
+ };
+ }
+ void getAdminProcessTimeline(process.id)
+ .then((events) => {
+ if (current) setDelegatedTimeline(events);
+ })
+ .catch((error) => console.error("Error loading delegated timeline:", error));
+ return () => {
+ current = false;
+ };
+ }, [adminJourney, isExpanded, process.id]);
+
useEffect(() => {
let current = true;
@@ -265,7 +291,11 @@ export default function ProcessCard({
setIsStartingMeeting(true);
await startMeeting(process.id);
onStatusUpdated?.();
- navigate(`/processes/${process.id}/meeting`);
+ navigate(
+ adminJourney
+ ? adminJourneyRoute("meeting", process.id)
+ : `/processes/${process.id}/meeting`,
+ );
} catch (error) {
console.error("Error starting meeting:", error);
alert(
@@ -280,7 +310,11 @@ export default function ProcessCard({
};
const handleJoinMeeting = () => {
- navigate(`/processes/${process.id}/meeting`);
+ navigate(
+ adminJourney
+ ? adminJourneyRoute("meeting", process.id)
+ : `/processes/${process.id}/meeting`,
+ );
};
const handleConversationDone = async () => {
@@ -368,9 +402,18 @@ export default function ProcessCard({
if (!confirmed) return;
+ const administrativeReason = adminJourney
+ ? window.prompt("Informe o motivo do cancelamento administrativo:")
+ : undefined;
+ if (adminJourney && !administrativeReason?.trim()) return;
+
try {
setIsCancelling(true);
- await cancelAppointment(process.id);
+ if (adminJourney) {
+ await cancelAppointment(process.id, administrativeReason!.trim());
+ } else {
+ await cancelAppointment(process.id);
+ }
} catch (error) {
console.error("Error cancelling appointment:", error);
alert(
@@ -431,7 +474,13 @@ export default function ProcessCard({
{process.status === "NEGOTIATION" && !isConsultancy && !isExpanded && (
navigate(`/processes/${process.id}/negotiation`)}
+ onClick={() =>
+ navigate(
+ adminJourney
+ ? adminJourneyRoute("negotiation", process.id)
+ : `/processes/${process.id}/negotiation`,
+ )
+ }
className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white text-xs md:text-sm font-medium rounded-lg shadow-lg hover:bg-blue-700 transition-colors whitespace-nowrap"
>
@@ -778,7 +827,13 @@ export default function ProcessCard({
{process.status === "NEGOTIATION" && !isConsultancy && !isExpanded && (
navigate(`/processes/${process.id}/negotiation`)}
+ onClick={() =>
+ navigate(
+ adminJourney
+ ? adminJourneyRoute("negotiation", process.id)
+ : `/processes/${process.id}/negotiation`,
+ )
+ }
className="w-full px-4 py-2 bg-blue-600 text-white text-xs font-medium rounded-lg shadow-lg hover:bg-blue-700 transition-colors inline-flex items-center justify-center gap-1"
>
@@ -853,6 +908,9 @@ export default function ProcessCard({
Contrato recusado ou cancelado
)}
+
+ Estado externo: {activeContract.provider_status || activeContract.status}
+
)}
@@ -989,6 +1047,27 @@ export default function ProcessCard({
{/* Expandable Details Section */}
{isExpanded && (
+ {adminJourney && (
+
+
+ Última ação delegada
+
+ {delegatedTimeline[0] ? (
+
+ {delegatedTimeline[0].action} por{" "}
+
+ {delegatedTimeline[0].actor.name || delegatedTimeline[0].actor.id}
+ {" "}
+ ({delegatedTimeline[0].actor.role}), em nome do especialista,
+ em {new Date(delegatedTimeline[0].createdAt).toLocaleString("pt-BR")}.
+
+ ) : (
+
+ Nenhuma ação administrativa registrada neste processo.
+
+ )}
+
+ )}
{product && (
@@ -1052,7 +1131,13 @@ export default function ProcessCard({
{/* Negotiation Button: Only show if status is NEGOTIATION and process has product */}
{process.status === "NEGOTIATION" && !isConsultancy && (
navigate(`/processes/${process.id}/negotiation`)}
+ onClick={() =>
+ navigate(
+ adminJourney
+ ? adminJourneyRoute("negotiation", process.id)
+ : `/processes/${process.id}/negotiation`,
+ )
+ }
className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 md:px-4 md:py-2 bg-blue-600 text-white text-xs md:text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors whitespace-nowrap"
>
@@ -1134,6 +1219,7 @@ export default function ProcessCard({
onStatusUpdated?.();
}}
process={process}
+ reasonRequired={adminJourney}
/>
;
+ reasonRequired?: boolean;
}
interface UpdateProcessFormData {
@@ -53,6 +54,7 @@ export default function UpdateProcessStatusModal({
process,
action = "status",
returnFocusRef,
+ reasonRequired = false,
}: UpdateProcessStatusModalProps) {
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState(null);
@@ -103,7 +105,11 @@ export default function UpdateProcessStatusModal({
setIsSubmitting(true);
setError(null);
- await rejectProcess(process.id, rejectionReason || undefined);
+ if (reasonRequired && !rejectionReason.trim()) {
+ setError("Informe o motivo da rejeição administrativa.");
+ return;
+ }
+ await rejectProcess(process.id, rejectionReason.trim() || undefined);
setRejectionReason("");
reset();
@@ -164,7 +170,9 @@ export default function UpdateProcessStatusModal({
className="block text-sm font-medium text-gray-700 mb-2"
>
Motivo da Rejeição{" "}
- (opcional)
+
+ {reasonRequired ? "(obrigatório para administrador)" : "(opcional)"}
+
diff --git a/frontend/src/components/specialist/ProductForm.tsx b/frontend/src/components/specialist/ProductForm.tsx
index fc732c4..3cfbb61 100644
--- a/frontend/src/components/specialist/ProductForm.tsx
+++ b/frontend/src/components/specialist/ProductForm.tsx
@@ -36,6 +36,8 @@ import {
import { Dialog, DialogContent } from "../../components/ui/dialog";
import type { ProductCurrency, SpecialityType, UserRole } from "../../types/types";
import { getProductSaveErrorMessage } from "../../lib/product-error-message";
+import { useAdminSpecialistJourney } from "../../contexts/AdminSpecialistJourneyContext";
+import { adminJourneyRoute } from "../../lib/admin-specialist-journey";
type ProductType = "CAR" | "BOAT" | "AIRCRAFT";
@@ -68,7 +70,9 @@ export default function ProductForm({
}: ProductFormProps) {
const navigate = useNavigate();
const user = useAuth((state) => state.user);
- const userSpeciality = user?.speciality as SpecialityType;
+ const adminJourney = useAdminSpecialistJourney();
+ const userSpeciality = (adminJourney?.specialist.speciality ??
+ user?.speciality) as SpecialityType;
const userRole = user?.role as UserRole;
// Define o tipo de produto baseado na especialidade do usuário
@@ -82,13 +86,15 @@ export default function ProductForm({
// Validação de autorização: ADMIN pode criar qualquer tipo, SPECIALIST só do seu tipo
const canCreateProductType = useCallback(
(type: ProductType): boolean => {
- if (userRole === "ADMIN") return true;
+ if (userRole === "ADMIN") {
+ return Boolean(adminJourney) && userSpeciality === type;
+ }
if (userRole === "SPECIALIST") {
return userSpeciality === type;
}
return false;
},
- [userRole, userSpeciality],
+ [adminJourney, userRole, userSpeciality],
);
// Verificar se o usuário pode criar o tipo de produto selecionado
@@ -215,8 +221,12 @@ export default function ProductForm({
};
// Vincula o produto ao especialista logado (quando aplicável)
- if (user?.role === "SPECIALIST" && user.id) {
- formattedData.specialist_id = user.id;
+ if (mode === "create") {
+ if (user?.role === "SPECIALIST" && user.id) {
+ formattedData.specialist_id = user.id;
+ } else if (user?.role === "ADMIN" && adminJourney) {
+ formattedData.specialist_id = adminJourney.targetSpecialistId;
+ }
}
// Adiciona campos específicos de cada tipo de produto (apenas se preenchidos)
@@ -272,14 +282,20 @@ export default function ProductForm({
try {
await assignProductToProcess(processId, productType, createdId);
window.alert("Produto criado e vinculado ao processo com sucesso!");
- navigate(`/processes/${processId}/negotiation`);
+ navigate(
+ adminJourney
+ ? adminJourneyRoute("negotiation", processId)
+ : `/processes/${processId}/negotiation`,
+ );
return;
} catch (assignError: any) {
console.error("Erro ao vincular produto ao processo:", assignError);
window.alert(
"Produto criado, mas não foi possível vinculá-lo automaticamente ao processo. Use a tela de seleção de produto para vinculá-lo manualmente.",
);
- navigate("/specialist/products");
+ navigate(
+ adminJourney ? adminJourneyRoute("products") : "/specialist/products",
+ );
return;
}
}
@@ -301,7 +317,9 @@ export default function ProductForm({
}
// Navega para a lista de produtos
- navigate("/specialist/products");
+ navigate(
+ adminJourney ? adminJourneyRoute("products") : "/specialist/products",
+ );
} catch (error: any) {
console.error("Erro ao salvar produto:", error);
@@ -333,7 +351,7 @@ export default function ProductForm({
)}
{/* Seletor de Tipo de Produto (apenas no modo criar e se for ADMIN sem especialidade) */}
- {mode === "create" && userRole === "ADMIN" && (
+ {mode === "create" && userRole === "ADMIN" && !adminJourney && (
@@ -449,7 +467,11 @@ export default function ProductForm({
navigate("/specialist/products")}
+ onClick={() =>
+ navigate(
+ adminJourney ? adminJourneyRoute("products") : "/specialist/products",
+ )
+ }
className="px-6 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition"
disabled={isSubmitting}
>
diff --git a/frontend/src/contexts/AdminSpecialistJourneyContext.tsx b/frontend/src/contexts/AdminSpecialistJourneyContext.tsx
new file mode 100644
index 0000000..b162aad
--- /dev/null
+++ b/frontend/src/contexts/AdminSpecialistJourneyContext.tsx
@@ -0,0 +1,17 @@
+import { createContext, useContext } from "react";
+import type { Specialist } from "../services/specialists.service";
+
+export type AdminSpecialistJourneyValue = {
+ specialist: Specialist;
+ targetSpecialistId: string;
+};
+
+const AdminSpecialistJourneyContext =
+ createContext(null);
+
+export const AdminSpecialistJourneyProvider =
+ AdminSpecialistJourneyContext.Provider;
+
+export function useAdminSpecialistJourney(): AdminSpecialistJourneyValue | null {
+ return useContext(AdminSpecialistJourneyContext);
+}
diff --git a/frontend/src/lib/admin-specialist-journey.test.ts b/frontend/src/lib/admin-specialist-journey.test.ts
new file mode 100644
index 0000000..9f3a82c
--- /dev/null
+++ b/frontend/src/lib/admin-specialist-journey.test.ts
@@ -0,0 +1,61 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it } from "vitest";
+import {
+ ADMIN_SPECIALIST_TARGET_KEY,
+ adminJourneyRoute,
+ attachAdminSpecialistTarget,
+ persistAdminSpecialistTarget,
+ readAdminSpecialistTarget,
+} from "./admin-specialist-journey";
+
+describe("admin specialist journey context", () => {
+ beforeEach(() => localStorage.clear());
+
+ it("persists only the represented specialist identity", () => {
+ persistAdminSpecialistTarget("specialist-1");
+ expect(readAdminSpecialistTarget()).toBe("specialist-1");
+ expect(localStorage.getItem(ADMIN_SPECIALIST_TARGET_KEY)).toBe(
+ "specialist-1",
+ );
+ persistAdminSpecialistTarget(null);
+ expect(readAdminSpecialistTarget()).toBeNull();
+ });
+
+ it("adds the explicit target only to admin journey domain requests", () => {
+ const config = attachAdminSpecialistTarget(
+ { url: "/processes/p1/status", params: { page: 1 } } as any,
+ "ADMIN",
+ "specialist-1",
+ );
+ expect(config.params).toEqual({
+ page: 1,
+ target_specialist_id: "specialist-1",
+ });
+ expect(
+ attachAdminSpecialistTarget(
+ { url: "/processes/p1/status" } as any,
+ "SPECIALIST",
+ "specialist-1",
+ ).params,
+ ).toBeUndefined();
+ expect(
+ attachAdminSpecialistTarget(
+ { url: "/admin/database/users" } as any,
+ "ADMIN",
+ "specialist-1",
+ ).params,
+ ).toBeUndefined();
+ });
+
+ it("keeps every operational route inside the admin workspace", () => {
+ expect(adminJourneyRoute("negotiation", "p1")).toBe(
+ "/admin/journey/processes/p1/negotiation",
+ );
+ expect(adminJourneyRoute("meeting", "p1")).toBe(
+ "/admin/journey/processes/p1/meeting",
+ );
+ expect(adminJourneyRoute("contract", "p1")).toBe(
+ "/admin/journey/contracts/new?processId=p1",
+ );
+ });
+});
diff --git a/frontend/src/lib/admin-specialist-journey.ts b/frontend/src/lib/admin-specialist-journey.ts
new file mode 100644
index 0000000..ed2aca6
--- /dev/null
+++ b/frontend/src/lib/admin-specialist-journey.ts
@@ -0,0 +1,62 @@
+import type { InternalAxiosRequestConfig } from "axios";
+
+export const ADMIN_SPECIALIST_TARGET_KEY = "highclass.admin.specialistTarget";
+
+const TARGETED_RESOURCES = [
+ "cars",
+ "boats",
+ "aircrafts",
+ "processes",
+ "appointments",
+ "meetings",
+ "proposals",
+ "contracts",
+ "product-import-jobs",
+] as const;
+
+export function readAdminSpecialistTarget(): string | null {
+ if (typeof window === "undefined") return null;
+ return window.localStorage.getItem(ADMIN_SPECIALIST_TARGET_KEY);
+}
+
+export function persistAdminSpecialistTarget(id: string | null): void {
+ if (typeof window === "undefined") return;
+ if (id) window.localStorage.setItem(ADMIN_SPECIALIST_TARGET_KEY, id);
+ else window.localStorage.removeItem(ADMIN_SPECIALIST_TARGET_KEY);
+}
+
+export function isTargetedJourneyRequest(url?: string): boolean {
+ if (!url) return false;
+ const pathname = url.replace(/^https?:\/\/[^/]+\/?/, "").replace(/^\//, "");
+ return TARGETED_RESOURCES.some(
+ (resource) => pathname === resource || pathname.startsWith(`${resource}/`),
+ );
+}
+
+export function attachAdminSpecialistTarget(
+ config: InternalAxiosRequestConfig,
+ role: string | undefined,
+ targetId: string | null,
+): InternalAxiosRequestConfig {
+ if (role !== "ADMIN" || !targetId || !isTargetedJourneyRequest(config.url)) {
+ return config;
+ }
+ config.params = { ...(config.params ?? {}), target_specialist_id: targetId };
+ return config;
+}
+
+export function adminJourneyRoute(
+ section: "products" | "processes" | "negotiation" | "meeting" | "contract",
+ processId?: string,
+): string {
+ if (section === "negotiation" && processId) {
+ return `/admin/journey/processes/${processId}/negotiation`;
+ }
+ if (section === "meeting" && processId) {
+ return `/admin/journey/processes/${processId}/meeting`;
+ }
+ if (section === "contract") {
+ return `/admin/journey/contracts/new${processId ? `?processId=${processId}` : ""}`;
+ }
+ return `/admin/journey/${section}`;
+}
diff --git a/frontend/src/lib/navigation.test.ts b/frontend/src/lib/navigation.test.ts
index 373aeb9..37389b0 100644
--- a/frontend/src/lib/navigation.test.ts
+++ b/frontend/src/lib/navigation.test.ts
@@ -49,8 +49,9 @@ describe("getSidebarLinks", () => {
[
"ADMIN",
[
- { to: "/admin/dashboard", label: "Dashboard" },
- { to: "/admin/companies", label: "Escritórios" },
+ { to: "/admin/dashboard", label: "Dashboard" },
+ { to: "/admin/journey", label: "Jornada por especialista" },
+ { to: "/admin/companies", label: "Escritórios" },
{ to: "/office/consultants", label: "Consultores" },
{ to: "/admin/specialists", label: "Especialistas" },
{ to: "/admin/commissions", label: "Comissões" },
diff --git a/frontend/src/lib/navigation.ts b/frontend/src/lib/navigation.ts
index eb19de5..a094eeb 100644
--- a/frontend/src/lib/navigation.ts
+++ b/frontend/src/lib/navigation.ts
@@ -94,6 +94,11 @@ const ROLE_SIDEBAR_LINKS: Record<
],
ADMIN: [
{ to: "/admin/dashboard", label: "Dashboard", icon: "dashboard" },
+ {
+ to: "/admin/journey",
+ label: "Jornada por especialista",
+ icon: "clipboard-list",
+ },
{ to: "/admin/companies", label: "Escritórios", icon: "building" },
{ to: "/office/consultants", label: "Consultores", icon: "users" },
{
diff --git a/frontend/src/pages/admin/SpecialistJourneyOverviewPage.tsx b/frontend/src/pages/admin/SpecialistJourneyOverviewPage.tsx
new file mode 100644
index 0000000..fd31e26
--- /dev/null
+++ b/frontend/src/pages/admin/SpecialistJourneyOverviewPage.tsx
@@ -0,0 +1,54 @@
+import { Link } from "react-router-dom";
+import { FileText, Package, UsersRound } from "lucide-react";
+import { useAdminSpecialistJourney } from "../../contexts/AdminSpecialistJourneyContext";
+
+export default function SpecialistJourneyOverviewPage() {
+ const context = useAdminSpecialistJourney();
+ if (!context) return null;
+
+ const cards = [
+ {
+ to: "/admin/journey/products",
+ icon: Package,
+ title: "Catálogo",
+ description: "Crie, edite e importe produtos do especialista, inclusive acompanhando inativos.",
+ },
+ {
+ to: "/admin/journey/processes",
+ icon: UsersRound,
+ title: "Processos, agenda e reunião",
+ description: "Acompanhe o cliente e execute somente as ações válidas para a etapa atual.",
+ },
+ {
+ to: "/admin/journey/processes",
+ icon: FileText,
+ title: "Negociação e contrato",
+ description: "Abra um processo para propor, revisar a timeline e preparar o contrato.",
+ },
+ ];
+
+ return (
+
+
+ Carteira de {context.specialist.name} {context.specialist.surname}
+
+
+ Especialidade: {context.specialist.speciality}. A troca de especialista
+ volta a esta visão e descarta contexto transitório de processo e preview.
+
+
+ {cards.map(({ to, icon: Icon, title, description }) => (
+
+
+
{title}
+
{description}
+
+ ))}
+
+
+ );
+}
diff --git a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx
new file mode 100644
index 0000000..8d76069
--- /dev/null
+++ b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx
@@ -0,0 +1,222 @@
+import { useEffect, useState } from "react";
+import { ChevronLeft, ChevronRight, Plus, Upload } from "lucide-react";
+import { useNavigate } from "react-router-dom";
+import { useAdminSpecialistJourney } from "../../contexts/AdminSpecialistJourneyContext";
+import {
+ getAdminSpecialistProducts,
+ importAdminCatalogCsv,
+ previewAdminCatalogCsv,
+ type AdminCatalogProduct,
+ type CsvImportPreview,
+ type ProductImportMode,
+} from "../../services/admin-specialist-journey.service";
+import { deleteCar } from "../../services/cars.service";
+import { deleteBoat } from "../../services/boats.service";
+import { deleteAircraft } from "../../services/aircrafts.service";
+import { formatCurrency } from "../../lib/currency";
+import Button from "../../components/ui/button";
+import { Alert } from "../../components/ui/alert";
+
+export default function SpecialistJourneyProductsPage() {
+ const context = useAdminSpecialistJourney();
+ const navigate = useNavigate();
+ const [products, setProducts] = useState([]);
+ const [page, setPage] = useState(1);
+ const [totalPages, setTotalPages] = useState(1);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(null);
+ const [file, setFile] = useState(null);
+ const [mode, setMode] = useState("ADDITIVE");
+ const [preview, setPreview] = useState(null);
+ const [syncConfirmed, setSyncConfirmed] = useState(false);
+ const [importing, setImporting] = useState(false);
+
+ if (!context) return null;
+ const productType = context.specialist.speciality;
+
+ const load = async (nextPage = page) => {
+ setLoading(true);
+ setError(null);
+ try {
+ const result = await getAdminSpecialistProducts(productType, nextPage, 20);
+ setProducts(result.products);
+ setPage(result.pagination.current_page);
+ setTotalPages(Math.max(1, Math.ceil(result.pagination.total_pages)));
+ } catch {
+ setError("Não foi possível carregar o catálogo administrativo.");
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ useEffect(() => {
+ setPage(1);
+ setPreview(null);
+ setFile(null);
+ void load(1);
+ }, [context.targetSpecialistId]);
+
+ const remove = async (id: string) => {
+ if (!window.confirm("Desativar este produto do catálogo?")) return;
+ if (productType === "CAR") await deleteCar(id);
+ else if (productType === "BOAT") await deleteBoat(id);
+ else await deleteAircraft(id);
+ await load();
+ };
+
+ const runPreview = async () => {
+ if (!file) return;
+ setError(null);
+ setSyncConfirmed(false);
+ try {
+ setPreview(
+ await previewAdminCatalogCsv(
+ productType,
+ context.targetSpecialistId,
+ file,
+ mode,
+ ),
+ );
+ } catch {
+ setError("CSV inválido ou incompatível com a especialidade selecionada.");
+ }
+ };
+
+ const runImport = async () => {
+ if (!file || !preview) return;
+ if (mode === "SYNCHRONIZE" && !syncConfirmed) return;
+ setImporting(true);
+ setError(null);
+ try {
+ const result = await importAdminCatalogCsv(
+ productType,
+ context.targetSpecialistId,
+ file,
+ mode,
+ syncConfirmed,
+ );
+ window.alert(result.message);
+ setPreview(null);
+ setFile(null);
+ await load(1);
+ } catch {
+ setError("A importação não foi concluída. O catálogo não foi sincronizado.");
+ } finally {
+ setImporting(false);
+ }
+ };
+
+ return (
+
+
+
+
Catálogo administrativo
+
+ Itens ativos e inativos de {context.specialist.name}; dono imutável após a criação.
+
+
+
navigate("/admin/journey/products/new")}>
+ Novo produto
+
+
+
+ {error && {error} }
+
+
+
+
+
Importação CSV segura
+
+
+ {
+ setFile(event.target.files?.[0] ?? null);
+ setPreview(null);
+ }}
+ className="rounded-lg border border-border px-3 py-2 text-sm"
+ />
+ {
+ setMode(event.target.value as ProductImportMode);
+ setPreview(null);
+ setSyncConfirmed(false);
+ }}
+ className="rounded-lg border border-border bg-surface px-3 py-2 text-sm"
+ >
+ Acréscimo seguro
+ Sincronizar catálogo
+
+
+ Pré-visualizar impacto
+
+
+ {preview && (
+
+
+ {preview.impact.csvRows} linhas · {preview.impact.wouldCreate} criações · {preview.impact.wouldUpdate} atualizações · {preview.impact.wouldDeactivate} desativações
+
+ {mode === "SYNCHRONIZE" && (
+
+ setSyncConfirmed(event.target.checked)}
+ />
+ Confirmo a sincronização de {context.specialist.name}, tipo {productType}, com o impacto acima.
+
+ )}
+
+ {importing ? "Importando…" : "Executar importação"}
+
+
+ )}
+
+
+
+ {loading ? (
+
Carregando catálogo…
+ ) : (
+
+
+ Produto Valor Estado Catálogo Ações
+
+
+ {products.map((product) => (
+
+ {product.marca} {product.modelo}
+ {formatCurrency(product.valor, product.currency)}
+ {product.estado ?? "-"}
+
+
+ {product.is_active ? "Ativo" : "Inativo"}
+
+
+
+ navigate(`/admin/journey/products/edit/${productType.toLowerCase()}s/${product.id}`)}>Editar
+ {product.is_active && void remove(product.id)}>Desativar }
+
+
+ ))}
+
+
+ )}
+
+
Página {page} de {totalPages}
+
+ void load(page - 1)}> Anterior
+ = totalPages} onClick={() => void load(page + 1)}>Próxima
+
+
+
+
+ );
+}
diff --git a/frontend/src/pages/meetings/MeetingRoomPage.tsx b/frontend/src/pages/meetings/MeetingRoomPage.tsx
index 71bd062..0ab34e4 100644
--- a/frontend/src/pages/meetings/MeetingRoomPage.tsx
+++ b/frontend/src/pages/meetings/MeetingRoomPage.tsx
@@ -11,6 +11,7 @@ import {
} from "../../services/processes.service";
import { BackButton } from "../../components/patterns/BackButton";
import Button from "../../components/ui/button";
+import { useAdminSpecialistJourney } from "../../contexts/AdminSpecialistJourneyContext";
function isJitsiLink(url?: string | null): boolean {
if (!url) return false;
@@ -51,6 +52,7 @@ export default function MeetingRoomPage() {
const { processId } = useParams();
const navigate = useNavigate();
const { user } = useAuth();
+ const adminJourney = useAdminSpecialistJourney();
const [meeting, setMeeting] = useState(null);
const [scheduledAt, setScheduledAt] = useState(null);
@@ -62,7 +64,7 @@ export default function MeetingRoomPage() {
useState(false);
const [copied, setCopied] = useState(false);
- const isSpecialist = user?.role === "SPECIALIST";
+ const isSpecialist = user?.role === "SPECIALIST" || Boolean(adminJourney);
useEffect(() => {
const loadMeeting = async () => {
@@ -358,7 +360,9 @@ export default function MeetingRoomPage() {
();
const navigate = useNavigate();
const { user } = useAuth();
+ const adminJourney = useAdminSpecialistJourney();
+ const commercialActorId = adminJourney?.targetSpecialistId ?? user?.id;
const [proposals, setProposals] = useState
([]);
const [processInfo, setProcessInfo] = useState(
@@ -53,6 +57,7 @@ export default function NegotiationPage() {
const [isRejecting, setIsRejecting] = useState(false);
const getProcessesRouteByRole = (): string => {
+ if (adminJourney) return adminJourneyRoute("processes");
return user?.role === "SPECIALIST"
? "/specialist/processes"
: "/customer/processes";
@@ -122,7 +127,7 @@ export default function NegotiationPage() {
// Carregar propostas ao montar
useEffect(() => {
loadProposals();
- }, [processId, user?.role]);
+ }, [processId, user?.role, adminJourney?.targetSpecialistId]);
/**
* Envia uma nova proposta
@@ -244,8 +249,8 @@ export default function NegotiationPage() {
* Verifica se o usuário pode responder a uma proposta
*/
const canRespondToProposal = (proposal: NegotiationProposal): boolean => {
- if (!user || proposal.status !== "PENDING") return false;
- return proposal.proposed_to.id === user.id;
+ if (!commercialActorId || proposal.status !== "PENDING") return false;
+ return proposal.proposed_to.id === commercialActorId;
};
// Loading state
@@ -349,7 +354,7 @@ export default function NegotiationPage() {
icon={MessageSquare}
title="Nenhuma proposta ainda"
description={`Inicie a negociação enviando uma proposta de valor para o ${
- user?.role === "SPECIALIST" ? "cliente" : "especialista"
+ user?.role === "SPECIALIST" || adminJourney ? "cliente" : "especialista"
}.`}
/>
)}
@@ -357,7 +362,7 @@ export default function NegotiationPage() {
{/* Proposals list (chat style) */}
{processInfo && proposals.map((proposal) => {
- const isOwnProposal = proposal.proposed_by.id === user?.id;
+ const isOwnProposal = proposal.proposed_by.id === commercialActorId;
return (
{proposal.proposed_by.name}{" "}
{proposal.proposed_by.surname}
- {isOwnProposal && " (você)"}
+ {isOwnProposal &&
+ (adminJourney
+ ? " (lado do especialista; executado pelo admin)"
+ : " (você)")}
Aguardando resposta do{" "}
- {meta?.pending_response_from === user?.id
+ {meta?.pending_response_from === commercialActorId
? "outro participante"
: "outro participante"}
...
diff --git a/frontend/src/pages/specialist/CreateContractPage.tsx b/frontend/src/pages/specialist/CreateContractPage.tsx
index bddf766..e640721 100644
--- a/frontend/src/pages/specialist/CreateContractPage.tsx
+++ b/frontend/src/pages/specialist/CreateContractPage.tsx
@@ -44,6 +44,8 @@ import {
cancelPreviewBeforeDiscard,
expirePreviewBeforeDiscard,
} from "../../lib/contract-preview-cancellation";
+import { useAdminSpecialistJourney } from "../../contexts/AdminSpecialistJourneyContext";
+import { adminJourneyRoute } from "../../lib/admin-specialist-journey";
interface ContractFormData {
// Vendedor
@@ -130,6 +132,7 @@ function extractBackendMessage(error: any): string {
}
export default function CreateContractPage() {
+ const adminJourney = useAdminSpecialistJourney();
const isMobile = useIsMobile();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
@@ -512,7 +515,11 @@ export default function CreateContractPage() {
const previewPayload: PreviewContractData = {
...contractData,
- return_url: `${window.location.origin}/specialist/contracts/preview-callback`,
+ return_url: `${window.location.origin}${
+ adminJourney
+ ? "/admin/journey/contracts/preview-callback"
+ : "/specialist/contracts/preview-callback"
+ }`,
};
const result = await previewContract(previewPayload);
@@ -582,7 +589,9 @@ export default function CreateContractPage() {
});
setTimeout(() => {
- navigate("/specialist/processes");
+ navigate(
+ adminJourney ? adminJourneyRoute("processes") : "/specialist/processes",
+ );
}, 2000);
} catch (error: any) {
console.error("Erro ao enviar contrato");
@@ -735,7 +744,15 @@ export default function CreateContractPage() {
Nenhum processo selecionado
- navigate("/specialist/processes")}>
+
+ navigate(
+ adminJourney
+ ? adminJourneyRoute("processes")
+ : "/specialist/processes",
+ )
+ }
+ >
Voltar ao Dashboard
diff --git a/frontend/src/pages/specialist/ProcessesPage.tsx b/frontend/src/pages/specialist/ProcessesPage.tsx
index a6e5ddf..c23313a 100644
--- a/frontend/src/pages/specialist/ProcessesPage.tsx
+++ b/frontend/src/pages/specialist/ProcessesPage.tsx
@@ -20,6 +20,9 @@ import {
} from "../../services/processes.service";
import type { Process } from "../../services/processes.service";
import { useAuth } from "../../store/authStateManager.ts";
+import { useAdminSpecialistJourney } from "../../contexts/AdminSpecialistJourneyContext";
+import { adminJourneyRoute } from "../../lib/admin-specialist-journey";
+import AdminCreateProcessDialog from "../../components/admin/AdminCreateProcessDialog";
// Status labels for filter dropdown
const STATUS_OPTIONS = [
@@ -46,9 +49,12 @@ interface ProcessWithProduct extends Process {
export default function ProcessesPage() {
const navigate = useNavigate();
const { user } = useAuth();
+ const adminJourney = useAdminSpecialistJourney();
+ const effectiveSpecialistId = adminJourney?.targetSpecialistId ?? user?.id;
+ const effectiveSpeciality = adminJourney?.specialist.speciality ?? user?.speciality;
// Validate user is logged in
- if (!user?.id) {
+ if (!effectiveSpecialistId) {
return (
@@ -83,6 +89,7 @@ export default function ProcessesPage() {
useState(false);
const [selectedProcessForProduct, setSelectedProcessForProduct] =
useState
(null);
+ const [showAdminCreateProcess, setShowAdminCreateProcess] = useState(false);
const itemsPerPage = 10;
@@ -115,7 +122,7 @@ export default function ProcessesPage() {
}
const processes = await getProcessesBySpecialist(
- user.id,
+ effectiveSpecialistId,
page,
itemsPerPage,
filters,
@@ -136,19 +143,19 @@ export default function ProcessesPage() {
setIsLoading(false);
}
},
- [user.id, statusFilter, searchQuery, itemsPerPage],
+ [effectiveSpecialistId, statusFilter, searchQuery, itemsPerPage],
);
// Load processes on mount or when user changes
useEffect(() => {
- if (user?.id) {
+ if (effectiveSpecialistId) {
loadProcesses(1);
}
- }, [user?.id, loadProcesses]);
+ }, [effectiveSpecialistId, loadProcesses]);
// Reload processes when filters change
useEffect(() => {
- if (user?.id) {
+ if (effectiveSpecialistId) {
loadProcesses(1);
}
}, [statusFilter, searchQuery]);
@@ -165,7 +172,7 @@ export default function ProcessesPage() {
// Smart Polling: Only poll if there are processes in NEGOTIATION or DOCUMENTATION
// AND user is not editing/in modal. Interval: 30 seconds
useEffect(() => {
- if (!user?.id) return;
+ if (!effectiveSpecialistId) return;
// Check if polling should be active
const shouldPoll =
@@ -178,7 +185,7 @@ export default function ProcessesPage() {
}, 30000); // Poll every 30 seconds
return () => clearInterval(pollingInterval);
- }, [user?.id, currentPage, isEditing, expandedProcessId, processes]);
+ }, [effectiveSpecialistId, currentPage, isEditing, expandedProcessId, processes]);
// Handle pagination
const handleNextPage = () => {
@@ -205,7 +212,11 @@ export default function ProcessesPage() {
// Handle upload documents button
const handleUploadDocuments = (processId: string) => {
setIsEditing(true); // Pause polling when navigating to upload
- navigate(`/specialist/contracts/new?processId=${processId}`);
+ navigate(
+ adminJourney
+ ? adminJourneyRoute("contract", processId)
+ : `/specialist/contracts/new?processId=${processId}`,
+ );
};
// Handle opening product selector for consultancy processes
@@ -244,9 +255,14 @@ export default function ProcessesPage() {
+ {adminJourney && (
+ setShowAdminCreateProcess(true)}>
+ Novo processo
+
+ )}
handleUploadDocuments(process.id)}
onStatusUpdated={() => handleStatusUpdated()}
onSelectProduct={() => handleSelectProduct(process)}
- specialistSpeciality={user?.speciality}
+ specialistSpeciality={effectiveSpeciality}
+ adminJourney={Boolean(adminJourney)}
/>
))}
@@ -481,7 +498,7 @@ export default function ProcessesPage() {
{/* Product Selector Modal for Consultancy Processes */}
- {selectedProcessForProduct && user?.speciality && (
+ {selectedProcessForProduct && effectiveSpeciality && (
{
@@ -491,8 +508,15 @@ export default function ProcessesPage() {
}}
onSuccess={handleProductAssigned}
process={selectedProcessForProduct}
- specialistId={user.id}
- specialistSpeciality={user.speciality}
+ specialistId={effectiveSpecialistId}
+ specialistSpeciality={effectiveSpeciality}
+ />
+ )}
+ {adminJourney && (
+ setShowAdminCreateProcess(false)}
+ onCreated={() => void loadProcesses(1)}
/>
)}
diff --git a/frontend/src/routes/routes.tsx b/frontend/src/routes/routes.tsx
index 40d8127..df43609 100644
--- a/frontend/src/routes/routes.tsx
+++ b/frontend/src/routes/routes.tsx
@@ -43,6 +43,9 @@ import OfficeClientsPage from "../pages/office/OfficeClientsPage";
import OfficeProcessesPage from "../pages/office/OfficeProcessesPage";
import OfficeCompanySettingsPage from "../pages/office/OfficeCompanySettingsPage";
import WhitelabelPage from "../pages/whitelabel/WhitelabelPage";
+import AdminSpecialistJourneyShell from "../components/admin/AdminSpecialistJourneyShell";
+import SpecialistJourneyOverviewPage from "../pages/admin/SpecialistJourneyOverviewPage";
+import SpecialistJourneyProductsPage from "../pages/admin/SpecialistJourneyProductsPage";
export default function RouterApp() {
const routerApp = createBrowserRouter([
@@ -318,6 +321,106 @@ export default function RouterApp() {
),
},
+ {
+ path: "/admin/journey",
+ element: (
+
+
+
+
+
+
+
+ ),
+ },
+ {
+ path: "/admin/journey/products",
+ element: (
+
+
+
+
+
+
+
+ ),
+ },
+ {
+ path: "/admin/journey/products/new",
+ element: (
+
+
+
+
+
+
+
+ ),
+ },
+ {
+ path: "/admin/journey/products/edit/:productType/:id",
+ element: (
+
+
+
+
+
+
+
+ ),
+ },
+ {
+ path: "/admin/journey/processes",
+ element: (
+
+
+
+
+
+
+
+ ),
+ },
+ {
+ path: "/admin/journey/processes/:processId/negotiation",
+ element: (
+
+
+
+
+
+
+
+ ),
+ },
+ {
+ path: "/admin/journey/processes/:processId/meeting",
+ element: (
+
+
+
+
+
+
+
+ ),
+ },
+ {
+ path: "/admin/journey/contracts/new",
+ element: (
+
+
+
+
+
+
+
+ ),
+ },
+ {
+ path: "/admin/journey/contracts/preview-callback",
+ element:
,
+ },
{
path: "/specialist/products",
element: (
diff --git a/frontend/src/services/admin-specialist-journey.service.ts b/frontend/src/services/admin-specialist-journey.service.ts
new file mode 100644
index 0000000..a635305
--- /dev/null
+++ b/frontend/src/services/admin-specialist-journey.service.ts
@@ -0,0 +1,116 @@
+import api from "./api";
+import type { PaginationMeta, Product, ResponseAPI } from "../types/types";
+import {
+ resolveImportResponse,
+ type CsvImportResponse,
+ type ImportJobAcceptedResponse,
+} from "./product-import-jobs.service";
+
+export type JourneyProductType = "CAR" | "BOAT" | "AIRCRAFT";
+export type ProductImportMode = "ADDITIVE" | "SYNCHRONIZE";
+
+const resourceByType: Record
= {
+ CAR: "cars",
+ BOAT: "boats",
+ AIRCRAFT: "aircrafts",
+};
+
+export type AdminCatalogProduct = Product & { is_active: boolean };
+
+export type AdminClientOption = {
+ id: string;
+ name: string;
+ surname: string;
+ email: string;
+};
+
+export async function getAdminClientOptions(
+ search = "",
+): Promise {
+ const response = await api.get(
+ "/processes/admin/client-options",
+ { params: { search } },
+ );
+ return response.data;
+}
+
+export async function getAdminSpecialistProducts(
+ productType: JourneyProductType,
+ page: number,
+ perPage: number,
+): Promise<{ products: AdminCatalogProduct[]; pagination: PaginationMeta }> {
+ const resource = resourceByType[productType];
+ const response = await api.get>>(
+ `/${resource}/admin/all`,
+ { params: { page, perPage } },
+ );
+ const products = response.data.data.map((raw) => ({
+ ...raw,
+ valor: Number(raw.valor),
+ imageUrl:
+ raw.images?.find((image: { is_primary: boolean }) => image.is_primary)
+ ?.image_url ?? "",
+ }));
+ return { products, pagination: response.data.meta.pagination };
+}
+
+export type CsvImportPreview = {
+ productType: JourneyProductType;
+ targetSpecialistId: string;
+ mode: ProductImportMode;
+ requiresExplicitConfirmation: boolean;
+ impact: {
+ csvRows: number;
+ existingProducts: number;
+ wouldCreate: number;
+ wouldUpdate: number;
+ wouldDeactivate: number;
+ };
+};
+
+function importForm(
+ file: File,
+ specialistId: string,
+ mode: ProductImportMode,
+ confirmSynchronize = false,
+): FormData {
+ const form = new FormData();
+ form.append("file", file);
+ form.append("specialist_id", specialistId);
+ form.append("mode", mode);
+ form.append("confirm_synchronize", String(confirmSynchronize));
+ return form;
+}
+
+export async function previewAdminCatalogCsv(
+ productType: JourneyProductType,
+ specialistId: string,
+ file: File,
+ mode: ProductImportMode,
+): Promise {
+ const resource = resourceByType[productType];
+ const response = await api.post(
+ `/${resource}/import-csv/preview`,
+ importForm(file, specialistId, mode),
+ { headers: { "Content-Type": "multipart/form-data" } },
+ );
+ return response.data;
+}
+
+export async function importAdminCatalogCsv(
+ productType: JourneyProductType,
+ specialistId: string,
+ file: File,
+ mode: ProductImportMode,
+ confirmSynchronize: boolean,
+): Promise {
+ const resource = resourceByType[productType];
+ const response = await api.post<
+ CsvImportResponse | ImportJobAcceptedResponse
+ >(
+ `/${resource}/import-csv`,
+ importForm(file, specialistId, mode, confirmSynchronize),
+ { headers: { "Content-Type": "multipart/form-data" } },
+ );
+ return resolveImportResponse(response.data);
+}
diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts
index e766395..88594a4 100644
--- a/frontend/src/services/api.ts
+++ b/frontend/src/services/api.ts
@@ -1,5 +1,9 @@
import axios from "axios";
import { useAuth } from "../store/authStateManager";
+import {
+ attachAdminSpecialistTarget,
+ readAdminSpecialistTarget,
+} from "../lib/admin-specialist-journey";
// Instanciar a origem das rquisições para a api
const api = axios.create({
@@ -8,7 +12,8 @@ const api = axios.create({
// Adiciona token de acesso no header das requisições
api.interceptors.request.use((config) => {
- const token = useAuth.getState().accessToken;
+ const auth = useAuth.getState();
+ const token = auth.accessToken;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
@@ -16,7 +21,11 @@ api.interceptors.request.use((config) => {
// Sempre incluir cookies nas requisições
config.withCredentials = true;
- return config;
+ return attachAdminSpecialistTarget(
+ config,
+ auth.user?.role,
+ readAdminSpecialistTarget(),
+ );
});
// Renova token em 401; converte erros HTTP em mensagens amigáveis
diff --git a/frontend/src/services/processes.service.ts b/frontend/src/services/processes.service.ts
index 2045ae3..edab506 100644
--- a/frontend/src/services/processes.service.ts
+++ b/frontend/src/services/processes.service.ts
@@ -79,6 +79,17 @@ export interface ConversationDoneResult {
};
}
+export interface DelegatedProcessTimelineEvent {
+ id: string;
+ action: string;
+ resourceType: string;
+ resourceId: string;
+ metadata: Record | null;
+ createdAt: string;
+ actor: { id: string; role: string; name: string | null };
+ representedSpecialistId: string;
+}
+
export interface ApiResponse {
success: boolean;
message: string;
@@ -182,8 +193,9 @@ export async function getProcessById(processId: string): Promise {
export interface CreateProcessRequest {
client_id: string;
specialist_id: string | undefined;
- product_type: "CAR" | "BOAT" | "AIRCRAFT";
- product_id: string;
+ product_type?: "CAR" | "BOAT" | "AIRCRAFT";
+ product_id?: string;
+ notes?: string;
}
/**
@@ -277,6 +289,15 @@ export async function getProcessWithActiveContract(
return response.data.data;
}
+export async function getAdminProcessTimeline(
+ processId: string,
+): Promise {
+ const response = await api.get<
+ ApiResponse
+ >(`/processes/${processId}/admin-timeline`, { withCredentials: true });
+ return response.data.data;
+}
+
/**
* Get processes by client ID
* @param clientId - ID of the client
@@ -344,10 +365,11 @@ export async function confirmAppointment(
*/
export async function cancelAppointment(
processId: string,
+ reason?: string,
): Promise<{ success: boolean; message: string }> {
const response = await api.post>(
`/processes/${processId}/cancel-appointment`,
- {},
+ reason ? { reason } : {},
{ withCredentials: true },
);
return response.data.data;
diff --git a/frontend/src/services/specialists.service.ts b/frontend/src/services/specialists.service.ts
index e5000eb..d9767aa 100644
--- a/frontend/src/services/specialists.service.ts
+++ b/frontend/src/services/specialists.service.ts
@@ -12,6 +12,7 @@ export type Specialist = {
rg: string;
password_hash: string;
speciality: "CAR" | "BOAT" | "AIRCRAFT";
+ is_active?: boolean;
company_id?: string | null;
commission_rate?: number | null;
bank?: string | null;
From 910dc1c1c879eec7245cea80507dc60245a7a2ea Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Fri, 23 Oct 2026 11:52:40 -0300
Subject: [PATCH 54/60] fix(admin): address delegated journey review findings
---
.../migration.sql | 2 +
backend/prisma/schema.prisma | 1 +
.../aircrafts/aircrafts.controller.spec.ts | 36 +-
.../aircrafts/aircrafts.controller.ts | 87 +++--
.../features/aircrafts/aircrafts.service.ts | 32 +-
.../features/boats/boats.controller.spec.ts | 36 +-
.../src/features/boats/boats.controller.ts | 80 +++--
backend/src/features/boats/boats.service.ts | 32 +-
.../src/features/cars/cars.controller.spec.ts | 33 +-
backend/src/features/cars/cars.controller.ts | 80 +++--
backend/src/features/cars/cars.service.ts | 32 +-
.../contracts/contracts.controller.spec.ts | 26 ++
.../contracts/contracts.controller.ts | 5 +-
.../dto/product-csv-import.dto.ts | 21 ++
.../product-import-jobs.service.spec.ts | 313 +++++++++++++++++-
.../product-import-jobs.service.ts | 307 ++++++++++++++---
.../product-sync-preview.postgres.spec.ts | 242 ++++++++++++++
.../product-delegated-audit.postgres.spec.ts | 166 ++++++++++
.../products/product-monetary-lock.ts | 11 +-
.../test/admin-specialist-journey.e2e-spec.ts | 10 +
.../admin/SpecialistJourneyProductsPage.tsx | 18 +-
.../admin-specialist-journey.service.test.ts | 34 ++
.../admin-specialist-journey.service.ts | 14 +-
.../product-import-jobs.service.test.ts | 38 +++
.../services/product-import-jobs.service.ts | 3 +
25 files changed, 1469 insertions(+), 190 deletions(-)
create mode 100644 backend/prisma/migrations/20261023114500_bind_product_sync_preview/migration.sql
create mode 100644 backend/src/features/contracts/contracts.controller.spec.ts
create mode 100644 backend/src/features/product-import-jobs/dto/product-csv-import.dto.ts
create mode 100644 backend/src/features/product-import-jobs/product-sync-preview.postgres.spec.ts
create mode 100644 backend/src/features/products/product-delegated-audit.postgres.spec.ts
create mode 100644 frontend/src/services/admin-specialist-journey.service.test.ts
create mode 100644 frontend/src/services/product-import-jobs.service.test.ts
diff --git a/backend/prisma/migrations/20261023114500_bind_product_sync_preview/migration.sql b/backend/prisma/migrations/20261023114500_bind_product_sync_preview/migration.sql
new file mode 100644
index 0000000..a1f3b60
--- /dev/null
+++ b/backend/prisma/migrations/20261023114500_bind_product_sync_preview/migration.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "ProductImportJob"
+ ADD COLUMN "sync_preview_snapshot" JSONB;
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index a942c5d..d12b809 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1341,6 +1341,7 @@ model ProductImportJob {
created_by_id String? @db.Uuid
mode String @default("ADDITIVE") @db.VarChar(20)
sync_confirmed Boolean @default(false)
+ sync_preview_snapshot Json?
status ProductImportJobStatus @default(PENDING)
total_items Int @default(0)
processed_items Int @default(0)
diff --git a/backend/src/features/aircrafts/aircrafts.controller.spec.ts b/backend/src/features/aircrafts/aircrafts.controller.spec.ts
index 93aa2e4..996ba04 100644
--- a/backend/src/features/aircrafts/aircrafts.controller.spec.ts
+++ b/backend/src/features/aircrafts/aircrafts.controller.spec.ts
@@ -24,13 +24,25 @@ function mkController() {
assertResourceSpecialist: jest.fn(),
} as any;
const audit = { record: jest.fn().mockResolvedValue(undefined) } as any;
- const controller = new AircraftsController(
+ const tx = { name: 'tx' } as any;
+ const prisma = {
+ $transaction: jest.fn(async (callback) => callback(tx)),
+ } as any;
+ const controller = new (AircraftsController as any)(
aircraftsService,
productImportJobsService,
actorContext,
audit,
+ prisma,
);
- return { controller, aircraftsService, productImportJobsService };
+ return {
+ controller,
+ aircraftsService,
+ productImportJobsService,
+ audit,
+ prisma,
+ tx,
+ };
}
const specialist = {
@@ -41,14 +53,14 @@ const specialist = {
describe('AircraftsController — Calendly opcional', () => {
it('permite criação manual sem consultar Calendly', async () => {
- const { controller, aircraftsService } = mkController();
+ const { controller, aircraftsService, tx } = mkController();
const dto = {} as any;
await expect(controller.create(dto, specialist)).resolves.toEqual({
id: 'aircraft-1',
});
expect(dto.specialist_id).toBe(specialist.id);
- expect(aircraftsService.create).toHaveBeenCalledWith(dto);
+ expect(aircraftsService.create).toHaveBeenCalledWith(dto, tx);
});
it('não permite remover o owner no PATCH comum', async () => {
@@ -64,6 +76,22 @@ describe('AircraftsController — Calendly opcional', () => {
expect(aircraftsService.update).not.toHaveBeenCalled();
});
+ it('executa criação manual e auditoria na mesma transação', async () => {
+ const { controller, aircraftsService, audit, prisma, tx } = mkController();
+ audit.record.mockRejectedValueOnce(new Error('audit unavailable'));
+
+ await expect(controller.create({} as any, specialist)).rejects.toThrow(
+ 'audit unavailable',
+ );
+
+ expect(prisma.$transaction).toHaveBeenCalledTimes(1);
+ expect(aircraftsService.create).toHaveBeenCalledWith(
+ expect.objectContaining({ specialist_id: specialist.id }),
+ tx,
+ );
+ expect(audit.record).toHaveBeenCalledWith(expect.any(Object), tx);
+ });
+
it('permite importação CSV sem consultar Calendly', async () => {
const { controller, productImportJobsService } = mkController();
const file = {
diff --git a/backend/src/features/aircrafts/aircrafts.controller.ts b/backend/src/features/aircrafts/aircrafts.controller.ts
index d7033d2..7e00032 100644
--- a/backend/src/features/aircrafts/aircrafts.controller.ts
+++ b/backend/src/features/aircrafts/aircrafts.controller.ts
@@ -34,6 +34,8 @@ import { Public } from 'src/shared/decorators/public.decorator';
import { ProductImportJobsService } from '../product-import-jobs/product-import-jobs.service';
import { ActorContextService } from 'src/shared/actor-context/actor-context.service';
import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
+import { ProductCsvImportDto } from '../product-import-jobs/dto/product-csv-import.dto';
+import { PrismaService } from 'src/prisma/prisma.service';
@Controller('aircrafts')
export class AircraftsController {
@@ -42,6 +44,7 @@ export class AircraftsController {
private readonly productImportJobsService: ProductImportJobsService,
private readonly actorContextService: ActorContextService,
private readonly delegatedAudit: DelegatedActionAuditService,
+ private readonly prisma: PrismaService,
) {}
@Post()
@@ -56,14 +59,22 @@ export class AircraftsController {
ProductType.AIRCRAFT,
);
createAircraftDto.specialist_id = context.specialistId;
- const aircraft = await this.aircraftsService.create(createAircraftDto);
- await this.delegatedAudit.record({
- context,
- action: 'PRODUCT_CREATE',
- resourceType: 'AIRCRAFT',
- resourceId: aircraft.id,
+ return this.prisma.$transaction(async (tx) => {
+ const aircraft = await this.aircraftsService.create(
+ createAircraftDto,
+ tx,
+ );
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_CREATE',
+ resourceType: 'AIRCRAFT',
+ resourceId: aircraft.id,
+ },
+ tx,
+ );
+ return aircraft;
});
- return aircraft;
}
@Post('import-csv/preview')
@@ -74,12 +85,11 @@ export class AircraftsController {
async previewCsvImport(
@UploadedFile() file: Express.Multer.File,
@CurrentUser() user: UserEntity,
- @Body('specialist_id') targetSpecialistId?: string,
- @Body('mode') mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE',
+ @Body() options: ProductCsvImportDto = new ProductCsvImportDto(),
) {
const context = await this.actorContextService.resolve(
user,
- targetSpecialistId,
+ options.specialist_id,
ProductType.AIRCRAFT,
);
if (!file?.originalname?.toLowerCase().endsWith('.csv')) {
@@ -89,7 +99,7 @@ export class AircraftsController {
file.buffer,
ProductType.AIRCRAFT,
context.specialistId,
- mode,
+ options.mode,
);
}
@@ -101,13 +111,11 @@ export class AircraftsController {
async importCsv(
@UploadedFile() file: Express.Multer.File,
@CurrentUser() user: UserEntity,
- @Body('specialist_id') targetSpecialistId?: string,
- @Body('mode') mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE',
- @Body('confirm_synchronize') confirmSynchronize = false,
+ @Body() options: ProductCsvImportDto = new ProductCsvImportDto(),
) {
const context = await this.actorContextService.resolve(
user,
- targetSpecialistId,
+ options.specialist_id,
ProductType.AIRCRAFT,
);
@@ -128,7 +136,12 @@ export class AircraftsController {
file.buffer,
user,
ProductType.AIRCRAFT,
- { context, mode, confirmSynchronize },
+ {
+ context,
+ mode: options.mode,
+ confirmSynchronize: options.confirm_synchronize,
+ synchronizePreviewToken: options.synchronize_preview_token,
+ },
);
}
@@ -253,14 +266,23 @@ export class AircraftsController {
context,
existing?.specialist_id,
);
- const aircraft = await this.aircraftsService.update(id, updateAircraftDto);
- await this.delegatedAudit.record({
- context,
- action: 'PRODUCT_UPDATE',
- resourceType: 'AIRCRAFT',
- resourceId: id,
+ return this.prisma.$transaction(async (tx) => {
+ const aircraft = await this.aircraftsService.update(
+ id,
+ updateAircraftDto,
+ tx,
+ );
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_UPDATE',
+ resourceType: 'AIRCRAFT',
+ resourceId: id,
+ },
+ tx,
+ );
+ return aircraft;
});
- return aircraft;
}
@Delete(':id')
@@ -280,13 +302,18 @@ export class AircraftsController {
context,
existing?.specialist_id,
);
- const result = await this.aircraftsService.remove(id);
- await this.delegatedAudit.record({
- context,
- action: 'PRODUCT_DEACTIVATE',
- resourceType: 'AIRCRAFT',
- resourceId: id,
+ return this.prisma.$transaction(async (tx) => {
+ const result = await this.aircraftsService.remove(id, tx);
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_DEACTIVATE',
+ resourceType: 'AIRCRAFT',
+ resourceId: id,
+ },
+ tx,
+ );
+ return result;
});
- return result;
}
}
diff --git a/backend/src/features/aircrafts/aircrafts.service.ts b/backend/src/features/aircrafts/aircrafts.service.ts
index d7d1e78..daddbb0 100644
--- a/backend/src/features/aircrafts/aircrafts.service.ts
+++ b/backend/src/features/aircrafts/aircrafts.service.ts
@@ -27,7 +27,10 @@ export class AircraftsService {
private s3Service: S3Service,
) {}
- async create(createAircraftDto: CreateAircraftDto) {
+ async create(
+ createAircraftDto: CreateAircraftDto,
+ client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ ) {
this.logger.log('[create] Iniciando criação de nova aeronave');
const { specialist_id, images, ...aircraftData } = createAircraftDto;
@@ -51,7 +54,7 @@ export class AircraftsService {
this.logger.debug(
`[create] Criando aeronave: ${aircraftData.marca} ${aircraftData.modelo}`,
);
- const aircraft = await this.prismaService.aircraft.create({
+ const aircraft = await client.aircraft.create({
data: payload,
});
this.logger.log(
@@ -77,7 +80,7 @@ export class AircraftsService {
key,
);
- await this.prismaService.aircraft_image.create({
+ await client.aircraft_image.create({
data: {
aircraft_id: aircraft.id,
image_url: imageKey,
@@ -93,7 +96,7 @@ export class AircraftsService {
}
// 3. Retornar a aeronave com as imagens
- const aircraftWithImages = await this.prismaService.aircraft.findUnique({
+ const aircraftWithImages = await client.aircraft.findUnique({
where: { id: aircraft.id },
include: { images: true },
});
@@ -258,7 +261,11 @@ export class AircraftsService {
// return `This action updates a #${id} aircraft`;
// }
- async update(id: string, updateAircraftDto: UpdateAircraftDto) {
+ async update(
+ id: string,
+ updateAircraftDto: UpdateAircraftDto,
+ client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ ) {
const { specialist_id, images, ...aircraftData } = updateAircraftDto;
const payload: Prisma.AircraftUncheckedUpdateInput = {};
@@ -299,7 +306,7 @@ export class AircraftsService {
payload.specialist_id = specialist_id ?? null;
}
- await updateProductWithMonetaryLock(this.prismaService, {
+ await updateProductWithMonetaryLock(client, {
productType: ProductType.AIRCRAFT,
productId: id,
nextValue: updateAircraftDto.valor,
@@ -312,7 +319,7 @@ export class AircraftsService {
// 1. Se houver novas imagens, processar
if (images && images.length > 0) {
// Remover imagens antigas
- await this.prismaService.aircraft_image.deleteMany({
+ await client.aircraft_image.deleteMany({
where: { aircraft_id: id },
});
@@ -328,7 +335,7 @@ export class AircraftsService {
key,
);
- await this.prismaService.aircraft_image.create({
+ await client.aircraft_image.create({
data: {
aircraft_id: id,
image_url: imageKey,
@@ -340,7 +347,7 @@ export class AircraftsService {
}
// 3. Retornar a aeronave atualizada com imagens
- return await this.prismaService.aircraft.findUnique({
+ return await client.aircraft.findUnique({
where: { id },
include: { images: true },
});
@@ -352,9 +359,12 @@ export class AircraftsService {
}
}
- async remove(id: string) {
+ async remove(
+ id: string,
+ client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ ) {
try {
- await updateProductWithMonetaryLock(this.prismaService, {
+ await updateProductWithMonetaryLock(client, {
productType: ProductType.AIRCRAFT,
productId: id,
data: {
diff --git a/backend/src/features/boats/boats.controller.spec.ts b/backend/src/features/boats/boats.controller.spec.ts
index 1a7108d..75354a7 100644
--- a/backend/src/features/boats/boats.controller.spec.ts
+++ b/backend/src/features/boats/boats.controller.spec.ts
@@ -24,13 +24,25 @@ function mkController() {
assertResourceSpecialist: jest.fn(),
} as any;
const audit = { record: jest.fn().mockResolvedValue(undefined) } as any;
- const controller = new BoatsController(
+ const tx = { name: 'tx' } as any;
+ const prisma = {
+ $transaction: jest.fn(async (callback) => callback(tx)),
+ } as any;
+ const controller = new (BoatsController as any)(
boatsService,
productImportJobsService,
actorContext,
audit,
+ prisma,
);
- return { controller, boatsService, productImportJobsService };
+ return {
+ controller,
+ boatsService,
+ productImportJobsService,
+ audit,
+ prisma,
+ tx,
+ };
}
const specialist = {
@@ -41,14 +53,14 @@ const specialist = {
describe('BoatsController — Calendly opcional', () => {
it('permite criação manual sem consultar Calendly', async () => {
- const { controller, boatsService } = mkController();
+ const { controller, boatsService, tx } = mkController();
const dto = {} as any;
await expect(controller.create(dto, specialist)).resolves.toEqual({
id: 'boat-1',
});
expect(dto.specialist_id).toBe(specialist.id);
- expect(boatsService.create).toHaveBeenCalledWith(dto);
+ expect(boatsService.create).toHaveBeenCalledWith(dto, tx);
});
it('não permite trocar o owner no PATCH comum', async () => {
@@ -64,6 +76,22 @@ describe('BoatsController — Calendly opcional', () => {
expect(boatsService.update).not.toHaveBeenCalled();
});
+ it('executa criação manual e auditoria na mesma transação', async () => {
+ const { controller, boatsService, audit, prisma, tx } = mkController();
+ audit.record.mockRejectedValueOnce(new Error('audit unavailable'));
+
+ await expect(controller.create({} as any, specialist)).rejects.toThrow(
+ 'audit unavailable',
+ );
+
+ expect(prisma.$transaction).toHaveBeenCalledTimes(1);
+ expect(boatsService.create).toHaveBeenCalledWith(
+ expect.objectContaining({ specialist_id: specialist.id }),
+ tx,
+ );
+ expect(audit.record).toHaveBeenCalledWith(expect.any(Object), tx);
+ });
+
it('permite importação CSV sem consultar Calendly', async () => {
const { controller, productImportJobsService } = mkController();
const file = {
diff --git a/backend/src/features/boats/boats.controller.ts b/backend/src/features/boats/boats.controller.ts
index 6439028..b86ac3b 100644
--- a/backend/src/features/boats/boats.controller.ts
+++ b/backend/src/features/boats/boats.controller.ts
@@ -34,6 +34,8 @@ import { Public } from 'src/shared/decorators/public.decorator';
import { ProductImportJobsService } from '../product-import-jobs/product-import-jobs.service';
import { ActorContextService } from 'src/shared/actor-context/actor-context.service';
import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
+import { ProductCsvImportDto } from '../product-import-jobs/dto/product-csv-import.dto';
+import { PrismaService } from 'src/prisma/prisma.service';
@Controller('boats')
export class BoatsController {
@@ -42,6 +44,7 @@ export class BoatsController {
private readonly productImportJobsService: ProductImportJobsService,
private readonly actorContextService: ActorContextService,
private readonly delegatedAudit: DelegatedActionAuditService,
+ private readonly prisma: PrismaService,
) {}
@Post()
@@ -56,14 +59,19 @@ export class BoatsController {
ProductType.BOAT,
);
createBoatDto.specialist_id = context.specialistId;
- const boat = await this.boatsService.create(createBoatDto);
- await this.delegatedAudit.record({
- context,
- action: 'PRODUCT_CREATE',
- resourceType: 'BOAT',
- resourceId: boat.id,
+ return this.prisma.$transaction(async (tx) => {
+ const boat = await this.boatsService.create(createBoatDto, tx);
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_CREATE',
+ resourceType: 'BOAT',
+ resourceId: boat.id,
+ },
+ tx,
+ );
+ return boat;
});
- return boat;
}
@Post('import-csv/preview')
@@ -74,12 +82,11 @@ export class BoatsController {
async previewCsvImport(
@UploadedFile() file: Express.Multer.File,
@CurrentUser() user: UserEntity,
- @Body('specialist_id') targetSpecialistId?: string,
- @Body('mode') mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE',
+ @Body() options: ProductCsvImportDto = new ProductCsvImportDto(),
) {
const context = await this.actorContextService.resolve(
user,
- targetSpecialistId,
+ options.specialist_id,
ProductType.BOAT,
);
if (!file?.originalname?.toLowerCase().endsWith('.csv')) {
@@ -89,7 +96,7 @@ export class BoatsController {
file.buffer,
ProductType.BOAT,
context.specialistId,
- mode,
+ options.mode,
);
}
@@ -101,13 +108,11 @@ export class BoatsController {
async importCsv(
@UploadedFile() file: Express.Multer.File,
@CurrentUser() user: UserEntity,
- @Body('specialist_id') targetSpecialistId?: string,
- @Body('mode') mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE',
- @Body('confirm_synchronize') confirmSynchronize = false,
+ @Body() options: ProductCsvImportDto = new ProductCsvImportDto(),
) {
const context = await this.actorContextService.resolve(
user,
- targetSpecialistId,
+ options.specialist_id,
ProductType.BOAT,
);
@@ -128,7 +133,12 @@ export class BoatsController {
file.buffer,
user,
ProductType.BOAT,
- { context, mode, confirmSynchronize },
+ {
+ context,
+ mode: options.mode,
+ confirmSynchronize: options.confirm_synchronize,
+ synchronizePreviewToken: options.synchronize_preview_token,
+ },
);
}
@@ -252,14 +262,19 @@ export class BoatsController {
context,
existing?.specialist_id,
);
- const boat = await this.boatsService.update(id, updateBoatDto);
- await this.delegatedAudit.record({
- context,
- action: 'PRODUCT_UPDATE',
- resourceType: 'BOAT',
- resourceId: id,
+ return this.prisma.$transaction(async (tx) => {
+ const boat = await this.boatsService.update(id, updateBoatDto, tx);
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_UPDATE',
+ resourceType: 'BOAT',
+ resourceId: id,
+ },
+ tx,
+ );
+ return boat;
});
- return boat;
}
@Delete(':id')
@@ -279,13 +294,18 @@ export class BoatsController {
context,
existing?.specialist_id,
);
- const result = await this.boatsService.remove(id);
- await this.delegatedAudit.record({
- context,
- action: 'PRODUCT_DEACTIVATE',
- resourceType: 'BOAT',
- resourceId: id,
+ return this.prisma.$transaction(async (tx) => {
+ const result = await this.boatsService.remove(id, tx);
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_DEACTIVATE',
+ resourceType: 'BOAT',
+ resourceId: id,
+ },
+ tx,
+ );
+ return result;
});
- return result;
}
}
diff --git a/backend/src/features/boats/boats.service.ts b/backend/src/features/boats/boats.service.ts
index fa411f5..c240bf5 100644
--- a/backend/src/features/boats/boats.service.ts
+++ b/backend/src/features/boats/boats.service.ts
@@ -27,7 +27,10 @@ export class BoatsService {
private s3Service: S3Service,
) {}
- async create(createBoatDto: CreateBoatDto) {
+ async create(
+ createBoatDto: CreateBoatDto,
+ client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ ) {
this.logger.log('[create] Iniciando criação de novo barco');
const { images, ...boatData } = createBoatDto;
@@ -36,7 +39,7 @@ export class BoatsService {
this.logger.debug(
`[create] Criando barco: ${boatData.marca} ${boatData.modelo}`,
);
- const boat = await this.prismaService.boat.create({ data: boatData });
+ const boat = await client.boat.create({ data: boatData });
this.logger.log(`[create] Barco criado com sucesso - ID: ${boat.id}`);
// 2. Processar e fazer upload das imagens, se existirem
@@ -58,7 +61,7 @@ export class BoatsService {
key,
);
- await this.prismaService.boat_image.create({
+ await client.boat_image.create({
data: {
boat_id: boat.id,
image_url: imageKey,
@@ -74,7 +77,7 @@ export class BoatsService {
}
// 3. Retornar o barco com as imagens
- const boatWithImages = await this.prismaService.boat.findUnique({
+ const boatWithImages = await client.boat.findUnique({
where: { id: boat.id },
include: { images: true },
});
@@ -231,10 +234,14 @@ export class BoatsService {
return { ...boat };
}
- async update(id: string, updateBoatDto: UpdateBoatDto) {
+ async update(
+ id: string,
+ updateBoatDto: UpdateBoatDto,
+ client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ ) {
const { images, ...boatData } = updateBoatDto;
- await updateProductWithMonetaryLock(this.prismaService, {
+ await updateProductWithMonetaryLock(client, {
productType: ProductType.BOAT,
productId: id,
nextValue: updateBoatDto.valor,
@@ -247,7 +254,7 @@ export class BoatsService {
// 1. Se houver novas imagens, processar
if (images && images.length > 0) {
// Remover imagens antigas
- await this.prismaService.boat_image.deleteMany({
+ await client.boat_image.deleteMany({
where: { boat_id: id },
});
@@ -263,7 +270,7 @@ export class BoatsService {
key,
);
- await this.prismaService.boat_image.create({
+ await client.boat_image.create({
data: {
boat_id: id,
image_url: imageKey,
@@ -275,7 +282,7 @@ export class BoatsService {
}
// 2. Retornar o barco atualizado com imagens
- return await this.prismaService.boat.findUnique({
+ return await client.boat.findUnique({
where: { id },
include: { images: true },
});
@@ -287,9 +294,12 @@ export class BoatsService {
}
}
- async remove(id: string) {
+ async remove(
+ id: string,
+ client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ ) {
try {
- await updateProductWithMonetaryLock(this.prismaService, {
+ await updateProductWithMonetaryLock(client, {
productType: ProductType.BOAT,
productId: id,
data: {
diff --git a/backend/src/features/cars/cars.controller.spec.ts b/backend/src/features/cars/cars.controller.spec.ts
index 465d962..b4742c7 100644
--- a/backend/src/features/cars/cars.controller.spec.ts
+++ b/backend/src/features/cars/cars.controller.spec.ts
@@ -24,11 +24,16 @@ function mkController() {
assertResourceSpecialist: jest.fn(),
} as any;
const audit = { record: jest.fn().mockResolvedValue(undefined) } as any;
- const controller = new CarsController(
+ const tx = { name: 'tx' } as any;
+ const prisma = {
+ $transaction: jest.fn(async (callback) => callback(tx)),
+ } as any;
+ const controller = new (CarsController as any)(
carsService,
productImportJobsService,
actorContext,
audit,
+ prisma,
);
return {
controller,
@@ -36,6 +41,8 @@ function mkController() {
productImportJobsService,
actorContext,
audit,
+ prisma,
+ tx,
};
}
@@ -47,18 +54,18 @@ const specialist = {
describe('CarsController — Calendly opcional', () => {
it('permite criação manual sem consultar Calendly', async () => {
- const { controller, carsService } = mkController();
+ const { controller, carsService, tx } = mkController();
const dto = {} as any;
await expect(controller.create(dto, specialist)).resolves.toEqual({
id: 'car-1',
});
expect(dto.specialist_id).toBe(specialist.id);
- expect(carsService.create).toHaveBeenCalledWith(dto);
+ expect(carsService.create).toHaveBeenCalledWith(dto, tx);
});
it('mantém ADMIN como ator e grava o SPECIALIST selecionado como owner', async () => {
- const { controller, carsService, actorContext, audit } = mkController();
+ const { controller, carsService, actorContext, audit, tx } = mkController();
const admin = { id: 'admin-1', role: 'ADMIN' } as any;
const dto = { specialist_id: 'spec-1' } as any;
@@ -71,6 +78,7 @@ describe('CarsController — Calendly opcional', () => {
);
expect(carsService.create).toHaveBeenCalledWith(
expect.objectContaining({ specialist_id: 'spec-1' }),
+ tx,
);
expect(audit.record).toHaveBeenCalledWith(
expect.objectContaining({
@@ -78,7 +86,24 @@ describe('CarsController — Calendly opcional', () => {
resourceType: 'CAR',
resourceId: 'car-1',
}),
+ tx,
+ );
+ });
+
+ it('executa criação manual e auditoria na mesma transação', async () => {
+ const { controller, carsService, audit, prisma, tx } = mkController();
+ audit.record.mockRejectedValueOnce(new Error('audit unavailable'));
+
+ await expect(controller.create({} as any, specialist)).rejects.toThrow(
+ 'audit unavailable',
+ );
+
+ expect(prisma.$transaction).toHaveBeenCalledTimes(1);
+ expect(carsService.create).toHaveBeenCalledWith(
+ expect.objectContaining({ specialist_id: specialist.id }),
+ tx,
);
+ expect(audit.record).toHaveBeenCalledWith(expect.any(Object), tx);
});
it('não permite remover o owner com specialist_id null no PATCH', async () => {
diff --git a/backend/src/features/cars/cars.controller.ts b/backend/src/features/cars/cars.controller.ts
index 5e1ec33..8266742 100644
--- a/backend/src/features/cars/cars.controller.ts
+++ b/backend/src/features/cars/cars.controller.ts
@@ -31,6 +31,8 @@ import { Public } from 'src/shared/decorators/public.decorator';
import { ProductImportJobsService } from '../product-import-jobs/product-import-jobs.service';
import { ActorContextService } from 'src/shared/actor-context/actor-context.service';
import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
+import { ProductCsvImportDto } from '../product-import-jobs/dto/product-csv-import.dto';
+import { PrismaService } from 'src/prisma/prisma.service';
@Controller('cars')
export class CarsController {
@@ -39,6 +41,7 @@ export class CarsController {
private readonly productImportJobsService: ProductImportJobsService,
private readonly actorContextService: ActorContextService,
private readonly delegatedAudit: DelegatedActionAuditService,
+ private readonly prisma: PrismaService,
) {}
@Post()
@@ -53,14 +56,19 @@ export class CarsController {
ProductType.CAR,
);
createCarDto.specialist_id = context.specialistId;
- const car = await this.carsService.create(createCarDto);
- await this.delegatedAudit.record({
- context,
- action: 'PRODUCT_CREATE',
- resourceType: 'CAR',
- resourceId: car!.id,
+ return this.prisma.$transaction(async (tx) => {
+ const car = await this.carsService.create(createCarDto, tx);
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_CREATE',
+ resourceType: 'CAR',
+ resourceId: car!.id,
+ },
+ tx,
+ );
+ return car;
});
- return car;
}
@Post('import-csv/preview')
@@ -71,12 +79,11 @@ export class CarsController {
async previewCsvImport(
@UploadedFile() file: Express.Multer.File,
@CurrentUser() user: UserEntity,
- @Body('specialist_id') targetSpecialistId?: string,
- @Body('mode') mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE',
+ @Body() options: ProductCsvImportDto = new ProductCsvImportDto(),
) {
const context = await this.actorContextService.resolve(
user,
- targetSpecialistId,
+ options.specialist_id,
ProductType.CAR,
);
if (!file?.originalname?.toLowerCase().endsWith('.csv')) {
@@ -86,7 +93,7 @@ export class CarsController {
file.buffer,
ProductType.CAR,
context.specialistId,
- mode,
+ options.mode,
);
}
@@ -98,13 +105,11 @@ export class CarsController {
async importCsv(
@UploadedFile() file: Express.Multer.File,
@CurrentUser() user: UserEntity,
- @Body('specialist_id') targetSpecialistId?: string,
- @Body('mode') mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE',
- @Body('confirm_synchronize') confirmSynchronize = false,
+ @Body() options: ProductCsvImportDto = new ProductCsvImportDto(),
) {
const context = await this.actorContextService.resolve(
user,
- targetSpecialistId,
+ options.specialist_id,
ProductType.CAR,
);
@@ -125,7 +130,12 @@ export class CarsController {
file.buffer,
user,
ProductType.CAR,
- { context, mode, confirmSynchronize },
+ {
+ context,
+ mode: options.mode,
+ confirmSynchronize: options.confirm_synchronize,
+ synchronizePreviewToken: options.synchronize_preview_token,
+ },
);
}
@@ -249,14 +259,19 @@ export class CarsController {
context,
existing?.specialist_id,
);
- const car = await this.carsService.update(id, updateCarDto);
- await this.delegatedAudit.record({
- context,
- action: 'PRODUCT_UPDATE',
- resourceType: 'CAR',
- resourceId: id,
+ return this.prisma.$transaction(async (tx) => {
+ const car = await this.carsService.update(id, updateCarDto, tx);
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_UPDATE',
+ resourceType: 'CAR',
+ resourceId: id,
+ },
+ tx,
+ );
+ return car;
});
- return car;
}
@Delete(':id')
@@ -276,13 +291,18 @@ export class CarsController {
context,
existing?.specialist_id,
);
- const result = await this.carsService.remove(id);
- await this.delegatedAudit.record({
- context,
- action: 'PRODUCT_DEACTIVATE',
- resourceType: 'CAR',
- resourceId: id,
+ return this.prisma.$transaction(async (tx) => {
+ const result = await this.carsService.remove(id, tx);
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_DEACTIVATE',
+ resourceType: 'CAR',
+ resourceId: id,
+ },
+ tx,
+ );
+ return result;
});
- return result;
}
}
diff --git a/backend/src/features/cars/cars.service.ts b/backend/src/features/cars/cars.service.ts
index e6fecc2..a5ec712 100644
--- a/backend/src/features/cars/cars.service.ts
+++ b/backend/src/features/cars/cars.service.ts
@@ -27,12 +27,15 @@ export class CarsService {
private s3Service: S3Service,
) {}
- async create(createCarDto: CreateCarDto) {
+ async create(
+ createCarDto: CreateCarDto,
+ client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ ) {
const { images, ...carData } = createCarDto;
try {
// 1. Criar o carro
- const car = await this.prismaService.car.create({ data: carData });
+ const car = await client.car.create({ data: carData });
// 2. Processar e fazer upload das imagens, se existirem
if (images && images.length > 0) {
@@ -50,7 +53,7 @@ export class CarsService {
);
// Salvar referência da imagem no banco de dados
- await this.prismaService.car_image.create({
+ await client.car_image.create({
data: {
car_id: car.id,
image_url: imageKey,
@@ -62,7 +65,7 @@ export class CarsService {
}
// 3. Retornar o carro com as imagens
- return await this.prismaService.car.findUnique({
+ return await client.car.findUnique({
where: { id: car.id },
include: { images: true },
});
@@ -211,10 +214,14 @@ export class CarsService {
return { ...car };
}
- async update(id: string, updateCarDto: UpdateCarDto) {
+ async update(
+ id: string,
+ updateCarDto: UpdateCarDto,
+ client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ ) {
const { images, ...carData } = updateCarDto;
- await updateProductWithMonetaryLock(this.prismaService, {
+ await updateProductWithMonetaryLock(client, {
productType: ProductType.CAR,
productId: id,
nextValue: updateCarDto.valor,
@@ -227,7 +234,7 @@ export class CarsService {
// 1. Se houver novas imagens, processar
if (images && images.length > 0) {
// Remover imagens antigas
- await this.prismaService.car_image.deleteMany({
+ await client.car_image.deleteMany({
where: { car_id: id },
});
@@ -243,7 +250,7 @@ export class CarsService {
key,
);
- await this.prismaService.car_image.create({
+ await client.car_image.create({
data: {
car_id: id,
image_url: imageKey,
@@ -255,7 +262,7 @@ export class CarsService {
}
// 2. Retornar o carro atualizado com imagens
- return await this.prismaService.car.findUnique({
+ return await client.car.findUnique({
where: { id },
include: { images: true },
});
@@ -267,9 +274,12 @@ export class CarsService {
}
}
- async remove(id: string) {
+ async remove(
+ id: string,
+ client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ ) {
try {
- await updateProductWithMonetaryLock(this.prismaService, {
+ await updateProductWithMonetaryLock(client, {
productType: ProductType.CAR,
productId: id,
data: {
diff --git a/backend/src/features/contracts/contracts.controller.spec.ts b/backend/src/features/contracts/contracts.controller.spec.ts
new file mode 100644
index 0000000..f5a1553
--- /dev/null
+++ b/backend/src/features/contracts/contracts.controller.spec.ts
@@ -0,0 +1,26 @@
+import { UserRole } from '@prisma/client';
+import { ROLES_KEY } from 'src/shared/decorators/roles.decorator';
+import { ContractsController } from './contracts.controller';
+
+describe('ContractsController route policy', () => {
+ it('reserva generate legado ao SPECIALIST e mantém preview/send para ADMIN', () => {
+ expect(
+ Reflect.getMetadata(
+ ROLES_KEY,
+ ContractsController.prototype.generateContract,
+ ),
+ ).toEqual([UserRole.SPECIALIST]);
+ expect(
+ Reflect.getMetadata(
+ ROLES_KEY,
+ ContractsController.prototype.previewContract,
+ ),
+ ).toEqual(expect.arrayContaining([UserRole.SPECIALIST, UserRole.ADMIN]));
+ expect(
+ Reflect.getMetadata(
+ ROLES_KEY,
+ ContractsController.prototype.sendContractAfterPreview,
+ ),
+ ).toEqual(expect.arrayContaining([UserRole.SPECIALIST, UserRole.ADMIN]));
+ });
+});
diff --git a/backend/src/features/contracts/contracts.controller.ts b/backend/src/features/contracts/contracts.controller.ts
index 9ad9061..e1eb813 100644
--- a/backend/src/features/contracts/contracts.controller.ts
+++ b/backend/src/features/contracts/contracts.controller.ts
@@ -41,7 +41,8 @@ import { ActorContextService } from 'src/shared/actor-context/actor-context.serv
*
* Segurança:
* - AuthGuard: Garante que apenas usuários autenticados podem acessar
- * - preview/send/generate: apenas SPECIALIST e ADMIN, com rate limit
+ * - preview/send: SPECIALIST e ADMIN, com rate limit
+ * - generate legado: apenas SPECIALIST; ADMIN deve usar preview + send
*
* Fluxo (ativo):
* 1. Frontend busca dados pré-preenchidos via GET /contracts/prefill/:processId
@@ -215,7 +216,7 @@ export class ContractsController {
* proteções.
*/
@Post('generate')
- @Roles(UserRole.SPECIALIST, UserRole.ADMIN)
+ @Roles(UserRole.SPECIALIST)
@UseGuards(RateLimitGuard)
@RateLimit({ windowMs: 60, max: 10 })
async generateContract(
diff --git a/backend/src/features/product-import-jobs/dto/product-csv-import.dto.ts b/backend/src/features/product-import-jobs/dto/product-csv-import.dto.ts
new file mode 100644
index 0000000..59d9daf
--- /dev/null
+++ b/backend/src/features/product-import-jobs/dto/product-csv-import.dto.ts
@@ -0,0 +1,21 @@
+import { Transform } from 'class-transformer';
+import { IsBoolean, IsIn, IsOptional, IsString, IsUUID } from 'class-validator';
+
+export class ProductCsvImportDto {
+ @IsOptional()
+ @IsUUID()
+ specialist_id?: string;
+
+ @IsOptional()
+ @IsIn(['ADDITIVE', 'SYNCHRONIZE'])
+ mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE';
+
+ @IsOptional()
+ @Transform(({ value }) => value === true || value === 'true')
+ @IsBoolean()
+ confirm_synchronize = false;
+
+ @IsOptional()
+ @IsString()
+ synchronize_preview_token?: string;
+}
diff --git a/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts b/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts
index ad82753..0574551 100644
--- a/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts
+++ b/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts
@@ -110,6 +110,7 @@ describe('ProductImportJobsService', () => {
jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({
mode: 'SYNCHRONIZE',
syncConfirmed: true,
+ syncPreviewSnapshot: { candidateIds: [], csvDigest: 'csv-digest' },
specialistIsEligible: true,
});
const deactivateMissingProducts = jest
@@ -135,6 +136,185 @@ describe('ProductImportJobsService', () => {
});
});
+ it('reconstrói produtos vistos ao retomar sincronização parcialmente concluída', async () => {
+ const specialistId = '00000000-0000-4000-8000-000000000001';
+ const productA = '11111111-1111-4111-8111-111111111111';
+ const productB = '22222222-2222-4222-8222-222222222222';
+ const prisma = {
+ productImportJob: {
+ findUnique: jest.fn().mockResolvedValue({
+ id: 'job-resume',
+ product_type: ProductType.CAR,
+ specialist_id: specialistId,
+ status: 'PROCESSING',
+ started_at: new Date('2026-10-23T12:00:00.000Z'),
+ items: [
+ {
+ id: 'item-a',
+ status: 'COMPLETED',
+ product_id: productA,
+ payload: validCarRow,
+ folder_url: null,
+ },
+ {
+ id: 'item-b',
+ status: 'PENDING',
+ product_id: null,
+ payload: {
+ ...validCarRow,
+ identificador: 'FERRARI-ROMA-2',
+ },
+ folder_url: null,
+ },
+ ],
+ }),
+ update: jest.fn().mockResolvedValue({}),
+ },
+ productImportJobItem: {
+ update: jest.fn().mockResolvedValue({}),
+ },
+ } as any;
+ const service = new ProductImportJobsService(prisma, {} as any, {} as any);
+ jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({
+ mode: 'SYNCHRONIZE',
+ syncConfirmed: true,
+ syncPreviewSnapshot: { candidateIds: [], csvDigest: 'csv-digest' },
+ specialistIsEligible: true,
+ });
+ jest.spyOn(service as any, 'upsertProductFromRow').mockResolvedValue({
+ productId: productB,
+ action: 'UPDATED',
+ });
+ const deactivateMissingProducts = jest
+ .spyOn(service as any, 'deactivateMissingProducts')
+ .mockImplementation(async (_type, _specialist, seen: Set) =>
+ seen.has(productA) && seen.has(productB) ? [] : [productA],
+ );
+ const refreshJobCounters = jest
+ .spyOn(service as any, 'refreshJobCounters')
+ .mockResolvedValue(undefined);
+
+ await (service as any).processJob('job-resume');
+
+ expect(deactivateMissingProducts).toHaveBeenCalledWith(
+ ProductType.CAR,
+ specialistId,
+ new Set([productA, productB]),
+ 'job-resume',
+ { candidateIds: [], csvDigest: 'csv-digest' },
+ );
+ expect(refreshJobCounters).toHaveBeenCalledWith('job-resume', {
+ deactivatedIds: [],
+ reactivatedCount: 0,
+ });
+ });
+
+ it('leva o snapshot confirmado para a revalidação transacional antes de desativar', async () => {
+ const snapshot = {
+ candidateIds: ['22222222-2222-4222-8222-222222222222'],
+ csvDigest: 'csv-digest',
+ };
+ const prisma = {
+ productImportJob: {
+ findUnique: jest.fn().mockResolvedValue({
+ id: 'job-snapshot',
+ product_type: ProductType.CAR,
+ specialist_id: '00000000-0000-4000-8000-000000000001',
+ status: 'PROCESSING',
+ started_at: new Date(),
+ items: [
+ {
+ id: 'item-seen',
+ status: 'COMPLETED',
+ product_id: '11111111-1111-4111-8111-111111111111',
+ payload: validCarRow,
+ folder_url: null,
+ },
+ ],
+ }),
+ update: jest.fn().mockResolvedValue({}),
+ },
+ } as any;
+ const service = new ProductImportJobsService(prisma, {} as any, {} as any);
+ jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({
+ mode: 'SYNCHRONIZE',
+ syncConfirmed: true,
+ syncPreviewSnapshot: snapshot,
+ specialistIsEligible: true,
+ });
+ const deactivateMissingProducts = jest
+ .spyOn(service as any, 'deactivateMissingProducts')
+ .mockResolvedValue([]);
+ jest
+ .spyOn(service as any, 'refreshJobCounters')
+ .mockResolvedValue(undefined);
+
+ await (service as any).processJob('job-snapshot');
+
+ expect(deactivateMissingProducts).toHaveBeenCalledWith(
+ ProductType.CAR,
+ '00000000-0000-4000-8000-000000000001',
+ new Set(['11111111-1111-4111-8111-111111111111']),
+ 'job-snapshot',
+ snapshot,
+ );
+ });
+
+ it('reprocessa item PROCESSING de forma idempotente após upsert sem checkpoint', async () => {
+ const existingProductId = '11111111-1111-4111-8111-111111111111';
+ const itemUpdate = jest.fn().mockResolvedValue({});
+ const prisma = {
+ productImportJob: {
+ findUnique: jest.fn().mockResolvedValue({
+ id: 'job-interrupted',
+ product_type: ProductType.CAR,
+ specialist_id: '00000000-0000-4000-8000-000000000001',
+ status: 'PROCESSING',
+ started_at: new Date(),
+ items: [
+ {
+ id: 'item-processing',
+ status: 'PROCESSING',
+ product_id: null,
+ payload: validCarRow,
+ folder_url: null,
+ },
+ ],
+ }),
+ update: jest.fn().mockResolvedValue({}),
+ },
+ productImportJobItem: { update: itemUpdate },
+ } as any;
+ const service = new ProductImportJobsService(prisma, {} as any, {} as any);
+ jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({
+ mode: 'ADDITIVE',
+ syncConfirmed: false,
+ syncPreviewSnapshot: null,
+ specialistIsEligible: true,
+ });
+ const upsert = jest
+ .spyOn(service as any, 'upsertProductFromRow')
+ .mockResolvedValue({
+ productId: existingProductId,
+ action: 'UPDATED',
+ });
+ jest
+ .spyOn(service as any, 'refreshJobCounters')
+ .mockResolvedValue(undefined);
+
+ await (service as any).processJob('job-interrupted');
+
+ expect(upsert).toHaveBeenCalledTimes(1);
+ expect(itemUpdate).toHaveBeenLastCalledWith({
+ where: { id: 'item-processing' },
+ data: expect.objectContaining({
+ status: 'COMPLETED',
+ product_id: existingProductId,
+ action: 'UPDATED',
+ }),
+ });
+ });
+
it('não inativa produtos ausentes no modo aditivo', async () => {
const prisma = {
productImportJob: {
@@ -235,6 +415,58 @@ describe('ProductImportJobsService', () => {
).rejects.toThrow('confirmação explícita');
});
+ it('exige token da prévia mesmo quando a sincronização foi confirmada', async () => {
+ const xlsxImportService = {
+ parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
+ validateStructure: jest.fn().mockReturnValue({ valid: true }),
+ } as any;
+ const prisma = {
+ car: { findMany: jest.fn().mockResolvedValue([]) },
+ $transaction: jest.fn(async (callback) =>
+ callback({
+ productImportJob: {
+ create: jest.fn().mockResolvedValue({
+ id: 'job-unsafe',
+ status: 'PENDING',
+ total_items: 1,
+ product_type: ProductType.CAR,
+ }),
+ },
+ $executeRaw: jest.fn(),
+ }),
+ ),
+ } as any;
+ const service = new ProductImportJobsService(
+ prisma,
+ xlsxImportService,
+ {} as any,
+ );
+ jest.spyOn(service as any, 'scheduleJob').mockImplementation(() => {});
+
+ await expect(
+ service.createJobFromCsv(
+ Buffer.from('csv'),
+ { id: 'admin-1', role: 'ADMIN' } as any,
+ ProductType.CAR,
+ {
+ mode: 'SYNCHRONIZE',
+ confirmSynchronize: true,
+ context: {
+ actorId: 'admin-1',
+ actorRole: 'ADMIN',
+ specialistId: '00000000-0000-4000-8000-000000000001',
+ specialist: {} as any,
+ delegated: true,
+ },
+ },
+ ),
+ ).rejects.toMatchObject({
+ response: expect.objectContaining({
+ code: 'SYNCHRONIZE_PREVIEW_REQUIRED',
+ }),
+ });
+ });
+
it('calcula o impacto da sincronização antes de criar o job', async () => {
const xlsxImportService = {
parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
@@ -254,14 +486,14 @@ describe('ProductImportJobsService', () => {
{} as any,
);
- await expect(
- service.previewCsvImport(
+ const preview = await service.previewCsvImport(
Buffer.from('csv'),
ProductType.CAR,
'00000000-0000-4000-8000-000000000001',
'SYNCHRONIZE',
- ),
- ).resolves.toMatchObject({
+ );
+
+ expect(preview).toMatchObject({
mode: 'SYNCHRONIZE',
targetSpecialistId: '00000000-0000-4000-8000-000000000001',
requiresExplicitConfirmation: true,
@@ -272,6 +504,79 @@ describe('ProductImportJobsService', () => {
deactivationCandidates: 1,
},
});
+ expect(preview).toEqual(
+ expect.objectContaining({ synchronizePreviewToken: expect.any(String) }),
+ );
+ });
+
+ it('rejeita confirmação quando os candidatos mudam antes do POST', async () => {
+ const specialistId = '00000000-0000-4000-8000-000000000001';
+ const activeProducts = [
+ { id: '11111111-1111-4111-8111-111111111111', identificador: 'FERRARI-ROMA-1' },
+ { id: '22222222-2222-4222-8222-222222222222', identificador: 'STALE-B' },
+ ];
+ const xlsxImportService = {
+ parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
+ validateStructure: jest.fn().mockReturnValue({ valid: true }),
+ } as any;
+ const prisma = {
+ car: {
+ findMany: jest.fn().mockImplementation(async () => [...activeProducts]),
+ },
+ $transaction: jest.fn(async (callback) =>
+ callback({
+ productImportJob: {
+ create: jest.fn().mockResolvedValue({
+ id: 'job-stale',
+ status: 'PENDING',
+ total_items: 1,
+ product_type: ProductType.CAR,
+ }),
+ },
+ $executeRaw: jest.fn(),
+ }),
+ ),
+ } as any;
+ const service = new ProductImportJobsService(
+ prisma,
+ xlsxImportService,
+ {} as any,
+ );
+ jest.spyOn(service as any, 'scheduleJob').mockImplementation(() => {});
+ const file = Buffer.from('csv-stable');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ activeProducts.push({
+ id: '33333333-3333-4333-8333-333333333333',
+ identificador: 'NEW-C',
+ });
+
+ await expect(
+ service.createJobFromCsv(
+ file,
+ { id: 'admin-1', role: 'ADMIN' } as any,
+ ProductType.CAR,
+ {
+ mode: 'SYNCHRONIZE',
+ confirmSynchronize: true,
+ synchronizePreviewToken: preview.synchronizePreviewToken,
+ context: {
+ actorId: 'admin-1',
+ actorRole: 'ADMIN',
+ specialistId,
+ specialist: {} as any,
+ delegated: true,
+ },
+ },
+ ),
+ ).rejects.toMatchObject({
+ response: expect.objectContaining({ code: 'SYNCHRONIZE_PREVIEW_STALE' }),
+ });
+ expect(prisma.$transaction).not.toHaveBeenCalled();
});
it('relata a linha não importada com erro em linguagem natural', () => {
diff --git a/backend/src/features/product-import-jobs/product-import-jobs.service.ts b/backend/src/features/product-import-jobs/product-import-jobs.service.ts
index dead110..4aa1238 100644
--- a/backend/src/features/product-import-jobs/product-import-jobs.service.ts
+++ b/backend/src/features/product-import-jobs/product-import-jobs.service.ts
@@ -1,5 +1,6 @@
import {
BadRequestException,
+ ConflictException,
ForbiddenException,
Injectable,
Logger,
@@ -44,6 +45,7 @@ import {
} from '../products/product-monetary-lock';
import { ActorContext } from 'src/shared/actor-context/actor-context.service';
import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
+import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
export type ProductImportMode = 'ADDITIVE' | 'SYNCHRONIZE';
@@ -51,6 +53,22 @@ export type ProductImportOptions = {
context?: ActorContext;
mode?: ProductImportMode | string;
confirmSynchronize?: boolean | string;
+ synchronizePreviewToken?: string;
+};
+
+type SynchronizePreviewClaims = {
+ version: 1;
+ csvDigest: string;
+ specialistId: string;
+ productType: ProductType;
+ mode: 'SYNCHRONIZE';
+ candidateDigest: string;
+ expiresAt: number;
+};
+
+type SynchronizePreviewSnapshot = {
+ candidateIds: string[];
+ csvDigest: string;
};
type UpsertResult = {
@@ -128,6 +146,13 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
'A sincronização exige confirmação explícita do alvo, tipo e impacto.',
);
}
+ if (mode === 'SYNCHRONIZE' && !options.synchronizePreviewToken) {
+ throw new BadRequestException({
+ code: 'SYNCHRONIZE_PREVIEW_REQUIRED',
+ message:
+ 'A sincronização exige uma prévia válida. Gere uma nova prévia e confirme novamente.',
+ });
+ }
const { rows } = this.xlsxImportService.parseCsv(fileBuffer);
@@ -147,6 +172,16 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
const normalizedRows = rows.map((row) => this.normalizeProductRow(row));
const specialistId = options.context?.specialistId ?? user.id;
+ const synchronizeSnapshot =
+ mode === 'SYNCHRONIZE'
+ ? await this.validateSynchronizePreviewToken(
+ options.synchronizePreviewToken!,
+ fileBuffer,
+ productType,
+ specialistId,
+ normalizedRows,
+ )
+ : null;
const impact = await this.estimateImportImpact(
productType,
specialistId,
@@ -184,7 +219,8 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
UPDATE "ProductImportJob"
SET "mode" = ${mode},
"sync_confirmed" = ${syncConfirmed},
- "created_by_id" = ${user.id}::uuid
+ "created_by_id" = ${user.id}::uuid,
+ "sync_preview_snapshot" = ${synchronizeSnapshot ? JSON.stringify(synchronizeSnapshot) : null}::jsonb
WHERE "id" = ${job.id}::uuid
`;
if (options.context && this.delegatedAudit) {
@@ -258,13 +294,141 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
normalizedRows,
mode,
);
+ const synchronizePreviewToken =
+ mode === 'SYNCHRONIZE'
+ ? await this.createSynchronizePreviewToken(
+ fileBuffer,
+ productType,
+ specialistId,
+ normalizedRows,
+ )
+ : undefined;
return {
productType,
targetSpecialistId: specialistId,
mode,
requiresExplicitConfirmation: mode === 'SYNCHRONIZE',
impact,
+ synchronizePreviewToken,
+ };
+ }
+
+ private async createSynchronizePreviewToken(
+ fileBuffer: Buffer,
+ productType: ProductType,
+ specialistId: string,
+ rows: ImportParsedRow[],
+ ): Promise {
+ const candidates = await this.getSynchronizationCandidateIds(
+ productType,
+ specialistId,
+ rows,
+ );
+ const claims: SynchronizePreviewClaims = {
+ version: 1,
+ csvDigest: this.sha256(fileBuffer),
+ specialistId,
+ productType,
+ mode: 'SYNCHRONIZE',
+ candidateDigest: this.sha256(candidates.join(',')),
+ expiresAt: Date.now() + 15 * 60 * 1000,
};
+ const payload = Buffer.from(JSON.stringify(claims)).toString('base64url');
+ const signature = createHmac('sha256', this.getPreviewSecret())
+ .update(payload)
+ .digest('base64url');
+ return `${payload}.${signature}`;
+ }
+
+ private async validateSynchronizePreviewToken(
+ token: string,
+ fileBuffer: Buffer,
+ productType: ProductType,
+ specialistId: string,
+ rows: ImportParsedRow[],
+ ): Promise<{ candidateIds: string[]; csvDigest: string }> {
+ try {
+ const [payload, providedSignature, extra] = token.split('.');
+ if (!payload || !providedSignature || extra) {
+ throw new Error('token malformado');
+ }
+ const expectedSignature = createHmac('sha256', this.getPreviewSecret())
+ .update(payload)
+ .digest();
+ const providedSignatureBuffer = Buffer.from(
+ providedSignature,
+ 'base64url',
+ );
+ if (
+ providedSignatureBuffer.length !== expectedSignature.length ||
+ !timingSafeEqual(providedSignatureBuffer, expectedSignature)
+ ) {
+ throw new Error('assinatura inválida');
+ }
+
+ const claims = JSON.parse(
+ Buffer.from(payload, 'base64url').toString('utf8'),
+ ) as SynchronizePreviewClaims;
+ const candidateIds = await this.getSynchronizationCandidateIds(
+ productType,
+ specialistId,
+ rows,
+ );
+ const csvDigest = this.sha256(fileBuffer);
+ const scopeMatches =
+ claims.version === 1 &&
+ claims.mode === 'SYNCHRONIZE' &&
+ claims.productType === productType &&
+ claims.specialistId === specialistId &&
+ claims.csvDigest === csvDigest &&
+ claims.candidateDigest === this.sha256(candidateIds.join(',')) &&
+ claims.expiresAt >= Date.now();
+ if (!scopeMatches) {
+ throw new Error('escopo ou snapshot divergente');
+ }
+ return { candidateIds, csvDigest };
+ } catch {
+ throw new ConflictException({
+ code: 'SYNCHRONIZE_PREVIEW_STALE',
+ message:
+ 'A prévia de sincronização expirou ou o catálogo/CSV mudou. Gere uma nova prévia antes de confirmar.',
+ });
+ }
+ }
+
+ private async getSynchronizationCandidateIds(
+ productType: ProductType,
+ specialistId: string,
+ rows: ImportParsedRow[],
+ ): Promise {
+ const incomingIdentifiers = new Set(
+ rows.map((row) => row.identificador?.trim()).filter(Boolean),
+ );
+ const activeProducts = await this.getActiveProductsByType(
+ productType,
+ specialistId,
+ );
+ return activeProducts
+ .filter((product) => !incomingIdentifiers.has(product.identificador))
+ .map((product) => product.id)
+ .sort();
+ }
+
+ private sha256(value: Buffer | string): string {
+ return createHash('sha256').update(value).digest('hex');
+ }
+
+ private getPreviewSecret(): string {
+ const secret =
+ process.env.PRODUCT_IMPORT_PREVIEW_SECRET ??
+ process.env.JWT_SECRET_ACCESS;
+ if (secret) return secret;
+ if (process.env.NODE_ENV === 'test') {
+ return 'product-import-preview-test-secret';
+ }
+ throw new Error(
+ 'PRODUCT_IMPORT_PREVIEW_SECRET ou JWT_SECRET_ACCESS deve estar configurado.',
+ );
}
async getJobStatus(
@@ -442,7 +606,17 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
});
try {
- const seenProductIds = new Set();
+ const seenProductIds = new Set(
+ job.items
+ .filter(
+ (item) =>
+ (item.status === ProductImportItemStatus.COMPLETED ||
+ item.status ===
+ ProductImportItemStatus.COMPLETED_WITH_WARNINGS) &&
+ item.product_id,
+ )
+ .map((item) => item.product_id as string),
+ );
let reactivatedCount = 0;
let hasFailedItems = job.items.some(
(item) => item.status === ProductImportItemStatus.FAILED,
@@ -539,6 +713,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
job.specialist_id,
seenProductIds,
job.id,
+ executionContext.syncPreviewSnapshot,
)
: [];
@@ -566,12 +741,17 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
}): Promise<{
mode: ProductImportMode;
syncConfirmed: boolean;
+ syncPreviewSnapshot: SynchronizePreviewSnapshot | null;
specialistIsEligible: boolean;
}> {
const metadata = await this.prisma.$queryRaw<
- Array<{ mode: string; sync_confirmed: boolean }>
+ Array<{
+ mode: string;
+ sync_confirmed: boolean;
+ sync_preview_snapshot: SynchronizePreviewSnapshot | null;
+ }>
>`
- SELECT "mode", "sync_confirmed"
+ SELECT "mode", "sync_confirmed", "sync_preview_snapshot"
FROM "ProductImportJob"
WHERE "id" = ${job.id}::uuid
`;
@@ -583,6 +763,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
return {
mode: row?.mode === 'SYNCHRONIZE' ? 'SYNCHRONIZE' : 'ADDITIVE',
syncConfirmed: row?.sync_confirmed === true,
+ syncPreviewSnapshot: row?.sync_preview_snapshot ?? null,
specialistIsEligible:
specialist?.role === UserRole.SPECIALIST &&
specialist.is_active === true &&
@@ -624,18 +805,19 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
private async getActiveProductsByType(
productType: ProductType,
specialistId: string,
+ client: PrismaService | Prisma.TransactionClient = this.prisma,
): Promise> {
const query = {
where: { specialist_id: specialistId, is_active: true },
select: { id: true, identificador: true },
};
if (productType === ProductType.CAR) {
- return this.prisma.car.findMany(query);
+ return (client as PrismaService).car.findMany(query);
}
if (productType === ProductType.BOAT) {
- return this.prisma.boat.findMany(query);
+ return (client as PrismaService).boat.findMany(query);
}
- return this.prisma.aircraft.findMany(query);
+ return (client as PrismaService).aircraft.findMany(query);
}
private async refreshJobCounters(
@@ -702,48 +884,87 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
specialistId: string,
seenProductIds: Set,
jobId: string,
+ snapshot: SynchronizePreviewSnapshot | null,
): Promise {
- const activeProductIds = await this.getActiveProductIdsByType(
- productType,
- specialistId,
- );
-
- const staleIds = activeProductIds.filter((id) => !seenProductIds.has(id));
-
- if (staleIds.length === 0) {
- return [];
+ if (!snapshot) {
+ throw this.synchronizePreviewStale();
}
+ return this.prisma.$transaction(
+ async (tx) => {
+ const activeProducts = await this.getActiveProductsByType(
+ productType,
+ specialistId,
+ tx,
+ );
+ const currentCandidateIds = activeProducts
+ .map((product) => product.id)
+ .filter((id) => !seenProductIds.has(id))
+ .sort();
+ const expectedCandidateIds = [...snapshot.candidateIds].sort();
+ if (
+ currentCandidateIds.length !== expectedCandidateIds.length ||
+ currentCandidateIds.some(
+ (id, index) => id !== expectedCandidateIds[index],
+ )
+ ) {
+ throw this.synchronizePreviewStale();
+ }
+ if (expectedCandidateIds.length === 0) {
+ return [];
+ }
- const data = {
- is_active: false,
- deactivated_at: new Date(),
- deactivated_by_sync_job_id: jobId,
- };
+ for (const productId of expectedCandidateIds) {
+ await acquireProductMonetaryLock(tx, { productType, productId });
+ }
- await this.prisma.$transaction(async (tx) => {
- for (const productId of [...staleIds].sort()) {
- await acquireProductMonetaryLock(tx, { productType, productId });
- }
+ const data = {
+ is_active: false,
+ deactivated_at: new Date(),
+ deactivated_by_sync_job_id: jobId,
+ };
+
+ if (productType === ProductType.CAR) {
+ await tx.car.updateMany({
+ where: {
+ id: { in: expectedCandidateIds },
+ specialist_id: specialistId,
+ is_active: true,
+ },
+ data,
+ });
+ } else if (productType === ProductType.BOAT) {
+ await tx.boat.updateMany({
+ where: {
+ id: { in: expectedCandidateIds },
+ specialist_id: specialistId,
+ is_active: true,
+ },
+ data,
+ });
+ } else {
+ await tx.aircraft.updateMany({
+ where: {
+ id: { in: expectedCandidateIds },
+ specialist_id: specialistId,
+ is_active: true,
+ },
+ data,
+ });
+ }
+ return expectedCandidateIds;
+ },
+ {
+ isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
+ },
+ );
+ }
- if (productType === ProductType.CAR) {
- await tx.car.updateMany({
- where: { id: { in: staleIds }, specialist_id: specialistId },
- data,
- });
- } else if (productType === ProductType.BOAT) {
- await tx.boat.updateMany({
- where: { id: { in: staleIds }, specialist_id: specialistId },
- data,
- });
- } else {
- await tx.aircraft.updateMany({
- where: { id: { in: staleIds }, specialist_id: specialistId },
- data,
- });
- }
+ private synchronizePreviewStale(): ConflictException {
+ return new ConflictException({
+ code: 'SYNCHRONIZE_PREVIEW_STALE',
+ message:
+ 'O catálogo mudou desde a prévia. Nenhum produto foi desativado; gere uma nova prévia.',
});
-
- return staleIds;
}
private async getActiveProductIdsByType(
diff --git a/backend/src/features/product-import-jobs/product-sync-preview.postgres.spec.ts b/backend/src/features/product-import-jobs/product-sync-preview.postgres.spec.ts
new file mode 100644
index 0000000..86c3d89
--- /dev/null
+++ b/backend/src/features/product-import-jobs/product-sync-preview.postgres.spec.ts
@@ -0,0 +1,242 @@
+import { randomUUID } from 'node:crypto';
+import {
+ PrismaClient,
+ ProductImportJobStatus,
+ ProductType,
+ UserRole,
+} from '@prisma/client';
+import { ProductImportJobsService } from './product-import-jobs.service';
+
+const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL;
+const describeWithPostgres = databaseUrl ? describe : describe.skip;
+
+describeWithPostgres('product synchronization preview — PostgreSQL', () => {
+ const prisma = new PrismaClient({
+ datasources: { db: { url: databaseUrl! } },
+ });
+ const specialistId = randomUUID();
+ const adminId = randomUUID();
+ const suffix = randomUUID().replaceAll('-', '');
+ const row = {
+ marca: 'Ferrari',
+ modelo: 'Roma',
+ identificador: `KEEP-${suffix}`,
+ valor: '1000000',
+ estado: 'SP',
+ ano: '2024',
+ };
+ const xlsx = {
+ parseCsv: jest.fn().mockReturnValue({ rows: [row] }),
+ validateStructure: jest.fn().mockReturnValue({ valid: true }),
+ } as any;
+
+ beforeAll(async () => {
+ process.env.PRODUCT_IMPORT_PREVIEW_SECRET = 'postgres-preview-secret';
+ await prisma.user.create({
+ data: {
+ id: specialistId,
+ name: 'Sync',
+ surname: 'Specialist',
+ email: `sync-${suffix}@example.test`,
+ rg: suffix.slice(0, 11),
+ role: UserRole.SPECIALIST,
+ speciality: ProductType.CAR,
+ password_hash: 'not-used',
+ },
+ });
+ });
+
+ beforeEach(async () => {
+ await prisma.productImportJob.deleteMany({
+ where: { specialist_id: specialistId },
+ });
+ await prisma.car.deleteMany({ where: { specialist_id: specialistId } });
+ await prisma.car.createMany({
+ data: [
+ {
+ specialist_id: specialistId,
+ identificador: row.identificador,
+ marca: row.marca,
+ modelo: row.modelo,
+ valor: Number(row.valor),
+ estado: row.estado,
+ ano: Number(row.ano),
+ },
+ {
+ specialist_id: specialistId,
+ identificador: `STALE-B-${suffix}`,
+ marca: 'Legacy',
+ modelo: 'B',
+ valor: 500000,
+ estado: 'SP',
+ ano: 2020,
+ },
+ ],
+ });
+ });
+
+ afterAll(async () => {
+ await prisma.productImportJob.deleteMany({
+ where: { specialist_id: specialistId },
+ });
+ await prisma.car.deleteMany({ where: { specialist_id: specialistId } });
+ await prisma.user.delete({ where: { id: specialistId } });
+ await prisma.$disconnect();
+ delete process.env.PRODUCT_IMPORT_PREVIEW_SECRET;
+ });
+
+ function createService() {
+ const service = new ProductImportJobsService(
+ prisma as any,
+ xlsx,
+ { importImagesForProductFromFolder: jest.fn() } as any,
+ );
+ jest.spyOn(service as any, 'scheduleJob').mockImplementation(() => {});
+ return service;
+ }
+
+ function options(token: string) {
+ return {
+ mode: 'SYNCHRONIZE' as const,
+ confirmSynchronize: true,
+ synchronizePreviewToken: token,
+ context: {
+ actorId: adminId,
+ actorRole: UserRole.ADMIN,
+ actor: { id: adminId, role: UserRole.ADMIN, name: 'Admin', surname: '' },
+ specialistId,
+ specialist: {} as any,
+ delegated: true,
+ },
+ };
+ }
+
+ it('rejeita o POST se um novo candidato surgiu depois da prévia', async () => {
+ const service = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ await prisma.car.create({
+ data: {
+ specialist_id: specialistId,
+ identificador: `NEW-C-BEFORE-${suffix}`,
+ marca: 'New',
+ modelo: 'C',
+ valor: 600000,
+ estado: 'RJ',
+ ano: 2025,
+ },
+ });
+
+ await expect(
+ service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ ),
+ ).rejects.toMatchObject({
+ response: expect.objectContaining({ code: 'SYNCHRONIZE_PREVIEW_STALE' }),
+ });
+ await expect(
+ prisma.productImportJob.count({ where: { specialist_id: specialistId } }),
+ ).resolves.toBe(0);
+ });
+
+ it('não desativa nada se o catálogo mudar entre o POST e a execução', async () => {
+ const service = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+ const productC = await prisma.car.create({
+ data: {
+ specialist_id: specialistId,
+ identificador: `NEW-C-AFTER-${suffix}`,
+ marca: 'New',
+ modelo: 'C',
+ valor: 600000,
+ estado: 'RJ',
+ ano: 2025,
+ },
+ });
+
+ await (service as any).processJob(accepted.jobId);
+
+ const products = await prisma.car.findMany({
+ where: { specialist_id: specialistId },
+ select: { id: true, identificador: true, is_active: true },
+ });
+ expect(products).toHaveLength(3);
+ expect(products.every((product) => product.is_active)).toBe(true);
+ expect(products.find((product) => product.id === productC.id)?.is_active).toBe(
+ true,
+ );
+ await expect(
+ prisma.productImportJob.findUniqueOrThrow({
+ where: { id: accepted.jobId },
+ select: {
+ status: true,
+ deactivated_items: true,
+ error_message: true,
+ },
+ }),
+ ).resolves.toMatchObject({
+ status: ProductImportJobStatus.FAILED,
+ deactivated_items: 0,
+ error_message: expect.stringContaining('catálogo mudou'),
+ });
+ });
+
+ it('desativa somente o candidato consentido quando o snapshot permanece igual', async () => {
+ const service = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+
+ await (service as any).processJob(accepted.jobId);
+
+ const products = await prisma.car.findMany({
+ where: { specialist_id: specialistId },
+ select: { identificador: true, is_active: true },
+ });
+ expect(
+ products.find((product) => product.identificador === row.identificador),
+ ).toMatchObject({ is_active: true });
+ expect(
+ products.find((product) => product.identificador.startsWith('STALE-B-')),
+ ).toMatchObject({ is_active: false });
+ await expect(
+ prisma.productImportJob.findUniqueOrThrow({
+ where: { id: accepted.jobId },
+ select: { status: true, deactivated_items: true },
+ }),
+ ).resolves.toEqual({
+ status: ProductImportJobStatus.COMPLETED,
+ deactivated_items: 1,
+ });
+ });
+});
diff --git a/backend/src/features/products/product-delegated-audit.postgres.spec.ts b/backend/src/features/products/product-delegated-audit.postgres.spec.ts
new file mode 100644
index 0000000..46bd43f
--- /dev/null
+++ b/backend/src/features/products/product-delegated-audit.postgres.spec.ts
@@ -0,0 +1,166 @@
+import { randomUUID } from 'node:crypto';
+import { PrismaClient, ProductType, UserRole } from '@prisma/client';
+import { CarsController } from '../cars/cars.controller';
+import { CarsService } from '../cars/cars.service';
+import { BoatsController } from '../boats/boats.controller';
+import { BoatsService } from '../boats/boats.service';
+import { AircraftsController } from '../aircrafts/aircrafts.controller';
+import { AircraftsService } from '../aircrafts/aircrafts.service';
+
+const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL;
+const describeWithPostgres = databaseUrl ? describe : describe.skip;
+
+describeWithPostgres('delegated product mutation audit — PostgreSQL', () => {
+ const prisma = new PrismaClient({
+ datasources: { db: { url: databaseUrl! } },
+ });
+ const specialistId = randomUUID();
+ const adminId = randomUUID();
+ const suffix = randomUUID().replaceAll('-', '');
+ const s3 = {
+ uploadBase64Image: jest.fn(),
+ getSignedUrl: jest.fn(async (key) => key),
+ } as any;
+ const actorContext = {
+ resolve: jest.fn(async (user, target) => ({
+ actorId: user.id,
+ actorRole: user.role,
+ actor: { id: user.id, role: user.role, name: 'Admin', surname: '' },
+ specialistId: target,
+ specialist: {},
+ delegated: true,
+ })),
+ assertResourceSpecialist: jest.fn((context, owner) => {
+ if (context.specialistId !== owner) throw new Error('wrong owner');
+ }),
+ } as any;
+ const audit = {
+ record: jest.fn(async () => {
+ throw new Error('audit unavailable');
+ }),
+ } as any;
+ const jobs = {} as any;
+ const admin = { id: adminId, role: UserRole.ADMIN } as any;
+
+ beforeAll(async () => {
+ await prisma.user.create({
+ data: {
+ id: specialistId,
+ name: 'Audit',
+ surname: 'Specialist',
+ email: `audit-${suffix}@example.test`,
+ rg: suffix.slice(0, 11),
+ role: UserRole.SPECIALIST,
+ speciality: ProductType.CAR,
+ password_hash: 'not-used',
+ },
+ });
+ });
+
+ beforeEach(async () => {
+ audit.record.mockClear();
+ await prisma.car.deleteMany({ where: { specialist_id: specialistId } });
+ await prisma.boat.deleteMany({ where: { specialist_id: specialistId } });
+ await prisma.aircraft.deleteMany({
+ where: { specialist_id: specialistId },
+ });
+ });
+
+ afterAll(async () => {
+ await prisma.car.deleteMany({ where: { specialist_id: specialistId } });
+ await prisma.boat.deleteMany({ where: { specialist_id: specialistId } });
+ await prisma.aircraft.deleteMany({
+ where: { specialist_id: specialistId },
+ });
+ await prisma.user.delete({ where: { id: specialistId } });
+ await prisma.$disconnect();
+ });
+
+ const cases = [
+ {
+ label: 'CAR',
+ delegate: 'car',
+ controller: new CarsController(
+ new CarsService(prisma as any, s3),
+ jobs,
+ actorContext,
+ audit,
+ prisma as any,
+ ),
+ },
+ {
+ label: 'BOAT',
+ delegate: 'boat',
+ controller: new BoatsController(
+ new BoatsService(prisma as any, s3),
+ jobs,
+ actorContext,
+ audit,
+ prisma as any,
+ ),
+ },
+ {
+ label: 'AIRCRAFT',
+ delegate: 'aircraft',
+ controller: new AircraftsController(
+ new AircraftsService(prisma as any, s3),
+ jobs,
+ actorContext,
+ audit,
+ prisma as any,
+ ),
+ },
+ ] as const;
+
+ it.each(cases)(
+ 'reverte POST/PATCH/DELETE de $label quando a auditoria falha',
+ async ({ label, delegate, controller }) => {
+ const model = (prisma as any)[delegate];
+ const createDto = {
+ specialist_id: specialistId,
+ identificador: `${label}-CREATE-${suffix}`,
+ marca: 'Original',
+ modelo: 'Original',
+ valor: 100000,
+ estado: 'SP',
+ ano: 2024,
+ };
+
+ await expect(
+ (controller as any).create({ ...createDto }, admin),
+ ).rejects.toThrow('audit unavailable');
+ await expect(
+ model.count({ where: { identificador: createDto.identificador } }),
+ ).resolves.toBe(0);
+
+ const existing = await model.create({
+ data: {
+ ...createDto,
+ identificador: `${label}-EXISTING-${suffix}`,
+ },
+ });
+ await expect(
+ (controller as any).update(
+ existing.id,
+ { modelo: 'Changed' },
+ admin,
+ specialistId,
+ ),
+ ).rejects.toThrow('audit unavailable');
+ await expect(
+ model.findUnique({ where: { id: existing.id }, select: { modelo: true } }),
+ ).resolves.toEqual({ modelo: 'Original' });
+
+ await expect(
+ (controller as any).remove(existing.id, admin, specialistId),
+ ).rejects.toThrow('audit unavailable');
+ await expect(
+ model.findUnique({
+ where: { id: existing.id },
+ select: { is_active: true },
+ }),
+ ).resolves.toEqual({ is_active: true });
+ expect(audit.record).toHaveBeenCalledTimes(3);
+ },
+ );
+});
diff --git a/backend/src/features/products/product-monetary-lock.ts b/backend/src/features/products/product-monetary-lock.ts
index 6bbc9dc..e8edc47 100644
--- a/backend/src/features/products/product-monetary-lock.ts
+++ b/backend/src/features/products/product-monetary-lock.ts
@@ -120,10 +120,10 @@ export async function assertProductMonetaryFieldsUnlocked(
}
export async function updateProductWithMonetaryLock(
- prisma: PrismaService,
+ prisma: PrismaService | Prisma.TransactionClient,
input: ProductMonetaryUpdateInput,
): Promise {
- return prisma.$transaction(async (tx) => {
+ const update = async (tx: Prisma.TransactionClient) => {
await acquireProductMonetaryLock(tx, input);
const delegateName = PRODUCT_DELEGATE_BY_TYPE[input.productType];
@@ -152,5 +152,10 @@ export async function updateProductWithMonetaryLock(
where: { id: input.productId },
data: input.data,
});
- });
+ };
+
+ if ('$transaction' in prisma) {
+ return prisma.$transaction(update);
+ }
+ return update(prisma);
}
diff --git a/backend/test/admin-specialist-journey.e2e-spec.ts b/backend/test/admin-specialist-journey.e2e-spec.ts
index 6f8a700..1be3102 100644
--- a/backend/test/admin-specialist-journey.e2e-spec.ts
+++ b/backend/test/admin-specialist-journey.e2e-spec.ts
@@ -511,6 +511,16 @@ describePostgres('ADMIN acting for SPECIALIST journey (HTTP + PostgreSQL)', () =
city: 'Sao Paulo',
description: 'Approved E2E legal content',
};
+ await request(app.getHttpServer())
+ .post('/api/contracts/generate')
+ .query(target())
+ .auth(adminToken, { type: 'bearer' })
+ .send(contractDto)
+ .expect(401);
+ await expect(
+ prisma.contract.count({ where: { process_id: processId } }),
+ ).resolves.toBe(0);
+
const preview = await request(app.getHttpServer())
.post('/api/contracts/preview')
.query(target())
diff --git a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx
index 8d76069..e7168fd 100644
--- a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx
+++ b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx
@@ -85,6 +85,10 @@ export default function SpecialistJourneyProductsPage() {
const runImport = async () => {
if (!file || !preview) return;
if (mode === "SYNCHRONIZE" && !syncConfirmed) return;
+ if (mode === "SYNCHRONIZE" && !preview.synchronizePreviewToken) {
+ setError("A prévia expirou. Gere uma nova prévia antes de sincronizar.");
+ return;
+ }
setImporting(true);
setError(null);
try {
@@ -94,13 +98,23 @@ export default function SpecialistJourneyProductsPage() {
file,
mode,
syncConfirmed,
+ preview.synchronizePreviewToken,
);
window.alert(result.message);
setPreview(null);
setFile(null);
await load(1);
- } catch {
- setError("A importação não foi concluída. O catálogo não foi sincronizado.");
+ } catch (caught) {
+ const explicitMessage =
+ caught instanceof Error &&
+ (caught.message.includes("prévia") ||
+ caught.message.includes("catálogo mudou"))
+ ? caught.message
+ : null;
+ setError(
+ explicitMessage ??
+ "A importação não foi concluída. O catálogo não foi sincronizado.",
+ );
} finally {
setImporting(false);
}
diff --git a/frontend/src/services/admin-specialist-journey.service.test.ts b/frontend/src/services/admin-specialist-journey.service.test.ts
new file mode 100644
index 0000000..85af1c7
--- /dev/null
+++ b/frontend/src/services/admin-specialist-journey.service.test.ts
@@ -0,0 +1,34 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import api from "./api";
+import { importAdminCatalogCsv } from "./admin-specialist-journey.service";
+
+vi.mock("./api", () => ({
+ default: { post: vi.fn() },
+}));
+
+describe("admin specialist CSV synchronization", () => {
+ beforeEach(() => {
+ vi.mocked(api.post).mockReset();
+ vi.mocked(api.post).mockResolvedValue({
+ data: { success: true, message: "ok" },
+ });
+ });
+
+ it("envia o token exato da prévia ao confirmar SYNCHRONIZE", async () => {
+ const file = new File(["csv"], "catalog.csv", { type: "text/csv" });
+
+ await importAdminCatalogCsv(
+ "CAR",
+ "00000000-0000-4000-8000-000000000001",
+ file,
+ "SYNCHRONIZE",
+ true,
+ "signed-preview-token",
+ );
+
+ const form = vi.mocked(api.post).mock.calls[0][1] as FormData;
+ expect(form.get("synchronize_preview_token")).toBe(
+ "signed-preview-token",
+ );
+ });
+});
diff --git a/frontend/src/services/admin-specialist-journey.service.ts b/frontend/src/services/admin-specialist-journey.service.ts
index a635305..1773619 100644
--- a/frontend/src/services/admin-specialist-journey.service.ts
+++ b/frontend/src/services/admin-specialist-journey.service.ts
@@ -59,6 +59,7 @@ export type CsvImportPreview = {
targetSpecialistId: string;
mode: ProductImportMode;
requiresExplicitConfirmation: boolean;
+ synchronizePreviewToken?: string;
impact: {
csvRows: number;
existingProducts: number;
@@ -73,12 +74,16 @@ function importForm(
specialistId: string,
mode: ProductImportMode,
confirmSynchronize = false,
+ synchronizePreviewToken?: string,
): FormData {
const form = new FormData();
form.append("file", file);
form.append("specialist_id", specialistId);
form.append("mode", mode);
form.append("confirm_synchronize", String(confirmSynchronize));
+ if (synchronizePreviewToken) {
+ form.append("synchronize_preview_token", synchronizePreviewToken);
+ }
return form;
}
@@ -103,13 +108,20 @@ export async function importAdminCatalogCsv(
file: File,
mode: ProductImportMode,
confirmSynchronize: boolean,
+ synchronizePreviewToken?: string,
): Promise {
const resource = resourceByType[productType];
const response = await api.post<
CsvImportResponse | ImportJobAcceptedResponse
>(
`/${resource}/import-csv`,
- importForm(file, specialistId, mode, confirmSynchronize),
+ importForm(
+ file,
+ specialistId,
+ mode,
+ confirmSynchronize,
+ synchronizePreviewToken,
+ ),
{ headers: { "Content-Type": "multipart/form-data" } },
);
return resolveImportResponse(response.data);
diff --git a/frontend/src/services/product-import-jobs.service.test.ts b/frontend/src/services/product-import-jobs.service.test.ts
new file mode 100644
index 0000000..7b68eb2
--- /dev/null
+++ b/frontend/src/services/product-import-jobs.service.test.ts
@@ -0,0 +1,38 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import api from "./api";
+import { waitImportJobCompletion } from "./product-import-jobs.service";
+
+vi.mock("./api", () => ({
+ default: { get: vi.fn() },
+}));
+
+describe("waitImportJobCompletion", () => {
+ beforeEach(() => {
+ vi.mocked(api.get).mockReset();
+ });
+
+ it("propaga o erro explícito quando o catálogo diverge da prévia", async () => {
+ vi.mocked(api.get).mockResolvedValue({
+ data: {
+ jobId: "job-1",
+ status: "FAILED",
+ productType: "CAR",
+ totalItems: 1,
+ processedItems: 1,
+ successItems: 1,
+ warningItems: 0,
+ failedItems: 0,
+ deactivatedItems: 0,
+ reactivatedItems: 0,
+ errorMessage:
+ "O catálogo mudou desde a prévia. Gere uma nova prévia antes de sincronizar.",
+ done: true,
+ result: { success: false, message: "Importação falhou." },
+ },
+ });
+
+ await expect(waitImportJobCompletion("job-1", 0, 100)).rejects.toThrow(
+ "O catálogo mudou desde a prévia. Gere uma nova prévia antes de sincronizar.",
+ );
+ });
+});
diff --git a/frontend/src/services/product-import-jobs.service.ts b/frontend/src/services/product-import-jobs.service.ts
index baeb83e..cb57ba1 100644
--- a/frontend/src/services/product-import-jobs.service.ts
+++ b/frontend/src/services/product-import-jobs.service.ts
@@ -75,6 +75,9 @@ export async function waitImportJobCompletion(
const status = await getImportJobStatus(jobId);
if (status.done) {
+ if (status.status === "FAILED" && status.errorMessage) {
+ throw new Error(status.errorMessage);
+ }
return status.result;
}
From 2b35cbb2d991f92c4ea347fe7a7cf0afa78daf46 Mon Sep 17 00:00:00 2001
From: Messias-Olivindo
Date: Fri, 23 Oct 2026 12:28:57 -0300
Subject: [PATCH 55/60] fix(admin): harden specialist catalog synchronization
---
.../migration.sql | 6 +
backend/prisma/schema.prisma | 3 +
.../aircrafts/aircrafts.controller.spec.ts | 69 +-
.../aircrafts/aircrafts.controller.ts | 88 +-
.../features/aircrafts/aircrafts.service.ts | 117 +-
.../features/boats/boats.controller.spec.ts | 61 +-
.../src/features/boats/boats.controller.ts | 77 +-
backend/src/features/boats/boats.service.ts | 115 +-
.../src/features/cars/cars.controller.spec.ts | 62 +-
backend/src/features/cars/cars.controller.ts | 77 +-
backend/src/features/cars/cars.service.ts | 110 +-
.../drive-import/drive-import.service.spec.ts | 114 ++
.../drive-import/drive-import.service.ts | 205 ++-
.../product-import-jobs.service.spec.ts | 237 ++-
.../product-import-jobs.service.ts | 1447 ++++++++++++++---
.../product-sync-preview.postgres.spec.ts | 772 ++++++++-
.../product-image-preparation.spec.ts | 79 +
.../products/product-image-preparation.ts | 56 +
.../product-services-update-errors.spec.ts | 59 +
.../SpecialistJourneyProductsPage.test.tsx | 71 +
.../admin/SpecialistJourneyProductsPage.tsx | 2 +-
.../admin-specialist-journey.service.ts | 10 +-
22 files changed, 3292 insertions(+), 545 deletions(-)
create mode 100644 backend/prisma/migrations/20261023120000_add_product_import_job_lease/migration.sql
create mode 100644 backend/src/features/drive-import/drive-import.service.spec.ts
create mode 100644 backend/src/features/products/product-image-preparation.spec.ts
create mode 100644 backend/src/features/products/product-image-preparation.ts
create mode 100644 backend/src/features/products/product-services-update-errors.spec.ts
create mode 100644 frontend/src/pages/admin/SpecialistJourneyProductsPage.test.tsx
diff --git a/backend/prisma/migrations/20261023120000_add_product_import_job_lease/migration.sql b/backend/prisma/migrations/20261023120000_add_product_import_job_lease/migration.sql
new file mode 100644
index 0000000..9c30ae9
--- /dev/null
+++ b/backend/prisma/migrations/20261023120000_add_product_import_job_lease/migration.sql
@@ -0,0 +1,6 @@
+ALTER TABLE "ProductImportJob"
+ADD COLUMN "processing_lease_token" UUID,
+ADD COLUMN "processing_lease_expires_at" TIMESTAMP(3);
+
+CREATE INDEX "ProductImportJob_status_processing_lease_expires_at_idx"
+ON "ProductImportJob"("status", "processing_lease_expires_at");
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index d12b809..b1a1b1f 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1354,6 +1354,8 @@ model ProductImportJob {
started_at DateTime?
finished_at DateTime?
error_message String?
+ processing_lease_token String? @db.Uuid
+ processing_lease_expires_at DateTime?
created_at DateTime @default(now())
updated_at DateTime @updatedAt
@@ -1363,6 +1365,7 @@ model ProductImportJob {
@@index([specialist_id])
@@index([created_by_id])
@@index([status])
+ @@index([status, processing_lease_expires_at])
@@index([product_type])
@@index([created_at])
}
diff --git a/backend/src/features/aircrafts/aircrafts.controller.spec.ts b/backend/src/features/aircrafts/aircrafts.controller.spec.ts
index 996ba04..e825f56 100644
--- a/backend/src/features/aircrafts/aircrafts.controller.spec.ts
+++ b/backend/src/features/aircrafts/aircrafts.controller.spec.ts
@@ -9,6 +9,8 @@ function mkController() {
specialist_id: 'spec-1',
}),
update: jest.fn().mockResolvedValue({ id: 'aircraft-1' }),
+ prepareProductImages: jest.fn().mockResolvedValue([]),
+ cleanupPreparedImages: jest.fn().mockResolvedValue(undefined),
} as any;
const productImportJobsService = {
createJobFromCsv: jest.fn().mockResolvedValue({ id: 'job-1' }),
@@ -60,7 +62,11 @@ describe('AircraftsController — Calendly opcional', () => {
id: 'aircraft-1',
});
expect(dto.specialist_id).toBe(specialist.id);
- expect(aircraftsService.create).toHaveBeenCalledWith(dto, tx);
+ expect(aircraftsService.create).toHaveBeenCalledWith(
+ dto,
+ tx,
+ expect.objectContaining({ productId: expect.any(String), images: [] }),
+ );
});
it('não permite remover o owner no PATCH comum', async () => {
@@ -88,10 +94,71 @@ describe('AircraftsController — Calendly opcional', () => {
expect(aircraftsService.create).toHaveBeenCalledWith(
expect.objectContaining({ specialist_id: specialist.id }),
tx,
+ expect.objectContaining({ productId: expect.any(String), images: [] }),
);
expect(audit.record).toHaveBeenCalledWith(expect.any(Object), tx);
});
+ it('aguarda upload fora da transação e compensa se a auditoria falhar', async () => {
+ const { controller, aircraftsService, audit, prisma } = mkController();
+ const prepared = [
+ { image_url: 'aircrafts/new-key.jpg', is_primary: true },
+ ];
+ let finishUpload!: (images: typeof prepared) => void;
+ aircraftsService.prepareProductImages.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishUpload = resolve;
+ }),
+ );
+ audit.record.mockRejectedValueOnce(new Error('audit unavailable'));
+
+ const operation = controller.create(
+ { images: [{ data: 'base64', is_primary: true }] } as any,
+ specialist,
+ );
+ const rejection = expect(operation).rejects.toThrow('audit unavailable');
+ await Promise.resolve();
+
+ expect(aircraftsService.prepareProductImages).toHaveBeenCalledTimes(1);
+ expect(prisma.$transaction).not.toHaveBeenCalled();
+ finishUpload(prepared);
+ await rejection;
+ expect(aircraftsService.cleanupPreparedImages).toHaveBeenCalledWith(
+ prepared,
+ );
+ });
+
+ it('também prepara PATCH fora da transação e compensa falha de auditoria', async () => {
+ const { controller, aircraftsService, audit, prisma } = mkController();
+ const prepared = [
+ { image_url: 'aircrafts/patch-key.jpg', is_primary: true },
+ ];
+ let finishUpload!: (images: typeof prepared) => void;
+ aircraftsService.prepareProductImages.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishUpload = resolve;
+ }),
+ );
+ audit.record.mockRejectedValueOnce(new Error('audit unavailable'));
+
+ const operation = controller.update(
+ 'aircraft-1',
+ { images: [{ data: 'base64', is_primary: true }] } as any,
+ specialist,
+ );
+ const rejection = expect(operation).rejects.toThrow('audit unavailable');
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(aircraftsService.prepareProductImages).toHaveBeenCalledTimes(1);
+ expect(prisma.$transaction).not.toHaveBeenCalled();
+ finishUpload(prepared);
+ await rejection;
+ expect(aircraftsService.cleanupPreparedImages).toHaveBeenCalledWith(
+ prepared,
+ );
+ });
+
it('permite importação CSV sem consultar Calendly', async () => {
const { controller, productImportJobsService } = mkController();
const file = {
diff --git a/backend/src/features/aircrafts/aircrafts.controller.ts b/backend/src/features/aircrafts/aircrafts.controller.ts
index 7e00032..446bd77 100644
--- a/backend/src/features/aircrafts/aircrafts.controller.ts
+++ b/backend/src/features/aircrafts/aircrafts.controller.ts
@@ -36,6 +36,7 @@ import { ActorContextService } from 'src/shared/actor-context/actor-context.serv
import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
import { ProductCsvImportDto } from '../product-import-jobs/dto/product-csv-import.dto';
import { PrismaService } from 'src/prisma/prisma.service';
+import { randomUUID } from 'node:crypto';
@Controller('aircrafts')
export class AircraftsController {
@@ -59,22 +60,33 @@ export class AircraftsController {
ProductType.AIRCRAFT,
);
createAircraftDto.specialist_id = context.specialistId;
- return this.prisma.$transaction(async (tx) => {
- const aircraft = await this.aircraftsService.create(
- createAircraftDto,
- tx,
- );
- await this.delegatedAudit.record(
- {
- context,
- action: 'PRODUCT_CREATE',
- resourceType: 'AIRCRAFT',
- resourceId: aircraft.id,
- },
- tx,
- );
- return aircraft;
- });
+ const productId = randomUUID();
+ const preparedImages = await this.aircraftsService.prepareProductImages(
+ productId,
+ createAircraftDto.images,
+ );
+ try {
+ return await this.prisma.$transaction(async (tx) => {
+ const aircraft = await this.aircraftsService.create(
+ createAircraftDto,
+ tx,
+ { productId, images: preparedImages },
+ );
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_CREATE',
+ resourceType: 'AIRCRAFT',
+ resourceId: aircraft.id,
+ },
+ tx,
+ );
+ return aircraft;
+ });
+ } catch (error) {
+ await this.aircraftsService.cleanupPreparedImages(preparedImages);
+ throw error;
+ }
}
@Post('import-csv/preview')
@@ -266,23 +278,33 @@ export class AircraftsController {
context,
existing?.specialist_id,
);
- return this.prisma.$transaction(async (tx) => {
- const aircraft = await this.aircraftsService.update(
- id,
- updateAircraftDto,
- tx,
- );
- await this.delegatedAudit.record(
- {
- context,
- action: 'PRODUCT_UPDATE',
- resourceType: 'AIRCRAFT',
- resourceId: id,
- },
- tx,
- );
- return aircraft;
- });
+ const preparedImages = await this.aircraftsService.prepareProductImages(
+ id,
+ updateAircraftDto.images,
+ );
+ try {
+ return await this.prisma.$transaction(async (tx) => {
+ const aircraft = await this.aircraftsService.update(
+ id,
+ updateAircraftDto,
+ tx,
+ { images: preparedImages },
+ );
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_UPDATE',
+ resourceType: 'AIRCRAFT',
+ resourceId: id,
+ },
+ tx,
+ );
+ return aircraft;
+ });
+ } catch (error) {
+ await this.aircraftsService.cleanupPreparedImages(preparedImages);
+ throw error;
+ }
}
@Delete(':id')
diff --git a/backend/src/features/aircrafts/aircrafts.service.ts b/backend/src/features/aircrafts/aircrafts.service.ts
index daddbb0..3c73d5b 100644
--- a/backend/src/features/aircrafts/aircrafts.service.ts
+++ b/backend/src/features/aircrafts/aircrafts.service.ts
@@ -1,4 +1,9 @@
-import { Injectable, NotFoundException, Logger } from '@nestjs/common';
+import {
+ HttpException,
+ Injectable,
+ NotFoundException,
+ Logger,
+} from '@nestjs/common';
import { CreateAircraftDto } from './dto/create-aircraft.dto';
import { UpdateAircraftDto } from './dto/update-aircraft.dto';
import { PrismaService } from 'src/prisma/prisma.service';
@@ -14,6 +19,13 @@ import { Prisma, ProductType } from '@prisma/client';
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';
+import { randomUUID } from 'node:crypto';
+import {
+ cleanupPreparedProductImages,
+ prepareProductImages,
+ PreparedProductImage,
+ ProductImageInput,
+} from '../products/product-image-preparation';
@Injectable()
export class AircraftsService {
@@ -27,12 +39,34 @@ export class AircraftsService {
private s3Service: S3Service,
) {}
+ prepareProductImages(productId: string, images?: ProductImageInput[]) {
+ return prepareProductImages(
+ this.s3Service,
+ 'aircrafts',
+ productId,
+ images,
+ );
+ }
+
+ cleanupPreparedImages(images: PreparedProductImage[]) {
+ return cleanupPreparedProductImages(this.s3Service, images);
+ }
+
async create(
createAircraftDto: CreateAircraftDto,
client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ preparedWrite?: {
+ productId: string;
+ images: PreparedProductImage[];
+ },
) {
this.logger.log('[create] Iniciando criação de nova aeronave');
const { specialist_id, images, ...aircraftData } = createAircraftDto;
+ const productId = preparedWrite?.productId ?? randomUUID();
+ const ownsPreparedImages = !preparedWrite;
+ const preparedImages =
+ preparedWrite?.images ??
+ (await this.prepareProductImages(productId, images));
const payload: Prisma.AircraftUncheckedCreateInput = {
categoria: aircraftData.categoria,
@@ -47,6 +81,7 @@ export class AircraftsService {
currency: aircraftData.currency,
tipo_aeronave: aircraftData.tipo_aeronave,
specialist_id: specialist_id ?? null,
+ id: productId,
};
try {
@@ -61,37 +96,23 @@ export class AircraftsService {
`[create] Aeronave criada com sucesso - ID: ${aircraft.id}`,
);
- // 2. Processar e fazer upload das imagens, se existirem
- if (images && images.length > 0) {
+ // 2. Persistir somente referências já preparadas fora da transação
+ if (preparedImages.length > 0) {
this.logger.log(
- `[create] Processando ${images.length} imagens para a aeronave ${aircraft.id}`,
+ `[create] Persistindo ${preparedImages.length} imagens para a aeronave ${aircraft.id}`,
);
- for (let i = 0; i < images.length; i++) {
- const image = images[i];
-
- const timestamp = Date.now();
- const key = `aircrafts/${aircraft.id}/${timestamp}-${i}.jpg`;
-
- this.logger.debug(
- `[create] Fazendo upload da imagem ${i + 1}/${images.length} para S3`,
- );
- const imageKey = await this.s3Service.uploadBase64Image(
- image.data,
- key,
- );
-
+ for (const image of preparedImages) {
await client.aircraft_image.create({
data: {
aircraft_id: aircraft.id,
- image_url: imageKey,
+ image_url: image.image_url,
is_primary: image.is_primary,
product_type: 'AIRCRAFT',
},
});
- this.logger.debug(`[create] Imagem ${i + 1} salva com sucesso`);
}
this.logger.log(
- `[create] Todas as ${images.length} imagens processadas com sucesso`,
+ `[create] Todas as ${preparedImages.length} imagens persistidas com sucesso`,
);
}
@@ -108,7 +129,13 @@ export class AircraftsService {
);
return aircraftWithImages;
} catch (error) {
- if (error instanceof Prisma.PrismaClientKnownRequestError) {
+ if (ownsPreparedImages) {
+ await this.cleanupPreparedImages(preparedImages);
+ }
+ if (
+ error instanceof HttpException ||
+ error instanceof Prisma.PrismaClientKnownRequestError
+ ) {
throw error;
}
this.logger.error(
@@ -265,8 +292,12 @@ export class AircraftsService {
id: string,
updateAircraftDto: UpdateAircraftDto,
client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ preparedWrite?: { images: PreparedProductImage[] },
) {
const { specialist_id, images, ...aircraftData } = updateAircraftDto;
+ const ownsPreparedImages = !preparedWrite;
+ const preparedImages =
+ preparedWrite?.images ?? (await this.prepareProductImages(id, images));
const payload: Prisma.AircraftUncheckedUpdateInput = {};
if (aircraftData.categoria !== undefined) {
@@ -306,16 +337,16 @@ export class AircraftsService {
payload.specialist_id = specialist_id ?? null;
}
- await updateProductWithMonetaryLock(client, {
- productType: ProductType.AIRCRAFT,
- productId: id,
- nextValue: updateAircraftDto.valor,
- nextCurrency: updateAircraftDto.currency,
- data: payload,
- notFoundMessage: 'Aircraft not found',
- });
-
try {
+ await updateProductWithMonetaryLock(client, {
+ productType: ProductType.AIRCRAFT,
+ productId: id,
+ nextValue: updateAircraftDto.valor,
+ nextCurrency: updateAircraftDto.currency,
+ data: payload,
+ notFoundMessage: 'Aircraft not found',
+ });
+
// 1. Se houver novas imagens, processar
if (images && images.length > 0) {
// Remover imagens antigas
@@ -323,22 +354,12 @@ export class AircraftsService {
where: { aircraft_id: id },
});
- // Adicionar novas imagens
- for (let i = 0; i < images.length; i++) {
- const image = images[i];
-
- const timestamp = Date.now();
- const key = `aircrafts/${id}/${timestamp}-${i}.jpg`;
-
- const imageKey = await this.s3Service.uploadBase64Image(
- image.data,
- key,
- );
-
+ // Adicionar referências das imagens já preparadas
+ for (const image of preparedImages) {
await client.aircraft_image.create({
data: {
aircraft_id: id,
- image_url: imageKey,
+ image_url: image.image_url,
is_primary: image.is_primary,
product_type: 'AIRCRAFT',
},
@@ -352,7 +373,13 @@ export class AircraftsService {
include: { images: true },
});
} catch (error) {
- if (error instanceof Prisma.PrismaClientKnownRequestError) {
+ if (ownsPreparedImages) {
+ await this.cleanupPreparedImages(preparedImages);
+ }
+ if (
+ error instanceof HttpException ||
+ error instanceof Prisma.PrismaClientKnownRequestError
+ ) {
throw error;
}
throw new Error(`Erro ao atualizar aeronave: ${error.message}`);
diff --git a/backend/src/features/boats/boats.controller.spec.ts b/backend/src/features/boats/boats.controller.spec.ts
index 75354a7..d6a6430 100644
--- a/backend/src/features/boats/boats.controller.spec.ts
+++ b/backend/src/features/boats/boats.controller.spec.ts
@@ -9,6 +9,8 @@ function mkController() {
specialist_id: 'spec-1',
}),
update: jest.fn().mockResolvedValue({ id: 'boat-1' }),
+ prepareProductImages: jest.fn().mockResolvedValue([]),
+ cleanupPreparedImages: jest.fn().mockResolvedValue(undefined),
} as any;
const productImportJobsService = {
createJobFromCsv: jest.fn().mockResolvedValue({ id: 'job-1' }),
@@ -60,7 +62,11 @@ describe('BoatsController — Calendly opcional', () => {
id: 'boat-1',
});
expect(dto.specialist_id).toBe(specialist.id);
- expect(boatsService.create).toHaveBeenCalledWith(dto, tx);
+ expect(boatsService.create).toHaveBeenCalledWith(
+ dto,
+ tx,
+ expect.objectContaining({ productId: expect.any(String), images: [] }),
+ );
});
it('não permite trocar o owner no PATCH comum', async () => {
@@ -88,10 +94,63 @@ describe('BoatsController — Calendly opcional', () => {
expect(boatsService.create).toHaveBeenCalledWith(
expect.objectContaining({ specialist_id: specialist.id }),
tx,
+ expect.objectContaining({ productId: expect.any(String), images: [] }),
);
expect(audit.record).toHaveBeenCalledWith(expect.any(Object), tx);
});
+ it('aguarda upload fora da transação e compensa se a auditoria falhar', async () => {
+ const { controller, boatsService, audit, prisma } = mkController();
+ const prepared = [{ image_url: 'boats/new-key.jpg', is_primary: true }];
+ let finishUpload!: (images: typeof prepared) => void;
+ boatsService.prepareProductImages.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishUpload = resolve;
+ }),
+ );
+ audit.record.mockRejectedValueOnce(new Error('audit unavailable'));
+
+ const operation = controller.create(
+ { images: [{ data: 'base64', is_primary: true }] } as any,
+ specialist,
+ );
+ const rejection = expect(operation).rejects.toThrow('audit unavailable');
+ await Promise.resolve();
+
+ expect(boatsService.prepareProductImages).toHaveBeenCalledTimes(1);
+ expect(prisma.$transaction).not.toHaveBeenCalled();
+ finishUpload(prepared);
+ await rejection;
+ expect(boatsService.cleanupPreparedImages).toHaveBeenCalledWith(prepared);
+ });
+
+ it('também prepara PATCH fora da transação e compensa falha de auditoria', async () => {
+ const { controller, boatsService, audit, prisma } = mkController();
+ const prepared = [{ image_url: 'boats/patch-key.jpg', is_primary: true }];
+ let finishUpload!: (images: typeof prepared) => void;
+ boatsService.prepareProductImages.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishUpload = resolve;
+ }),
+ );
+ audit.record.mockRejectedValueOnce(new Error('audit unavailable'));
+
+ const operation = controller.update(
+ 'boat-1',
+ { images: [{ data: 'base64', is_primary: true }] } as any,
+ specialist,
+ );
+ const rejection = expect(operation).rejects.toThrow('audit unavailable');
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(boatsService.prepareProductImages).toHaveBeenCalledTimes(1);
+ expect(prisma.$transaction).not.toHaveBeenCalled();
+ finishUpload(prepared);
+ await rejection;
+ expect(boatsService.cleanupPreparedImages).toHaveBeenCalledWith(prepared);
+ });
+
it('permite importação CSV sem consultar Calendly', async () => {
const { controller, productImportJobsService } = mkController();
const file = {
diff --git a/backend/src/features/boats/boats.controller.ts b/backend/src/features/boats/boats.controller.ts
index b86ac3b..55cad87 100644
--- a/backend/src/features/boats/boats.controller.ts
+++ b/backend/src/features/boats/boats.controller.ts
@@ -36,6 +36,7 @@ import { ActorContextService } from 'src/shared/actor-context/actor-context.serv
import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
import { ProductCsvImportDto } from '../product-import-jobs/dto/product-csv-import.dto';
import { PrismaService } from 'src/prisma/prisma.service';
+import { randomUUID } from 'node:crypto';
@Controller('boats')
export class BoatsController {
@@ -59,19 +60,32 @@ export class BoatsController {
ProductType.BOAT,
);
createBoatDto.specialist_id = context.specialistId;
- return this.prisma.$transaction(async (tx) => {
- const boat = await this.boatsService.create(createBoatDto, tx);
- await this.delegatedAudit.record(
- {
- context,
- action: 'PRODUCT_CREATE',
- resourceType: 'BOAT',
- resourceId: boat.id,
- },
- tx,
- );
- return boat;
- });
+ const productId = randomUUID();
+ const preparedImages = await this.boatsService.prepareProductImages(
+ productId,
+ createBoatDto.images,
+ );
+ try {
+ return await this.prisma.$transaction(async (tx) => {
+ const boat = await this.boatsService.create(createBoatDto, tx, {
+ productId,
+ images: preparedImages,
+ });
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_CREATE',
+ resourceType: 'BOAT',
+ resourceId: boat.id,
+ },
+ tx,
+ );
+ return boat;
+ });
+ } catch (error) {
+ await this.boatsService.cleanupPreparedImages(preparedImages);
+ throw error;
+ }
}
@Post('import-csv/preview')
@@ -262,19 +276,30 @@ export class BoatsController {
context,
existing?.specialist_id,
);
- return this.prisma.$transaction(async (tx) => {
- const boat = await this.boatsService.update(id, updateBoatDto, tx);
- await this.delegatedAudit.record(
- {
- context,
- action: 'PRODUCT_UPDATE',
- resourceType: 'BOAT',
- resourceId: id,
- },
- tx,
- );
- return boat;
- });
+ const preparedImages = await this.boatsService.prepareProductImages(
+ id,
+ updateBoatDto.images,
+ );
+ try {
+ return await this.prisma.$transaction(async (tx) => {
+ const boat = await this.boatsService.update(id, updateBoatDto, tx, {
+ images: preparedImages,
+ });
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_UPDATE',
+ resourceType: 'BOAT',
+ resourceId: id,
+ },
+ tx,
+ );
+ return boat;
+ });
+ } catch (error) {
+ await this.boatsService.cleanupPreparedImages(preparedImages);
+ throw error;
+ }
}
@Delete(':id')
diff --git a/backend/src/features/boats/boats.service.ts b/backend/src/features/boats/boats.service.ts
index c240bf5..92ac180 100644
--- a/backend/src/features/boats/boats.service.ts
+++ b/backend/src/features/boats/boats.service.ts
@@ -1,4 +1,9 @@
-import { Injectable, NotFoundException, Logger } from '@nestjs/common';
+import {
+ HttpException,
+ Injectable,
+ NotFoundException,
+ Logger,
+} from '@nestjs/common';
import { Prisma, ProductType } from '@prisma/client';
import { CreateBoatDto } from './dto/create-boat.dto';
import { UpdateBoatDto } from './dto/update-boat.dto';
@@ -14,6 +19,13 @@ import {
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';
+import { randomUUID } from 'node:crypto';
+import {
+ cleanupPreparedProductImages,
+ prepareProductImages,
+ PreparedProductImage,
+ ProductImageInput,
+} from '../products/product-image-preparation';
@Injectable()
export class BoatsService {
@@ -27,52 +39,57 @@ export class BoatsService {
private s3Service: S3Service,
) {}
+ prepareProductImages(productId: string, images?: ProductImageInput[]) {
+ return prepareProductImages(this.s3Service, 'boats', productId, images);
+ }
+
+ cleanupPreparedImages(images: PreparedProductImage[]) {
+ return cleanupPreparedProductImages(this.s3Service, images);
+ }
+
async create(
createBoatDto: CreateBoatDto,
client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ preparedWrite?: {
+ productId: string;
+ images: PreparedProductImage[];
+ },
) {
this.logger.log('[create] Iniciando criação de novo barco');
const { images, ...boatData } = createBoatDto;
+ const productId = preparedWrite?.productId ?? randomUUID();
+ const ownsPreparedImages = !preparedWrite;
+ const preparedImages =
+ preparedWrite?.images ??
+ (await this.prepareProductImages(productId, images));
try {
// 1. Criar o barco
this.logger.debug(
`[create] Criando barco: ${boatData.marca} ${boatData.modelo}`,
);
- const boat = await client.boat.create({ data: boatData });
+ const boat = await client.boat.create({
+ data: { ...boatData, id: productId },
+ });
this.logger.log(`[create] Barco criado com sucesso - ID: ${boat.id}`);
- // 2. Processar e fazer upload das imagens, se existirem
- if (images && images.length > 0) {
+ // 2. Persistir somente referências já preparadas fora da transação
+ if (preparedImages.length > 0) {
this.logger.log(
- `[create] Processando ${images.length} imagens para o barco ${boat.id}`,
+ `[create] Persistindo ${preparedImages.length} imagens para o barco ${boat.id}`,
);
- for (let i = 0; i < images.length; i++) {
- const image = images[i];
-
- const timestamp = Date.now();
- const key = `boats/${boat.id}/${timestamp}-${i}.jpg`;
-
- this.logger.debug(
- `[create] Fazendo upload da imagem ${i + 1}/${images.length} para S3`,
- );
- const imageKey = await this.s3Service.uploadBase64Image(
- image.data,
- key,
- );
-
+ for (const image of preparedImages) {
await client.boat_image.create({
data: {
boat_id: boat.id,
- image_url: imageKey,
+ image_url: image.image_url,
is_primary: image.is_primary,
product_type: 'BOAT',
},
});
- this.logger.debug(`[create] Imagem ${i + 1} salva com sucesso`);
}
this.logger.log(
- `[create] Todas as ${images.length} imagens processadas com sucesso`,
+ `[create] Todas as ${preparedImages.length} imagens persistidas com sucesso`,
);
}
@@ -89,7 +106,13 @@ export class BoatsService {
);
return boatWithImages;
} catch (error) {
- if (error instanceof Prisma.PrismaClientKnownRequestError) {
+ if (ownsPreparedImages) {
+ await this.cleanupPreparedImages(preparedImages);
+ }
+ if (
+ error instanceof HttpException ||
+ error instanceof Prisma.PrismaClientKnownRequestError
+ ) {
throw error;
}
this.logger.error(
@@ -238,19 +261,23 @@ export class BoatsService {
id: string,
updateBoatDto: UpdateBoatDto,
client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ preparedWrite?: { images: PreparedProductImage[] },
) {
const { images, ...boatData } = updateBoatDto;
-
- await updateProductWithMonetaryLock(client, {
- productType: ProductType.BOAT,
- productId: id,
- nextValue: updateBoatDto.valor,
- nextCurrency: updateBoatDto.currency,
- data: boatData,
- notFoundMessage: 'Boat not found',
- });
+ const ownsPreparedImages = !preparedWrite;
+ const preparedImages =
+ preparedWrite?.images ?? (await this.prepareProductImages(id, images));
try {
+ await updateProductWithMonetaryLock(client, {
+ productType: ProductType.BOAT,
+ productId: id,
+ nextValue: updateBoatDto.valor,
+ nextCurrency: updateBoatDto.currency,
+ data: boatData,
+ notFoundMessage: 'Boat not found',
+ });
+
// 1. Se houver novas imagens, processar
if (images && images.length > 0) {
// Remover imagens antigas
@@ -258,22 +285,12 @@ export class BoatsService {
where: { boat_id: id },
});
- // Adicionar novas imagens
- for (let i = 0; i < images.length; i++) {
- const image = images[i];
-
- const timestamp = Date.now();
- const key = `boats/${id}/${timestamp}-${i}.jpg`;
-
- const imageKey = await this.s3Service.uploadBase64Image(
- image.data,
- key,
- );
-
+ // Adicionar referências das imagens já preparadas
+ for (const image of preparedImages) {
await client.boat_image.create({
data: {
boat_id: id,
- image_url: imageKey,
+ image_url: image.image_url,
is_primary: image.is_primary,
product_type: 'BOAT',
},
@@ -287,7 +304,13 @@ export class BoatsService {
include: { images: true },
});
} catch (error) {
- if (error instanceof Prisma.PrismaClientKnownRequestError) {
+ if (ownsPreparedImages) {
+ await this.cleanupPreparedImages(preparedImages);
+ }
+ if (
+ error instanceof HttpException ||
+ error instanceof Prisma.PrismaClientKnownRequestError
+ ) {
throw error;
}
throw new Error(`Erro ao atualizar lancha: ${error.message}`);
diff --git a/backend/src/features/cars/cars.controller.spec.ts b/backend/src/features/cars/cars.controller.spec.ts
index b4742c7..bfc5129 100644
--- a/backend/src/features/cars/cars.controller.spec.ts
+++ b/backend/src/features/cars/cars.controller.spec.ts
@@ -9,6 +9,8 @@ function mkController() {
specialist_id: 'spec-1',
}),
update: jest.fn().mockResolvedValue({ id: 'car-1' }),
+ prepareProductImages: jest.fn().mockResolvedValue([]),
+ cleanupPreparedImages: jest.fn().mockResolvedValue(undefined),
} as any;
const productImportJobsService = {
createJobFromCsv: jest.fn().mockResolvedValue({ id: 'job-1' }),
@@ -61,7 +63,11 @@ describe('CarsController — Calendly opcional', () => {
id: 'car-1',
});
expect(dto.specialist_id).toBe(specialist.id);
- expect(carsService.create).toHaveBeenCalledWith(dto, tx);
+ expect(carsService.create).toHaveBeenCalledWith(
+ dto,
+ tx,
+ expect.objectContaining({ productId: expect.any(String), images: [] }),
+ );
});
it('mantém ADMIN como ator e grava o SPECIALIST selecionado como owner', async () => {
@@ -79,6 +85,7 @@ describe('CarsController — Calendly opcional', () => {
expect(carsService.create).toHaveBeenCalledWith(
expect.objectContaining({ specialist_id: 'spec-1' }),
tx,
+ expect.objectContaining({ productId: expect.any(String), images: [] }),
);
expect(audit.record).toHaveBeenCalledWith(
expect.objectContaining({
@@ -102,10 +109,63 @@ describe('CarsController — Calendly opcional', () => {
expect(carsService.create).toHaveBeenCalledWith(
expect.objectContaining({ specialist_id: specialist.id }),
tx,
+ expect.objectContaining({ productId: expect.any(String), images: [] }),
);
expect(audit.record).toHaveBeenCalledWith(expect.any(Object), tx);
});
+ it('aguarda upload fora da transação e compensa se a auditoria falhar', async () => {
+ const { controller, carsService, audit, prisma } = mkController();
+ const prepared = [{ image_url: 'cars/new-key.jpg', is_primary: true }];
+ let finishUpload!: (images: typeof prepared) => void;
+ carsService.prepareProductImages.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishUpload = resolve;
+ }),
+ );
+ audit.record.mockRejectedValueOnce(new Error('audit unavailable'));
+
+ const operation = controller.create(
+ { images: [{ data: 'base64', is_primary: true }] } as any,
+ specialist,
+ );
+ const rejection = expect(operation).rejects.toThrow('audit unavailable');
+ await Promise.resolve();
+
+ expect(carsService.prepareProductImages).toHaveBeenCalledTimes(1);
+ expect(prisma.$transaction).not.toHaveBeenCalled();
+ finishUpload(prepared);
+ await rejection;
+ expect(carsService.cleanupPreparedImages).toHaveBeenCalledWith(prepared);
+ });
+
+ it('também prepara PATCH fora da transação e compensa falha de auditoria', async () => {
+ const { controller, carsService, audit, prisma } = mkController();
+ const prepared = [{ image_url: 'cars/patch-key.jpg', is_primary: true }];
+ let finishUpload!: (images: typeof prepared) => void;
+ carsService.prepareProductImages.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishUpload = resolve;
+ }),
+ );
+ audit.record.mockRejectedValueOnce(new Error('audit unavailable'));
+
+ const operation = controller.update(
+ 'car-1',
+ { images: [{ data: 'base64', is_primary: true }] } as any,
+ specialist,
+ );
+ const rejection = expect(operation).rejects.toThrow('audit unavailable');
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(carsService.prepareProductImages).toHaveBeenCalledTimes(1);
+ expect(prisma.$transaction).not.toHaveBeenCalled();
+ finishUpload(prepared);
+ await rejection;
+ expect(carsService.cleanupPreparedImages).toHaveBeenCalledWith(prepared);
+ });
+
it('não permite remover o owner com specialist_id null no PATCH', async () => {
const { controller, carsService } = mkController();
diff --git a/backend/src/features/cars/cars.controller.ts b/backend/src/features/cars/cars.controller.ts
index 8266742..4e7fe34 100644
--- a/backend/src/features/cars/cars.controller.ts
+++ b/backend/src/features/cars/cars.controller.ts
@@ -33,6 +33,7 @@ import { ActorContextService } from 'src/shared/actor-context/actor-context.serv
import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
import { ProductCsvImportDto } from '../product-import-jobs/dto/product-csv-import.dto';
import { PrismaService } from 'src/prisma/prisma.service';
+import { randomUUID } from 'node:crypto';
@Controller('cars')
export class CarsController {
@@ -56,19 +57,32 @@ export class CarsController {
ProductType.CAR,
);
createCarDto.specialist_id = context.specialistId;
- return this.prisma.$transaction(async (tx) => {
- const car = await this.carsService.create(createCarDto, tx);
- await this.delegatedAudit.record(
- {
- context,
- action: 'PRODUCT_CREATE',
- resourceType: 'CAR',
- resourceId: car!.id,
- },
- tx,
- );
- return car;
- });
+ const productId = randomUUID();
+ const preparedImages = await this.carsService.prepareProductImages(
+ productId,
+ createCarDto.images,
+ );
+ try {
+ return await this.prisma.$transaction(async (tx) => {
+ const car = await this.carsService.create(createCarDto, tx, {
+ productId,
+ images: preparedImages,
+ });
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_CREATE',
+ resourceType: 'CAR',
+ resourceId: car!.id,
+ },
+ tx,
+ );
+ return car;
+ });
+ } catch (error) {
+ await this.carsService.cleanupPreparedImages(preparedImages);
+ throw error;
+ }
}
@Post('import-csv/preview')
@@ -259,19 +273,30 @@ export class CarsController {
context,
existing?.specialist_id,
);
- return this.prisma.$transaction(async (tx) => {
- const car = await this.carsService.update(id, updateCarDto, tx);
- await this.delegatedAudit.record(
- {
- context,
- action: 'PRODUCT_UPDATE',
- resourceType: 'CAR',
- resourceId: id,
- },
- tx,
- );
- return car;
- });
+ const preparedImages = await this.carsService.prepareProductImages(
+ id,
+ updateCarDto.images,
+ );
+ try {
+ return await this.prisma.$transaction(async (tx) => {
+ const car = await this.carsService.update(id, updateCarDto, tx, {
+ images: preparedImages,
+ });
+ await this.delegatedAudit.record(
+ {
+ context,
+ action: 'PRODUCT_UPDATE',
+ resourceType: 'CAR',
+ resourceId: id,
+ },
+ tx,
+ );
+ return car;
+ });
+ } catch (error) {
+ await this.carsService.cleanupPreparedImages(preparedImages);
+ throw error;
+ }
}
@Delete(':id')
diff --git a/backend/src/features/cars/cars.service.ts b/backend/src/features/cars/cars.service.ts
index a5ec712..9cb6ddd 100644
--- a/backend/src/features/cars/cars.service.ts
+++ b/backend/src/features/cars/cars.service.ts
@@ -1,4 +1,9 @@
-import { Injectable, NotFoundException, Logger } from '@nestjs/common';
+import {
+ HttpException,
+ Injectable,
+ NotFoundException,
+ Logger,
+} from '@nestjs/common';
import { Prisma, ProductType } from '@prisma/client';
import { CreateCarDto } from './dto/create-car.dto';
import { UpdateCarDto } from './dto/update-car.dto';
@@ -14,6 +19,13 @@ import {
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';
+import { randomUUID } from 'node:crypto';
+import {
+ cleanupPreparedProductImages,
+ prepareProductImages,
+ PreparedProductImage,
+ ProductImageInput,
+} from '../products/product-image-preparation';
@Injectable()
export class CarsService {
@@ -27,36 +39,42 @@ export class CarsService {
private s3Service: S3Service,
) {}
+ prepareProductImages(productId: string, images?: ProductImageInput[]) {
+ return prepareProductImages(this.s3Service, 'cars', productId, images);
+ }
+
+ cleanupPreparedImages(images: PreparedProductImage[]) {
+ return cleanupPreparedProductImages(this.s3Service, images);
+ }
+
async create(
createCarDto: CreateCarDto,
client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ preparedWrite?: {
+ productId: string;
+ images: PreparedProductImage[];
+ },
) {
const { images, ...carData } = createCarDto;
+ const productId = preparedWrite?.productId ?? randomUUID();
+ const ownsPreparedImages = !preparedWrite;
+ const preparedImages =
+ preparedWrite?.images ??
+ (await this.prepareProductImages(productId, images));
try {
// 1. Criar o carro
- const car = await client.car.create({ data: carData });
-
- // 2. Processar e fazer upload das imagens, se existirem
- if (images && images.length > 0) {
- for (let i = 0; i < images.length; i++) {
- const image = images[i];
-
- // Gerar chave única para a imagem no S3
- const timestamp = Date.now();
- const key = `cars/${car.id}/${timestamp}-${i}.jpg`;
-
- // Upload da imagem base64 para o S3
- const imageKey = await this.s3Service.uploadBase64Image(
- image.data,
- key,
- );
+ const car = await client.car.create({
+ data: { ...carData, id: productId },
+ });
- // Salvar referência da imagem no banco de dados
+ // 2. Persistir somente referências já preparadas fora da transação
+ if (preparedImages.length > 0) {
+ for (const image of preparedImages) {
await client.car_image.create({
data: {
car_id: car.id,
- image_url: imageKey,
+ image_url: image.image_url,
is_primary: image.is_primary,
product_type: 'CAR',
},
@@ -70,7 +88,13 @@ export class CarsService {
include: { images: true },
});
} catch (error) {
- if (error instanceof Prisma.PrismaClientKnownRequestError) {
+ if (ownsPreparedImages) {
+ await this.cleanupPreparedImages(preparedImages);
+ }
+ if (
+ error instanceof HttpException ||
+ error instanceof Prisma.PrismaClientKnownRequestError
+ ) {
throw error;
}
throw new Error(`Erro ao criar carro: ${error.message}`);
@@ -218,19 +242,23 @@ export class CarsService {
id: string,
updateCarDto: UpdateCarDto,
client: PrismaService | Prisma.TransactionClient = this.prismaService,
+ preparedWrite?: { images: PreparedProductImage[] },
) {
const { images, ...carData } = updateCarDto;
-
- await updateProductWithMonetaryLock(client, {
- productType: ProductType.CAR,
- productId: id,
- nextValue: updateCarDto.valor,
- nextCurrency: updateCarDto.currency,
- data: carData,
- notFoundMessage: 'Car not found',
- });
+ const ownsPreparedImages = !preparedWrite;
+ const preparedImages =
+ preparedWrite?.images ?? (await this.prepareProductImages(id, images));
try {
+ await updateProductWithMonetaryLock(client, {
+ productType: ProductType.CAR,
+ productId: id,
+ nextValue: updateCarDto.valor,
+ nextCurrency: updateCarDto.currency,
+ data: carData,
+ notFoundMessage: 'Car not found',
+ });
+
// 1. Se houver novas imagens, processar
if (images && images.length > 0) {
// Remover imagens antigas
@@ -238,22 +266,12 @@ export class CarsService {
where: { car_id: id },
});
- // Adicionar novas imagens
- for (let i = 0; i < images.length; i++) {
- const image = images[i];
-
- const timestamp = Date.now();
- const key = `cars/${id}/${timestamp}-${i}.jpg`;
-
- const imageKey = await this.s3Service.uploadBase64Image(
- image.data,
- key,
- );
-
+ // Adicionar referências das imagens já preparadas
+ for (const image of preparedImages) {
await client.car_image.create({
data: {
car_id: id,
- image_url: imageKey,
+ image_url: image.image_url,
is_primary: image.is_primary,
product_type: 'CAR',
},
@@ -267,7 +285,13 @@ export class CarsService {
include: { images: true },
});
} catch (error) {
- if (error instanceof Prisma.PrismaClientKnownRequestError) {
+ if (ownsPreparedImages) {
+ await this.cleanupPreparedImages(preparedImages);
+ }
+ if (
+ error instanceof HttpException ||
+ error instanceof Prisma.PrismaClientKnownRequestError
+ ) {
throw error;
}
throw new Error(`Erro ao atualizar carro: ${error.message}`);
diff --git a/backend/src/features/drive-import/drive-import.service.spec.ts b/backend/src/features/drive-import/drive-import.service.spec.ts
new file mode 100644
index 0000000..8ab6a60
--- /dev/null
+++ b/backend/src/features/drive-import/drive-import.service.spec.ts
@@ -0,0 +1,114 @@
+import { ProductType } from '@prisma/client';
+import { DriveImportService } from './drive-import.service';
+
+describe('DriveImportService fencing', () => {
+ it('propaga perda do lease depois do upload e não persiste a imagem', async () => {
+ const prisma = {
+ car_image: {
+ findMany: jest.fn().mockResolvedValue([]),
+ deleteMany: jest.fn().mockResolvedValue({ count: 0 }),
+ create: jest.fn().mockResolvedValue({}),
+ },
+ } as any;
+ const s3 = {
+ uploadBuffer: jest.fn().mockResolvedValue('drive-import/car/key.jpg'),
+ deleteObjects: jest.fn().mockResolvedValue(undefined),
+ } as any;
+ const config = {
+ get: jest.fn().mockReturnValue('drive-api-key'),
+ } as any;
+ const service = new DriveImportService(prisma, s3, config);
+ jest.spyOn(service as any, 'listPublicFolderImages').mockResolvedValue([
+ { id: 'file-1', name: 'photo.jpg', mimeType: 'image/jpeg' },
+ ]);
+ jest.spyOn(service as any, 'downloadDriveFile').mockResolvedValue({
+ buffer: Buffer.from('image'),
+ contentType: 'image/jpeg',
+ });
+ jest.spyOn(service as any, 'sleepBetweenDownloads').mockResolvedValue(undefined);
+ let checks = 0;
+ const assertActive = jest.fn(async () => {
+ checks += 1;
+ if (checks >= 5) throw new Error('lease perdido');
+ });
+
+ await expect(
+ service.importImagesForProductFromFolder({
+ folder_url: 'valid-folder-id',
+ product_type: ProductType.CAR,
+ product_id: '11111111-1111-4111-8111-111111111111',
+ assert_active: assertActive,
+ import_job_fence: {
+ job_id: '22222222-2222-4222-8222-222222222222',
+ lease_token: '33333333-3333-4333-8333-333333333333',
+ },
+ }),
+ ).rejects.toThrow('lease perdido');
+
+ expect(s3.uploadBuffer).toHaveBeenCalledTimes(1);
+ expect(prisma.car_image.create).not.toHaveBeenCalled();
+ expect(s3.deleteObjects).toHaveBeenCalledWith([
+ 'drive-import/car/key.jpg',
+ ]);
+ expect(assertActive).toHaveBeenCalledTimes(6);
+ expect(s3.uploadBuffer.mock.calls[0][1]).toContain(
+ '/33333333-3333-4333-8333-333333333333/',
+ );
+ });
+
+ it('troca referências em transação fenced antes de apagar chaves antigas', async () => {
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ id: 'job-1' }]),
+ car_image: {
+ findMany: jest.fn().mockResolvedValue([{ image_url: 'old-key.jpg' }]),
+ deleteMany: jest.fn().mockResolvedValue({ count: 1 }),
+ createMany: jest.fn().mockResolvedValue({ count: 1 }),
+ },
+ } as any;
+ const prisma = {
+ $transaction: jest.fn(async (callback) => callback(tx)),
+ } as any;
+ const s3 = {
+ uploadBuffer: jest.fn().mockResolvedValue('new-versioned-key.jpg'),
+ deleteObjects: jest.fn().mockResolvedValue(undefined),
+ } as any;
+ const service = new DriveImportService(
+ prisma,
+ s3,
+ { get: jest.fn().mockReturnValue('drive-api-key') } as any,
+ );
+ jest.spyOn(service as any, 'listPublicFolderImages').mockResolvedValue([
+ { id: 'file-1', name: 'photo.jpg', mimeType: 'image/jpeg' },
+ ]);
+ jest.spyOn(service as any, 'downloadDriveFile').mockResolvedValue({
+ buffer: Buffer.from('image'),
+ contentType: 'image/jpeg',
+ });
+ jest.spyOn(service as any, 'sleepBetweenDownloads').mockResolvedValue(undefined);
+ const assertActive = jest.fn().mockResolvedValue(undefined);
+
+ await expect(
+ service.importImagesForProductFromFolder({
+ folder_url: 'valid-folder-id',
+ product_type: ProductType.CAR,
+ product_id: '11111111-1111-4111-8111-111111111111',
+ assert_active: assertActive,
+ import_job_fence: {
+ job_id: '22222222-2222-4222-8222-222222222222',
+ lease_token: '33333333-3333-4333-8333-333333333333',
+ },
+ }),
+ ).resolves.toMatchObject({ uploaded: 1, failed: 0 });
+
+ expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
+ expect(tx.car_image.createMany).toHaveBeenCalledWith({
+ data: [
+ expect.objectContaining({
+ image_url: 'new-versioned-key.jpg',
+ is_primary: true,
+ }),
+ ],
+ });
+ expect(s3.deleteObjects).toHaveBeenLastCalledWith(['old-key.jpg']);
+ });
+});
diff --git a/backend/src/features/drive-import/drive-import.service.ts b/backend/src/features/drive-import/drive-import.service.ts
index b085634..cb9a115 100644
--- a/backend/src/features/drive-import/drive-import.service.ts
+++ b/backend/src/features/drive-import/drive-import.service.ts
@@ -5,8 +5,13 @@ import {
Logger,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
-import { ProductType, UserRole } from '@prisma/client';
+import {
+ ProductImportJobStatus,
+ ProductType,
+ UserRole,
+} from '@prisma/client';
import axios from 'axios';
+import { randomUUID } from 'node:crypto';
import { PrismaService } from 'src/prisma/prisma.service';
import { S3Service } from 'src/aws/s3.service';
import { ImportDriveImagesDto } from './dto/import-drive-images.dto';
@@ -58,6 +63,8 @@ export class DriveImportService {
product_type: ProductType;
product_id: string;
max_files?: number;
+ assert_active?: () => Promise;
+ import_job_fence?: { job_id: string; lease_token: string };
}): Promise {
const apiKey = this.configService.get('GOOGLE_DRIVE_API_KEY');
@@ -69,13 +76,17 @@ export class DriveImportService {
const folderId = this.extractFolderId(params.folder_url);
const maxFiles = params.max_files ?? 500;
+ const assertActive = params.assert_active ?? (async () => {});
let files: DriveFile[];
const warnings: string[] = [];
try {
+ await assertActive();
files = await this.listPublicFolderImages(folderId, apiKey, maxFiles);
+ await assertActive();
} catch (listError: any) {
+ await assertActive();
return {
folder_id: folderId,
found: 0,
@@ -99,47 +110,79 @@ export class DriveImportService {
};
}
- // Substituir imagens existentes: apagar do S3 e do banco antes de importar
- await this.deleteAllProductImages(params.product_type, params.product_id);
-
- let hasPrimary: boolean = false;
let uploaded = 0;
const skipped = 0;
let failed = 0;
+ const preparedImages: Array<{ key: string; isPrimary: boolean }> = [];
+ const operationNamespace =
+ params.import_job_fence?.lease_token ?? randomUUID();
+ let imagesCommitted = false;
- for (const file of files) {
- try {
- const downloaded = await this.downloadDriveFile(file.id, apiKey);
- const objectKey = this.buildS3ObjectKey(
- params.product_type,
- params.product_id,
- file.name,
- );
+ try {
+ for (const file of files) {
+ await assertActive();
+ let uploadedKey: string | null = null;
+ try {
+ const downloaded = await this.downloadDriveFile(file.id, apiKey);
+ await assertActive();
+ const objectKey = this.buildS3ObjectKey(
+ params.product_type,
+ params.product_id,
+ file.name,
+ operationNamespace,
+ );
- const s3Key = await this.s3Service.uploadBuffer(
- downloaded.buffer,
- objectKey,
- downloaded.contentType,
- );
+ uploadedKey = await this.s3Service.uploadBuffer(
+ downloaded.buffer,
+ objectKey,
+ downloaded.contentType,
+ );
+ await assertActive();
+ preparedImages.push({
+ key: uploadedKey,
+ isPrimary: preparedImages.length === 0,
+ });
+ uploaded += 1;
+ } catch (error) {
+ if (uploadedKey) {
+ await this.s3Service.deleteObjects([uploadedKey]);
+ }
+ // Se o fencing foi perdido, a nova verificação propaga o erro em
+ // vez de convertê-lo em um simples aviso de imagem.
+ await assertActive();
+ failed += 1;
+ warnings.push(
+ `Falha ao importar ${file.name}: ${error?.message || 'erro desconhecido'}`,
+ );
+ }
- const isPrimary: boolean = !hasPrimary;
- await this.createImageRecord({
- productType: params.product_type,
- productId: params.product_id,
- imageKey: s3Key,
- isPrimary,
- });
+ await this.sleepBetweenDownloads();
+ await assertActive();
+ }
- hasPrimary = hasPrimary || isPrimary;
- uploaded += 1;
- } catch (error) {
- failed += 1;
- warnings.push(
- `Falha ao importar ${file.name}: ${error?.message || 'erro desconhecido'}`,
+ if (preparedImages.length > 0) {
+ await assertActive();
+ const oldKeys = await this.replaceProductImages(
+ params.product_type,
+ params.product_id,
+ preparedImages,
+ params.import_job_fence,
);
+ imagesCommitted = true;
+ if (oldKeys.length > 0) {
+ // Copy-on-write: só remove as chaves antigas depois que o swap
+ // fenced das referências foi commitado. Chaves novas incluem o
+ // lease, portanto um worker antigo nunca apaga as do atual.
+ await this.s3Service.deleteObjects(oldKeys);
+ }
}
-
- await this.sleepBetweenDownloads();
+ } catch (error) {
+ if (!imagesCommitted && preparedImages.length > 0) {
+ await this.s3Service.deleteObjects(
+ preparedImages.map((image) => image.key),
+ );
+ }
+ throw error;
}
return {
@@ -604,42 +647,75 @@ export class DriveImportService {
return Boolean(record);
}
- private async deleteAllProductImages(
+ private async replaceProductImages(
type: ProductType,
productId: string,
- ): Promise {
- let keys: string[] = [];
+ images: Array<{ key: string; isPrimary: boolean }>,
+ fence?: { job_id: string; lease_token: string },
+ ): Promise {
+ return this.prisma.$transaction(async (tx) => {
+ if (fence) {
+ const owned = await tx.$queryRaw>`
+ SELECT "id"
+ FROM "ProductImportJob"
+ WHERE "id" = ${fence.job_id}::uuid
+ AND "processing_lease_token" = ${fence.lease_token}::uuid
+ AND "status" = ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus"
+ AND "processing_lease_expires_at" > NOW()
+ FOR UPDATE
+ `;
+ if (owned.length !== 1) {
+ throw new Error('Lease do job de importação perdido durante o swap de imagens.');
+ }
+ }
- if (type === ProductType.CAR) {
- const records = await this.prisma.car_image.findMany({
- where: { car_id: productId },
- select: { image_url: true },
- });
- keys = records.map((r) => r.image_url);
- await this.prisma.car_image.deleteMany({ where: { car_id: productId } });
- } else if (type === ProductType.BOAT) {
- const records = await this.prisma.boat_image.findMany({
- where: { boat_id: productId },
- select: { image_url: true },
- });
- keys = records.map((r) => r.image_url);
- await this.prisma.boat_image.deleteMany({
- where: { boat_id: productId },
- });
- } else {
- const records = await this.prisma.aircraft_image.findMany({
+ if (type === ProductType.CAR) {
+ const old = await tx.car_image.findMany({
+ where: { car_id: productId },
+ select: { image_url: true },
+ });
+ await tx.car_image.deleteMany({ where: { car_id: productId } });
+ await tx.car_image.createMany({
+ data: images.map((image) => ({
+ car_id: productId,
+ image_url: image.key,
+ is_primary: image.isPrimary,
+ product_type: ProductType.CAR,
+ })),
+ });
+ return old.map((image) => image.image_url);
+ }
+ if (type === ProductType.BOAT) {
+ const old = await tx.boat_image.findMany({
+ where: { boat_id: productId },
+ select: { image_url: true },
+ });
+ await tx.boat_image.deleteMany({ where: { boat_id: productId } });
+ await tx.boat_image.createMany({
+ data: images.map((image) => ({
+ boat_id: productId,
+ image_url: image.key,
+ is_primary: image.isPrimary,
+ product_type: ProductType.BOAT,
+ })),
+ });
+ return old.map((image) => image.image_url);
+ }
+ const old = await tx.aircraft_image.findMany({
where: { aircraft_id: productId },
select: { image_url: true },
});
- keys = records.map((r) => r.image_url);
- await this.prisma.aircraft_image.deleteMany({
- where: { aircraft_id: productId },
+ await tx.aircraft_image.deleteMany({ where: { aircraft_id: productId } });
+ await tx.aircraft_image.createMany({
+ data: images.map((image) => ({
+ aircraft_id: productId,
+ image_url: image.key,
+ is_primary: image.isPrimary,
+ product_type: ProductType.AIRCRAFT,
+ })),
});
- }
-
- if (keys.length > 0) {
- await this.s3Service.deleteObjects(keys);
- }
+ return old.map((image) => image.image_url);
+ });
}
private parseProductFromFileName(fileName: string): {
@@ -696,8 +772,13 @@ export class DriveImportService {
type: ProductType,
productId: string,
originalName: string,
+ operationNamespace?: string,
): string {
const safeFileName = this.sanitizeS3FileName(originalName);
+ if (operationNamespace) {
+ const safeNamespace = this.sanitizeS3FileName(operationNamespace);
+ return `drive-import/${type.toLowerCase()}/${productId}/${safeNamespace}/${randomUUID()}-${safeFileName}`;
+ }
return `drive-import/${type.toLowerCase()}/${productId}/${safeFileName}`;
}
diff --git a/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts b/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts
index 0574551..b4eae2d 100644
--- a/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts
+++ b/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts
@@ -2,6 +2,49 @@ import { ProductImportJobsService } from './product-import-jobs.service';
import { Prisma, ProductCurrency, ProductType } from '@prisma/client';
describe('ProductImportJobsService', () => {
+ beforeEach(() => {
+ jest
+ .spyOn(ProductImportJobsService.prototype as any, 'claimJob')
+ .mockResolvedValue('unit-test-lease');
+ jest
+ .spyOn(ProductImportJobsService.prototype as any, 'releaseJobLease')
+ .mockResolvedValue(undefined);
+ jest
+ .spyOn(ProductImportJobsService.prototype as any, 'pauseIneligibleJob')
+ .mockResolvedValue(undefined);
+ jest
+ .spyOn(ProductImportJobsService.prototype as any, 'checkpointProductUpsert')
+ .mockImplementation(function (job: any, _item: any, payload: any) {
+ return (this as any).upsertProductFromRow(
+ job.product_type,
+ payload,
+ job.specialist_id,
+ );
+ });
+ jest
+ .spyOn(ProductImportJobsService.prototype as any, 'finalizeUnsynchronizedJob')
+ .mockImplementation(function (jobId: string, summary: any) {
+ return (this as any).refreshJobCounters(jobId, summary);
+ });
+ jest
+ .spyOn(ProductImportJobsService.prototype as any, 'updateImportItemWithLease')
+ .mockImplementation(function (
+ _jobId: string,
+ _leaseToken: string,
+ itemId: string,
+ data: any,
+ ) {
+ return (this as any).prisma.productImportJobItem.update({
+ where: { id: itemId },
+ data,
+ });
+ });
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
const validCarRow = {
marca: 'Ferrari',
modelo: 'Roma',
@@ -11,6 +54,25 @@ describe('ProductImportJobsService', () => {
ano: '2024',
};
+ it('repete uma transação serializável abortada por P2034', async () => {
+ const transaction = jest
+ .fn()
+ .mockRejectedValueOnce({ code: 'P2034' })
+ .mockImplementationOnce(async (callback: any) => callback({ ok: true }));
+ const service = new ProductImportJobsService(
+ { $transaction: transaction } as any,
+ {} as any,
+ {} as any,
+ );
+ const operation = jest.fn().mockResolvedValue('done');
+
+ await expect(
+ (service as any).runSerializableWithRetry(operation),
+ ).resolves.toBe('done');
+ expect(transaction).toHaveBeenCalledTimes(2);
+ expect(operation).toHaveBeenCalledWith({ ok: true });
+ });
+
it.each([
['identificador', '-', 'Identificador do veículo faltando'],
['marca', ' - ', 'Marca do veículo faltando'],
@@ -113,6 +175,9 @@ describe('ProductImportJobsService', () => {
syncPreviewSnapshot: { candidateIds: [], csvDigest: 'csv-digest' },
specialistIsEligible: true,
});
+ jest
+ .spyOn(service as any, 'assertSynchronizationSnapshotCurrent')
+ .mockResolvedValue(undefined);
const deactivateMissingProducts = jest
.spyOn(service as any, 'deactivateMissingProducts')
.mockResolvedValue(['stale-product']);
@@ -181,32 +246,30 @@ describe('ProductImportJobsService', () => {
syncPreviewSnapshot: { candidateIds: [], csvDigest: 'csv-digest' },
specialistIsEligible: true,
});
+ jest
+ .spyOn(service as any, 'assertSynchronizationSnapshotCurrent')
+ .mockResolvedValue(undefined);
jest.spyOn(service as any, 'upsertProductFromRow').mockResolvedValue({
productId: productB,
action: 'UPDATED',
});
- const deactivateMissingProducts = jest
- .spyOn(service as any, 'deactivateMissingProducts')
- .mockImplementation(async (_type, _specialist, seen: Set) =>
- seen.has(productA) && seen.has(productB) ? [] : [productA],
- );
- const refreshJobCounters = jest
- .spyOn(service as any, 'refreshJobCounters')
+ const finalizeSynchronizedJob = jest
+ .spyOn(service as any, 'finalizeSynchronizedJob')
.mockResolvedValue(undefined);
await (service as any).processJob('job-resume');
- expect(deactivateMissingProducts).toHaveBeenCalledWith(
- ProductType.CAR,
- specialistId,
- new Set([productA, productB]),
+ expect(finalizeSynchronizedJob).toHaveBeenCalledWith(
'job-resume',
- { candidateIds: [], csvDigest: 'csv-digest' },
+ {
+ productType: ProductType.CAR,
+ specialistId,
+ seenProductIds: new Set([productA, productB]),
+ snapshot: { candidateIds: [], csvDigest: 'csv-digest' },
+ },
+ 0,
+ 'unit-test-lease',
);
- expect(refreshJobCounters).toHaveBeenCalledWith('job-resume', {
- deactivatedIds: [],
- reactivatedCount: 0,
- });
});
it('leva o snapshot confirmado para a revalidação transacional antes de desativar', async () => {
@@ -242,21 +305,25 @@ describe('ProductImportJobsService', () => {
syncPreviewSnapshot: snapshot,
specialistIsEligible: true,
});
- const deactivateMissingProducts = jest
- .spyOn(service as any, 'deactivateMissingProducts')
- .mockResolvedValue([]);
jest
- .spyOn(service as any, 'refreshJobCounters')
+ .spyOn(service as any, 'assertSynchronizationSnapshotCurrent')
+ .mockResolvedValue(undefined);
+ const finalizeSynchronizedJob = jest
+ .spyOn(service as any, 'finalizeSynchronizedJob')
.mockResolvedValue(undefined);
await (service as any).processJob('job-snapshot');
- expect(deactivateMissingProducts).toHaveBeenCalledWith(
- ProductType.CAR,
- '00000000-0000-4000-8000-000000000001',
- new Set(['11111111-1111-4111-8111-111111111111']),
+ expect(finalizeSynchronizedJob).toHaveBeenCalledWith(
'job-snapshot',
- snapshot,
+ {
+ productType: ProductType.CAR,
+ specialistId: '00000000-0000-4000-8000-000000000001',
+ seenProductIds: new Set(['11111111-1111-4111-8111-111111111111']),
+ snapshot,
+ },
+ 0,
+ 'unit-test-lease',
);
});
@@ -374,14 +441,10 @@ describe('ProductImportJobsService', () => {
await (service as any).processJob('job-inactive');
- expect(prisma.productImportJob.update).toHaveBeenCalledTimes(1);
- expect(prisma.productImportJob.update).toHaveBeenCalledWith({
- where: { id: 'job-inactive' },
- data: expect.objectContaining({
- status: 'PENDING',
- error_message: expect.stringContaining('inativo'),
- }),
- });
+ expect((service as any).pauseIneligibleJob).toHaveBeenCalledWith(
+ 'job-inactive',
+ 'unit-test-lease',
+ );
});
it('exige confirmação explícita para sincronizar', async () => {
@@ -415,6 +478,29 @@ describe('ProductImportJobsService', () => {
).rejects.toThrow('confirmação explícita');
});
+ it('rejeita identificadores duplicados no mesmo CSV', async () => {
+ const xlsxImportService = {
+ parseCsv: jest.fn().mockReturnValue({
+ rows: [validCarRow, { ...validCarRow, modelo: 'Duplicado' }],
+ }),
+ validateStructure: jest.fn().mockReturnValue({ valid: true }),
+ } as any;
+ const service = new ProductImportJobsService(
+ {} as any,
+ xlsxImportService,
+ {} as any,
+ );
+
+ await expect(
+ service.previewCsvImport(
+ Buffer.from('csv-duplicado'),
+ ProductType.CAR,
+ '00000000-0000-4000-8000-000000000001',
+ 'SYNCHRONIZE',
+ ),
+ ).rejects.toThrow('identificadores duplicados');
+ });
+
it('exige token da prévia mesmo quando a sincronização foi confirmada', async () => {
const xlsxImportService = {
parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
@@ -509,6 +595,85 @@ describe('ProductImportJobsService', () => {
);
});
+ it('deriva impacto e token da mesma leitura do catálogo', async () => {
+ const specialistId = '00000000-0000-4000-8000-000000000001';
+ const productA = {
+ id: '11111111-1111-4111-8111-111111111111',
+ identificador: validCarRow.identificador,
+ };
+ const productC = {
+ id: '33333333-3333-4333-8333-333333333333',
+ identificador: 'NEW-C',
+ };
+ const catalogReads = [[productA], [productA, productC], [productA, productC]];
+ const findMany = jest
+ .fn()
+ .mockImplementation(async () =>
+ catalogReads.shift() ?? [productA, productC],
+ );
+ const xlsxImportService = {
+ parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
+ validateStructure: jest.fn().mockReturnValue({ valid: true }),
+ } as any;
+ const prisma = {
+ car: {
+ findMany,
+ },
+ $transaction: jest.fn(async (callback) =>
+ callback({
+ car: { findMany },
+ productImportJob: {
+ create: jest.fn().mockResolvedValue({
+ id: 'job-unsafe-preview',
+ status: 'PENDING',
+ total_items: 1,
+ product_type: ProductType.CAR,
+ }),
+ },
+ $executeRaw: jest.fn(),
+ }),
+ ),
+ } as any;
+ const service = new ProductImportJobsService(
+ prisma,
+ xlsxImportService,
+ {} as any,
+ );
+ jest.spyOn(service as any, 'scheduleJob').mockImplementation(() => {});
+ const file = Buffer.from('preview-race-csv');
+
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+
+ expect(preview.impact.deactivationCandidates).toBe(0);
+ await expect(
+ service.createJobFromCsv(
+ file,
+ { id: 'admin-1', role: 'ADMIN' } as any,
+ ProductType.CAR,
+ {
+ mode: 'SYNCHRONIZE',
+ confirmSynchronize: true,
+ synchronizePreviewToken: preview.synchronizePreviewToken,
+ context: {
+ actorId: 'admin-1',
+ actorRole: 'ADMIN',
+ specialistId,
+ specialist: {} as any,
+ delegated: true,
+ },
+ },
+ ),
+ ).rejects.toMatchObject({
+ response: expect.objectContaining({ code: 'SYNCHRONIZE_PREVIEW_STALE' }),
+ });
+ expect(prisma.$transaction).toHaveBeenCalledTimes(1);
+ });
+
it('rejeita confirmação quando os candidatos mudam antes do POST', async () => {
const specialistId = '00000000-0000-4000-8000-000000000001';
const activeProducts = [
@@ -519,12 +684,14 @@ describe('ProductImportJobsService', () => {
parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
validateStructure: jest.fn().mockReturnValue({ valid: true }),
} as any;
+ const findMany = jest.fn().mockImplementation(async () => [...activeProducts]);
const prisma = {
car: {
- findMany: jest.fn().mockImplementation(async () => [...activeProducts]),
+ findMany,
},
$transaction: jest.fn(async (callback) =>
callback({
+ car: { findMany },
productImportJob: {
create: jest.fn().mockResolvedValue({
id: 'job-stale',
@@ -576,7 +743,7 @@ describe('ProductImportJobsService', () => {
).rejects.toMatchObject({
response: expect.objectContaining({ code: 'SYNCHRONIZE_PREVIEW_STALE' }),
});
- expect(prisma.$transaction).not.toHaveBeenCalled();
+ expect(prisma.$transaction).toHaveBeenCalledTimes(1);
});
it('relata a linha não importada com erro em linguagem natural', () => {
diff --git a/backend/src/features/product-import-jobs/product-import-jobs.service.ts b/backend/src/features/product-import-jobs/product-import-jobs.service.ts
index 4aa1238..9c78f0f 100644
--- a/backend/src/features/product-import-jobs/product-import-jobs.service.ts
+++ b/backend/src/features/product-import-jobs/product-import-jobs.service.ts
@@ -40,12 +40,16 @@ import { CreateBoatDto } from '../boats/dto/create-boat.dto';
import { CreateAircraftDto } from '../aircrafts/dto/create-aircraft.dto';
import { DriveImportService } from '../drive-import/drive-import.service';
import {
- acquireProductMonetaryLock,
updateProductWithMonetaryLock,
} from '../products/product-monetary-lock';
import { ActorContext } from 'src/shared/actor-context/actor-context.service';
import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service';
-import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
+import {
+ createHash,
+ createHmac,
+ randomUUID,
+ timingSafeEqual,
+} from 'node:crypto';
export type ProductImportMode = 'ADDITIVE' | 'SYNCHRONIZE';
@@ -57,26 +61,72 @@ export type ProductImportOptions = {
};
type SynchronizePreviewClaims = {
- version: 1;
+ version: 2;
csvDigest: string;
specialistId: string;
productType: ProductType;
mode: 'SYNCHRONIZE';
candidateDigest: string;
+ catalogDigest: string;
expiresAt: number;
};
+type CatalogProductSnapshot = {
+ id: string;
+ identificador: string;
+ isActive: boolean;
+ updatedAt: string;
+ rowVersion: string;
+};
+
type SynchronizePreviewSnapshot = {
candidateIds: string[];
csvDigest: string;
+ catalogDigest: string;
+ catalogProducts: CatalogProductSnapshot[];
+};
+
+type ImportImpact = {
+ incomingItems: number;
+ activeItemsBefore: number;
+ matchingItems: number;
+ newOrReactivatedItems: number;
+ deactivationCandidates: number;
+};
+
+type SynchronizationCatalogSnapshot = {
+ candidateIds: string[];
+ catalogDigest: string;
+ catalogProducts: CatalogProductSnapshot[];
+ impact: ImportImpact;
};
type UpsertResult = {
productId: string;
action: 'CREATED' | 'UPDATED';
reactivated?: boolean;
+ updatedAt?: string;
};
+type ProductImportEffect = {
+ productId: string;
+ action: 'CREATED' | 'UPDATED';
+ rowVersion: string;
+ updatedAt?: string;
+ reactivated?: boolean;
+};
+
+type ImportItemPayload = ImportParsedRow & {
+ __productImportEffect?: ProductImportEffect;
+};
+
+class ProductImportJobLeaseLostError extends Error {
+ constructor() {
+ super('Lease do job de importação perdido para outro worker.');
+ this.name = 'ProductImportJobLeaseLostError';
+ }
+}
+
const REQUIRED_PRODUCT_FIELDS = [
{ key: 'identificador', label: 'Identificador do veículo' },
{ key: 'marca', label: 'Marca do veículo' },
@@ -90,6 +140,7 @@ const REQUIRED_PRODUCT_FIELDS = [
export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(ProductImportJobsService.name);
private readonly runningJobs = new Set();
+ private readonly lostJobLeases = new Set();
private recoveryTimer?: NodeJS.Timeout;
constructor(
@@ -108,6 +159,33 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
);
}
+ private isSerializationFailure(error: unknown): boolean {
+ return (
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ error.code === 'P2034'
+ );
+ }
+
+ private async runSerializableWithRetry(
+ operation: (tx: Prisma.TransactionClient) => Promise,
+ maxAttempts = 3,
+ ): Promise {
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
+ try {
+ return await this.prisma.$transaction(operation, {
+ isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
+ });
+ } catch (error) {
+ if (!this.isSerializationFailure(error) || attempt === maxAttempts) {
+ throw error;
+ }
+ }
+ }
+ throw new Error('Unreachable serializable transaction retry state');
+ }
+
onModuleInit() {
this.recoverPendingJobs().catch((error) => {
this.logger.error('Falha ao recuperar jobs pendentes', error);
@@ -171,27 +249,43 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
}
const normalizedRows = rows.map((row) => this.normalizeProductRow(row));
+ this.validateUniqueIdentifiers(normalizedRows);
const specialistId = options.context?.specialistId ?? user.id;
- const synchronizeSnapshot =
- mode === 'SYNCHRONIZE'
- ? await this.validateSynchronizePreviewToken(
- options.synchronizePreviewToken!,
- fileBuffer,
+ let creationResult;
+ try {
+ creationResult = await this.runSerializableWithRetry(async (tx) => {
+ if (mode === 'SYNCHRONIZE') {
+ await this.lockProductCatalogForSnapshot(tx, productType);
+ }
+ const validatedSynchronization =
+ mode === 'SYNCHRONIZE'
+ ? await this.validateSynchronizePreviewToken(
+ options.synchronizePreviewToken!,
+ fileBuffer,
+ productType,
+ specialistId,
+ normalizedRows,
+ tx,
+ )
+ : null;
+ const synchronizeSnapshot: SynchronizePreviewSnapshot | null =
+ validatedSynchronization
+ ? {
+ candidateIds: validatedSynchronization.candidateIds,
+ csvDigest: validatedSynchronization.csvDigest,
+ catalogDigest: validatedSynchronization.catalogDigest,
+ catalogProducts: validatedSynchronization.catalogProducts,
+ }
+ : null;
+ const impact =
+ validatedSynchronization?.impact ??
+ (await this.estimateImportImpact(
productType,
specialistId,
normalizedRows,
- )
- : null;
- const impact = await this.estimateImportImpact(
- productType,
- specialistId,
- normalizedRows,
- mode,
- );
-
- let createdJob;
- try {
- createdJob = await this.prisma.$transaction(async (tx) => {
+ mode,
+ tx,
+ ));
const job = await tx.productImportJob.create({
data: {
product_type: productType,
@@ -235,7 +329,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
tx,
);
}
- return job;
+ return { job, impact };
});
} catch (error) {
if (this.isMissingImportJobsTableError(error)) {
@@ -246,6 +340,8 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
throw error;
}
+ const { job: createdJob, impact } = creationResult;
+
this.scheduleJob(createdJob.id);
return {
@@ -288,19 +384,28 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
});
}
const normalizedRows = rows.map((row) => this.normalizeProductRow(row));
- const impact = await this.estimateImportImpact(
+ this.validateUniqueIdentifiers(normalizedRows);
+ const catalogSnapshot = await this.getSynchronizationCatalogSnapshot(
productType,
specialistId,
normalizedRows,
- mode,
);
+ const impact =
+ mode === 'SYNCHRONIZE'
+ ? catalogSnapshot.impact
+ : this.deriveImportImpact(
+ catalogSnapshot.impact.activeItemsBefore,
+ catalogSnapshot.impact.matchingItems,
+ normalizedRows,
+ 0,
+ );
const synchronizePreviewToken =
mode === 'SYNCHRONIZE'
- ? await this.createSynchronizePreviewToken(
+ ? this.createSynchronizePreviewToken(
fileBuffer,
productType,
specialistId,
- normalizedRows,
+ catalogSnapshot,
)
: undefined;
return {
@@ -313,24 +418,20 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
};
}
- private async createSynchronizePreviewToken(
+ private createSynchronizePreviewToken(
fileBuffer: Buffer,
productType: ProductType,
specialistId: string,
- rows: ImportParsedRow[],
- ): Promise {
- const candidates = await this.getSynchronizationCandidateIds(
- productType,
- specialistId,
- rows,
- );
+ snapshot: SynchronizationCatalogSnapshot,
+ ): string {
const claims: SynchronizePreviewClaims = {
- version: 1,
+ version: 2,
csvDigest: this.sha256(fileBuffer),
specialistId,
productType,
mode: 'SYNCHRONIZE',
- candidateDigest: this.sha256(candidates.join(',')),
+ candidateDigest: this.sha256(snapshot.candidateIds.join(',')),
+ catalogDigest: snapshot.catalogDigest,
expiresAt: Date.now() + 15 * 60 * 1000,
};
const payload = Buffer.from(JSON.stringify(claims)).toString('base64url');
@@ -346,7 +447,14 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
productType: ProductType,
specialistId: string,
rows: ImportParsedRow[],
- ): Promise<{ candidateIds: string[]; csvDigest: string }> {
+ client: PrismaService | Prisma.TransactionClient = this.prisma,
+ ): Promise<{
+ candidateIds: string[];
+ csvDigest: string;
+ catalogDigest: string;
+ catalogProducts: CatalogProductSnapshot[];
+ impact: ImportImpact;
+ }> {
try {
const [payload, providedSignature, extra] = token.split('.');
if (!payload || !providedSignature || extra) {
@@ -369,24 +477,34 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
const claims = JSON.parse(
Buffer.from(payload, 'base64url').toString('utf8'),
) as SynchronizePreviewClaims;
- const candidateIds = await this.getSynchronizationCandidateIds(
+ const catalogSnapshot = await this.getSynchronizationCatalogSnapshot(
productType,
specialistId,
rows,
+ client,
);
+ const { candidateIds, catalogDigest, catalogProducts, impact } =
+ catalogSnapshot;
const csvDigest = this.sha256(fileBuffer);
const scopeMatches =
- claims.version === 1 &&
+ claims.version === 2 &&
claims.mode === 'SYNCHRONIZE' &&
claims.productType === productType &&
claims.specialistId === specialistId &&
claims.csvDigest === csvDigest &&
claims.candidateDigest === this.sha256(candidateIds.join(',')) &&
+ claims.catalogDigest === catalogDigest &&
claims.expiresAt >= Date.now();
if (!scopeMatches) {
throw new Error('escopo ou snapshot divergente');
}
- return { candidateIds, csvDigest };
+ return {
+ candidateIds,
+ csvDigest,
+ catalogDigest,
+ catalogProducts,
+ impact,
+ };
} catch {
throw new ConflictException({
code: 'SYNCHRONIZE_PREVIEW_STALE',
@@ -396,28 +514,58 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
}
}
- private async getSynchronizationCandidateIds(
+ private async getSynchronizationCatalogSnapshot(
productType: ProductType,
specialistId: string,
rows: ImportParsedRow[],
- ): Promise {
+ client: PrismaService | Prisma.TransactionClient = this.prisma,
+ ): Promise {
const incomingIdentifiers = new Set(
rows.map((row) => row.identificador?.trim()).filter(Boolean),
);
- const activeProducts = await this.getActiveProductsByType(
+ const catalogProducts = await this.getCatalogProductsByType(
productType,
specialistId,
+ client,
);
- return activeProducts
+ const activeProducts = catalogProducts.filter((product) => product.isActive);
+ const matchingItems = activeProducts.filter((product) =>
+ incomingIdentifiers.has(product.identificador),
+ ).length;
+ const candidateIds = activeProducts
.filter((product) => !incomingIdentifiers.has(product.identificador))
.map((product) => product.id)
.sort();
+ return {
+ candidateIds,
+ catalogDigest: this.catalogDigest(catalogProducts),
+ catalogProducts,
+ impact: this.deriveImportImpact(
+ activeProducts.length,
+ matchingItems,
+ rows,
+ candidateIds.length,
+ ),
+ };
}
private sha256(value: Buffer | string): string {
return createHash('sha256').update(value).digest('hex');
}
+ private catalogDigest(products: CatalogProductSnapshot[]): string {
+ const canonical = [...products].sort((left, right) =>
+ left.id.localeCompare(right.id),
+ ).map((product) => [
+ product.id,
+ product.identificador,
+ product.isActive,
+ product.updatedAt,
+ product.rowVersion,
+ ]);
+ return this.sha256(JSON.stringify(canonical));
+ }
+
private getPreviewSecret(): string {
const secret =
process.env.PRODUCT_IMPORT_PREVIEW_SECRET ??
@@ -489,6 +637,12 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
: [],
reactivatedCount: job.reactivated_items,
});
+ if (
+ job.status === ProductImportJobStatus.COMPLETED_WITH_ERRORS &&
+ job.error_message
+ ) {
+ response.message = job.error_message;
+ }
return {
jobId: job.id,
@@ -562,6 +716,165 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
}
private async processJob(jobId: string) {
+ const leaseToken = await this.claimJob(jobId);
+ if (!leaseToken) return;
+ const leaseKey = this.jobLeaseKey(jobId, leaseToken);
+ const heartbeat = setInterval(() => {
+ this.renewJobLease(jobId, leaseToken)
+ .then((renewed) => {
+ if (!renewed) this.lostJobLeases.add(leaseKey);
+ })
+ .catch((error) => {
+ // Falha de transporte deixa a posse desconhecida; o próximo fence
+ // consulta o PostgreSQL. Somente UPDATE 0 prova perda definitiva.
+ this.logger.error(`Falha ao renovar lease do job ${jobId}`, error);
+ });
+ }, 15000);
+ heartbeat.unref?.();
+ try {
+ await this.processClaimedJob(jobId, leaseToken);
+ } finally {
+ clearInterval(heartbeat);
+ await this.releaseJobLease(jobId, leaseToken);
+ this.lostJobLeases.delete(leaseKey);
+ }
+ }
+
+ private jobLeaseKey(jobId: string, leaseToken: string): string {
+ return `${jobId}:${leaseToken}`;
+ }
+
+ private throwIfJobLeaseLost(jobId: string, leaseToken: string): void {
+ if (this.lostJobLeases.has(this.jobLeaseKey(jobId, leaseToken))) {
+ throw new ProductImportJobLeaseLostError();
+ }
+ }
+
+ private async claimJob(jobId: string): Promise {
+ const leaseToken = randomUUID();
+ const claimed = await this.prisma.$queryRaw>`
+ UPDATE "ProductImportJob"
+ SET "status" = ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus",
+ "started_at" = COALESCE("started_at", NOW()),
+ "error_message" = NULL,
+ "processing_lease_token" = ${leaseToken}::uuid,
+ "processing_lease_expires_at" = NOW() + INTERVAL '5 minutes',
+ "updated_at" = NOW()
+ WHERE "id" = ${jobId}::uuid
+ AND "status" IN (
+ ${ProductImportJobStatus.PENDING}::"ProductImportJobStatus",
+ ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus"
+ )
+ AND (
+ "status" = ${ProductImportJobStatus.PENDING}::"ProductImportJobStatus"
+ OR "processing_lease_token" IS NULL
+ OR "processing_lease_expires_at" <= NOW()
+ )
+ RETURNING "id"
+ `;
+ return claimed.length === 1 ? leaseToken : null;
+ }
+
+ private async renewJobLease(
+ jobId: string,
+ leaseToken: string,
+ ): Promise {
+ const updated = await this.prisma.$executeRaw`
+ UPDATE "ProductImportJob"
+ SET "processing_lease_expires_at" = GREATEST(
+ "processing_lease_expires_at",
+ NOW() + INTERVAL '5 minutes'
+ ),
+ "updated_at" = NOW()
+ WHERE "id" = ${jobId}::uuid
+ AND "processing_lease_token" = ${leaseToken}::uuid
+ AND "status" = ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus"
+ AND "processing_lease_expires_at" > NOW()
+ `;
+ return updated === 1;
+ }
+
+ private async extendJobLeaseForExternalEffect(
+ jobId: string,
+ leaseToken: string,
+ ): Promise {
+ this.throwIfJobLeaseLost(jobId, leaseToken);
+ const updated = await this.prisma.$executeRaw`
+ UPDATE "ProductImportJob"
+ SET "processing_lease_expires_at" = GREATEST(
+ "processing_lease_expires_at",
+ NOW() + INTERVAL '30 minutes'
+ ),
+ "updated_at" = NOW()
+ WHERE "id" = ${jobId}::uuid
+ AND "processing_lease_token" = ${leaseToken}::uuid
+ AND "status" = ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus"
+ AND "processing_lease_expires_at" > NOW()
+ `;
+ if (updated !== 1) {
+ this.lostJobLeases.add(this.jobLeaseKey(jobId, leaseToken));
+ throw new ProductImportJobLeaseLostError();
+ }
+ }
+
+ private async assertJobLeaseOwned(
+ tx: Prisma.TransactionClient,
+ jobId: string,
+ leaseToken: string,
+ ): Promise {
+ this.throwIfJobLeaseLost(jobId, leaseToken);
+ const owned = await tx.$queryRaw>`
+ SELECT "id"
+ FROM "ProductImportJob"
+ WHERE "id" = ${jobId}::uuid
+ AND "processing_lease_token" = ${leaseToken}::uuid
+ AND "status" = ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus"
+ AND "processing_lease_expires_at" > NOW()
+ FOR UPDATE
+ `;
+ if (owned.length !== 1) {
+ this.lostJobLeases.add(this.jobLeaseKey(jobId, leaseToken));
+ throw new ProductImportJobLeaseLostError();
+ }
+ }
+
+ private isJobLeaseLost(error: unknown): boolean {
+ return error instanceof ProductImportJobLeaseLostError;
+ }
+
+ private async releaseJobLease(
+ jobId: string,
+ leaseToken: string,
+ ): Promise {
+ await this.prisma.$executeRaw`
+ UPDATE "ProductImportJob"
+ SET "processing_lease_token" = NULL,
+ "processing_lease_expires_at" = NULL,
+ "updated_at" = NOW()
+ WHERE "id" = ${jobId}::uuid
+ AND "processing_lease_token" = ${leaseToken}::uuid
+ AND "processing_lease_expires_at" > NOW()
+ `;
+ }
+
+ private async pauseIneligibleJob(
+ jobId: string,
+ leaseToken: string,
+ ): Promise {
+ await this.prisma.$executeRaw`
+ UPDATE "ProductImportJob"
+ SET "status" = ${ProductImportJobStatus.PENDING}::"ProductImportJobStatus",
+ "error_message" = 'Job pausado: especialista-alvo inativo ou incompatível com o tipo do produto.',
+ "processing_lease_token" = NULL,
+ "processing_lease_expires_at" = NULL,
+ "updated_at" = NOW()
+ WHERE "id" = ${jobId}::uuid
+ AND "processing_lease_token" = ${leaseToken}::uuid
+ AND "processing_lease_expires_at" > NOW()
+ `;
+ }
+
+ private async processClaimedJob(jobId: string, leaseToken: string) {
const job = await this.prisma.productImportJob.findUnique({
where: { id: jobId },
include: {
@@ -585,26 +898,42 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
const executionContext = await this.getJobExecutionContext(job);
if (!executionContext.specialistIsEligible) {
- await this.prisma.productImportJob.update({
- where: { id: jobId },
- data: {
- status: ProductImportJobStatus.PENDING,
- error_message:
- 'Job pausado: especialista-alvo inativo ou incompatível com o tipo do produto.',
- },
- });
+ await this.pauseIneligibleJob(jobId, leaseToken);
return;
}
- await this.prisma.productImportJob.update({
- where: { id: jobId },
- data: {
- status: ProductImportJobStatus.PROCESSING,
- started_at: job.started_at ?? new Date(),
- error_message: null,
- },
- });
+ if (
+ executionContext.mode === 'SYNCHRONIZE' &&
+ executionContext.syncConfirmed
+ ) {
+ try {
+ await this.assertSynchronizationSnapshotCurrent(
+ job,
+ executionContext.syncPreviewSnapshot,
+ );
+ } catch (error) {
+ if (await this.jobHasPersistedEffects(job)) {
+ await this.markSynchronizationPartial(jobId, 0, leaseToken);
+ } else {
+ await this.markJobFailedUnlessTerminal(
+ jobId,
+ error?.message || 'Prévia de sincronização desatualizada',
+ leaseToken,
+ );
+ }
+ return;
+ }
+ }
+ let reactivatedCount = job.items.filter(
+ (item) =>
+ (item.status === ProductImportItemStatus.COMPLETED ||
+ item.status === ProductImportItemStatus.COMPLETED_WITH_WARNINGS) &&
+ Boolean(
+ (item.payload as unknown as ImportItemPayload).__productImportEffect
+ ?.reactivated,
+ ),
+ ).length;
try {
const seenProductIds = new Set(
job.items
@@ -612,17 +941,18 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
(item) =>
(item.status === ProductImportItemStatus.COMPLETED ||
item.status ===
- ProductImportItemStatus.COMPLETED_WITH_WARNINGS) &&
+ ProductImportItemStatus.COMPLETED_WITH_WARNINGS ||
+ item.status === ProductImportItemStatus.PROCESSING) &&
item.product_id,
)
.map((item) => item.product_id as string),
);
- let reactivatedCount = 0;
let hasFailedItems = job.items.some(
(item) => item.status === ProductImportItemStatus.FAILED,
);
for (const item of job.items) {
+ this.throwIfJobLeaseLost(jobId, leaseToken);
if (
item.status !== ProductImportItemStatus.PENDING &&
item.status !== ProductImportItemStatus.PROCESSING
@@ -630,21 +960,21 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
continue;
}
- await this.prisma.productImportJobItem.update({
- where: { id: item.id },
- data: {
- status: ProductImportItemStatus.PROCESSING,
- attempts: { increment: 1 },
- },
- });
-
try {
- const row = item.payload as unknown as ImportParsedRow;
- const upsertResult = await this.upsertProductFromRow(
- job.product_type,
- row,
- job.specialist_id,
- );
+ const payload = item.payload as unknown as ImportItemPayload;
+ const checkpointedEffect = payload.__productImportEffect;
+ const upsertResult =
+ item.status === ProductImportItemStatus.PROCESSING &&
+ checkpointedEffect &&
+ item.product_id === checkpointedEffect.productId &&
+ item.action === checkpointedEffect.action
+ ? checkpointedEffect
+ : await this.checkpointProductUpsert(
+ job,
+ item,
+ payload,
+ leaseToken,
+ );
seenProductIds.add(upsertResult.productId);
if (upsertResult.reactivated) {
reactivatedCount += 1;
@@ -655,11 +985,18 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
if (folderUrl) {
try {
+ await this.extendJobLeaseForExternalEffect(jobId, leaseToken);
const folderImportResult =
await this.driveImportService.importImagesForProductFromFolder({
folder_url: folderUrl,
product_type: job.product_type,
product_id: upsertResult.productId,
+ assert_active: () =>
+ this.extendJobLeaseForExternalEffect(jobId, leaseToken),
+ import_job_fence: {
+ job_id: jobId,
+ lease_token: leaseToken,
+ },
});
if (
@@ -669,36 +1006,33 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
warnings.push(...folderImportResult.warnings);
}
} catch (driveError: any) {
+ if (this.isJobLeaseLost(driveError)) throw driveError;
warnings.push(
`Aviso: falha ao importar imagens da pasta — ${driveError?.message || 'erro desconhecido'}`,
);
}
}
- await this.prisma.productImportJobItem.update({
- where: { id: item.id },
- data: {
- status:
- warnings.length > 0
- ? ProductImportItemStatus.COMPLETED_WITH_WARNINGS
- : ProductImportItemStatus.COMPLETED,
- product_id: upsertResult.productId,
- action: upsertResult.action,
- warnings: warnings.length > 0 ? warnings : undefined,
- error_message: null,
- processed_at: new Date(),
- },
+ await this.updateImportItemWithLease(jobId, leaseToken, item.id, {
+ status:
+ warnings.length > 0
+ ? ProductImportItemStatus.COMPLETED_WITH_WARNINGS
+ : ProductImportItemStatus.COMPLETED,
+ product_id: upsertResult.productId,
+ action: upsertResult.action,
+ warnings: warnings.length > 0 ? warnings : undefined,
+ error_message: null,
+ processed_at: new Date(),
});
} catch (error) {
+ if (this.isJobLeaseLost(error)) throw error;
hasFailedItems = true;
- await this.prisma.productImportJobItem.update({
- where: { id: item.id },
- data: {
- status: ProductImportItemStatus.FAILED,
- error_message:
- error?.message || 'Erro desconhecido no processamento da linha',
- processed_at: new Date(),
- },
+ await this.updateImportItemWithLease(jobId, leaseToken, item.id, {
+ status: ProductImportItemStatus.FAILED,
+ attempts: { increment: 1 },
+ error_message:
+ error?.message || 'Erro desconhecido no processamento da linha',
+ processed_at: new Date(),
});
}
}
@@ -707,31 +1041,317 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
executionContext.mode === 'SYNCHRONIZE' &&
executionContext.syncConfirmed &&
!hasFailedItems;
- const deactivatedIds = shouldSynchronize
- ? await this.deactivateMissingProducts(
- job.product_type,
- job.specialist_id,
+ if (shouldSynchronize) {
+ await this.finalizeSynchronizedJob(
+ jobId,
+ {
+ productType: job.product_type,
+ specialistId: job.specialist_id,
seenProductIds,
- job.id,
- executionContext.syncPreviewSnapshot,
- )
- : [];
+ snapshot: executionContext.syncPreviewSnapshot,
+ },
+ reactivatedCount,
+ leaseToken,
+ );
+ } else {
+ await this.finalizeUnsynchronizedJob(
+ jobId,
+ { deactivatedIds: [], reactivatedCount },
+ leaseToken,
+ );
+ }
+ } catch (error) {
+ if (this.isJobLeaseLost(error)) return;
+ if (
+ executionContext.mode === 'SYNCHRONIZE' &&
+ (this.isSynchronizationPreviewStale(error) ||
+ this.isSerializationFailure(error))
+ ) {
+ await this.markSynchronizationPartial(
+ jobId,
+ reactivatedCount,
+ leaseToken,
+ );
+ return;
+ }
+ await this.markJobFailedUnlessTerminal(
+ jobId,
+ error?.message || 'Erro ao processar job de importação',
+ leaseToken,
+ );
+ }
+ }
- await this.refreshJobCounters(jobId, {
- deactivatedIds,
- reactivatedCount,
+ private async checkpointProductUpsert(
+ job: { id: string; product_type: ProductType; specialist_id: string },
+ item: { id: string },
+ payload: ImportItemPayload,
+ leaseToken: string,
+ ): Promise {
+ return this.prisma.$transaction(async (tx) => {
+ await this.assertJobLeaseOwned(tx, job.id, leaseToken);
+ await tx.productImportJobItem.update({
+ where: { id: item.id },
+ data: {
+ status: ProductImportItemStatus.PROCESSING,
+ attempts: { increment: 1 },
+ },
});
- } catch (error) {
- await this.prisma.productImportJob.update({
+ const result = await this.upsertProductFromRow(
+ job.product_type,
+ payload,
+ job.specialist_id,
+ tx,
+ );
+ const version = await this.getProductVersion(
+ job.product_type,
+ result.productId,
+ tx,
+ );
+ const effect: ProductImportEffect = {
+ productId: result.productId,
+ action: result.action,
+ rowVersion: version.rowVersion,
+ updatedAt: version.updatedAt,
+ ...(result.reactivated !== undefined
+ ? { reactivated: result.reactivated }
+ : {}),
+ };
+ await tx.productImportJobItem.update({
+ where: { id: item.id },
+ data: {
+ status: ProductImportItemStatus.PROCESSING,
+ product_id: effect.productId,
+ action: effect.action,
+ payload: {
+ ...payload,
+ __productImportEffect: effect,
+ },
+ error_message: null,
+ },
+ });
+ return effect;
+ });
+ }
+
+ private async updateImportItemWithLease(
+ jobId: string,
+ leaseToken: string,
+ itemId: string,
+ data: Prisma.ProductImportJobItemUpdateInput,
+ ): Promise {
+ await this.prisma.$transaction(async (tx) => {
+ await this.assertJobLeaseOwned(tx, jobId, leaseToken);
+ await tx.productImportJobItem.update({
+ where: { id: itemId },
+ data,
+ });
+ });
+ }
+
+ private async getProductVersion(
+ productType: ProductType,
+ productId: string,
+ client: Prisma.TransactionClient,
+ ): Promise<{ rowVersion: string; updatedAt: string }> {
+ type VersionRow = { rowVersion: string; updatedAt: Date };
+ const rows =
+ productType === ProductType.CAR
+ ? await client.$queryRaw`
+ SELECT xmin::text AS "rowVersion", "updated_at" AS "updatedAt"
+ FROM "Car" WHERE "id" = ${productId}::uuid
+ `
+ : productType === ProductType.BOAT
+ ? await client.$queryRaw`
+ SELECT xmin::text AS "rowVersion", "updated_at" AS "updatedAt"
+ FROM "Boat" WHERE "id" = ${productId}::uuid
+ `
+ : await client.$queryRaw`
+ SELECT xmin::text AS "rowVersion", "updated_at" AS "updatedAt"
+ FROM "Aircraft" WHERE "id" = ${productId}::uuid
+ `;
+ if (rows.length !== 1) {
+ throw new NotFoundException('Produto importado não encontrado.');
+ }
+ return {
+ rowVersion: rows[0].rowVersion,
+ updatedAt: rows[0].updatedAt.toISOString(),
+ };
+ }
+
+ private async markJobFailedUnlessTerminal(
+ jobId: string,
+ message: string,
+ leaseToken: string,
+ ): Promise {
+ await this.prisma.$executeRaw`
+ UPDATE "ProductImportJob"
+ SET "status" = ${ProductImportJobStatus.FAILED}::"ProductImportJobStatus",
+ "error_message" = ${message},
+ "finished_at" = NOW(),
+ "updated_at" = NOW()
+ WHERE "id" = ${jobId}::uuid
+ AND "status" = ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus"
+ AND "processing_lease_token" = ${leaseToken}::uuid
+ AND "processing_lease_expires_at" > NOW()
+ `;
+ }
+
+ private async jobHasPersistedEffects(job: {
+ id: string;
+ product_type: ProductType;
+ specialist_id: string;
+ items: Array<{
+ status: ProductImportItemStatus;
+ product_id: string | null;
+ payload: unknown;
+ }>;
+ }): Promise {
+ if (
+ job.items.some(
+ (item) =>
+ item.status === ProductImportItemStatus.COMPLETED ||
+ item.status === ProductImportItemStatus.COMPLETED_WITH_WARNINGS ||
+ (item.status === ProductImportItemStatus.PROCESSING &&
+ Boolean(item.product_id) &&
+ Boolean(
+ (item.payload as unknown as ImportItemPayload)
+ .__productImportEffect,
+ )),
+ )
+ ) {
+ return true;
+ }
+ const deactivatedIds = await this.getProductsDeactivatedByJob(
+ job.product_type,
+ job.specialist_id,
+ job.id,
+ this.prisma,
+ );
+ return deactivatedIds.length > 0;
+ }
+
+ private isSynchronizationPreviewStale(error: unknown): boolean {
+ if (!(error instanceof ConflictException)) return false;
+ const response = error.getResponse();
+ return (
+ typeof response === 'object' &&
+ response !== null &&
+ 'code' in response &&
+ response.code === 'SYNCHRONIZE_PREVIEW_STALE'
+ );
+ }
+
+ private async markSynchronizationPartial(
+ jobId: string,
+ reactivatedCount: number,
+ leaseToken: string,
+ ): Promise {
+ await this.prisma.$transaction(async (tx) => {
+ await this.assertJobLeaseOwned(tx, jobId, leaseToken);
+ const job = await tx.productImportJob.findUnique({
where: { id: jobId },
+ select: {
+ status: true,
+ product_type: true,
+ specialist_id: true,
+ reactivated_items: true,
+ },
+ });
+ if (
+ !job ||
+ job.status === ProductImportJobStatus.COMPLETED ||
+ job.status === ProductImportJobStatus.COMPLETED_WITH_ERRORS ||
+ job.status === ProductImportJobStatus.FAILED
+ ) {
+ return;
+ }
+ await tx.productImportJobItem.updateMany({
+ where: {
+ job_id: jobId,
+ status: ProductImportItemStatus.PROCESSING,
+ product_id: { not: null },
+ },
data: {
- status: ProductImportJobStatus.FAILED,
+ status: ProductImportItemStatus.COMPLETED_WITH_WARNINGS,
+ warnings: [
+ 'O catálogo mudou após o checkpoint; confira a importação de imagens antes de gerar uma nova prévia.',
+ ],
+ processed_at: new Date(),
+ },
+ });
+ const items = await tx.productImportJobItem.findMany({
+ where: { job_id: jobId },
+ select: {
+ status: true,
+ action: true,
+ product_id: true,
+ },
+ });
+ const completed = items.filter(
+ (item) =>
+ item.status === ProductImportItemStatus.COMPLETED ||
+ item.status === ProductImportItemStatus.COMPLETED_WITH_WARNINGS ||
+ (item.status === ProductImportItemStatus.PROCESSING &&
+ Boolean(item.product_id)),
+ );
+ const changedProductIds = completed
+ .map((item) => item.product_id)
+ .filter((id): id is string => Boolean(id));
+ const insertedCount = completed.filter(
+ (item) => item.action === 'CREATED',
+ ).length;
+ const updatedCount = completed.filter(
+ (item) => item.action === 'UPDATED',
+ ).length;
+ const warningItems = completed.filter(
+ (item) =>
+ item.status === ProductImportItemStatus.COMPLETED_WITH_WARNINGS,
+ ).length;
+ const failedItems = items.filter(
+ (item) => item.status === ProductImportItemStatus.FAILED,
+ ).length;
+ const deactivatedIds = await this.getProductsDeactivatedByJob(
+ job.product_type,
+ job.specialist_id,
+ jobId,
+ tx,
+ );
+ const details = changedProductIds.length
+ ? ` Produtos alterados: ${changedProductIds.join(', ')}.`
+ : '';
+ await tx.productImportJob.updateMany({
+ where: {
+ id: jobId,
+ status: {
+ in: [
+ ProductImportJobStatus.PENDING,
+ ProductImportJobStatus.PROCESSING,
+ ],
+ },
+ },
+ data: {
+ status: ProductImportJobStatus.COMPLETED_WITH_ERRORS,
+ total_items: items.length,
+ processed_items: completed.length + failedItems,
+ success_items: completed.length,
+ warning_items: warningItems,
+ failed_items: failedItems,
+ deactivated_items: deactivatedIds.length,
+ deactivated_product_ids: deactivatedIds,
+ reactivated_items: Math.max(
+ reactivatedCount,
+ job.reactivated_items,
+ ),
error_message:
- error?.message || 'Erro ao processar job de importação',
+ `Importação parcial: ${insertedCount} inserido(s), ${updatedCount} atualizado(s). ` +
+ `O catálogo mudou durante o processamento; nenhuma nova desativação foi aplicada` +
+ `${deactivatedIds.length ? ` e ${deactivatedIds.length} desativação(ões) anterior(es) do job foi(ram) preservada(s)` : ''}. ` +
+ `Gere uma nova prévia.${details}`,
finished_at: new Date(),
},
});
- }
+ });
}
private async getJobExecutionContext(job: {
@@ -776,55 +1396,144 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
specialistId: string,
rows: ImportParsedRow[],
mode: ProductImportMode,
+ client: PrismaService | Prisma.TransactionClient = this.prisma,
) {
- const activeProducts = await this.getActiveProductsByType(
+ const snapshot = await this.getSynchronizationCatalogSnapshot(
productType,
specialistId,
+ rows,
+ client,
);
+ if (mode === 'SYNCHRONIZE') return snapshot.impact;
+ return { ...snapshot.impact, deactivationCandidates: 0 };
+ }
+
+ private deriveImportImpact(
+ activeItemsBefore: number,
+ matchingItems: number,
+ rows: ImportParsedRow[],
+ deactivationCandidates: number,
+ ): ImportImpact {
const incomingIdentifiers = new Set(
rows.map((row) => row.identificador?.trim()).filter(Boolean),
);
- const matching = activeProducts.filter((product) =>
- incomingIdentifiers.has(product.identificador),
- ).length;
- const deactivationCandidates =
- mode === 'SYNCHRONIZE'
- ? activeProducts.filter(
- (product) => !incomingIdentifiers.has(product.identificador),
- ).length
- : 0;
return {
incomingItems: rows.length,
- activeItemsBefore: activeProducts.length,
- matchingItems: matching,
- newOrReactivatedItems: Math.max(0, incomingIdentifiers.size - matching),
+ activeItemsBefore,
+ matchingItems,
+ newOrReactivatedItems: Math.max(
+ 0,
+ incomingIdentifiers.size - matchingItems,
+ ),
deactivationCandidates,
};
}
- private async getActiveProductsByType(
+ private async getCatalogProductsByType(
productType: ProductType,
specialistId: string,
client: PrismaService | Prisma.TransactionClient = this.prisma,
- ): Promise> {
+ ): Promise {
+ type CatalogRow = {
+ id: string;
+ identificador: string;
+ isActive: boolean;
+ updatedAt: Date;
+ rowVersion: string;
+ };
+ const rawClient = client as PrismaService;
+ if (typeof rawClient.$queryRaw === 'function') {
+ const rows =
+ productType === ProductType.CAR
+ ? await rawClient.$queryRaw`
+ SELECT "id"::text AS "id", "identificador",
+ COALESCE("is_active", true) AS "isActive",
+ "updated_at" AS "updatedAt", xmin::text AS "rowVersion"
+ FROM "Car" WHERE "specialist_id" = ${specialistId}::uuid
+ `
+ : productType === ProductType.BOAT
+ ? await rawClient.$queryRaw`
+ SELECT "id"::text AS "id", "identificador",
+ COALESCE("is_active", true) AS "isActive",
+ "updated_at" AS "updatedAt", xmin::text AS "rowVersion"
+ FROM "Boat" WHERE "specialist_id" = ${specialistId}::uuid
+ `
+ : await rawClient.$queryRaw`
+ SELECT "id"::text AS "id", "identificador",
+ COALESCE("is_active", true) AS "isActive",
+ "updated_at" AS "updatedAt", xmin::text AS "rowVersion"
+ FROM "Aircraft" WHERE "specialist_id" = ${specialistId}::uuid
+ `;
+ return rows.map((product) => ({
+ id: product.id,
+ identificador: product.identificador,
+ isActive: product.isActive,
+ updatedAt: product.updatedAt.toISOString(),
+ rowVersion: product.rowVersion,
+ }));
+ }
+
+ // Doubles unitários simples não expõem query raw. Em execução real,
+ // a consulta única acima captura dados e xmin no mesmo snapshot.
const query = {
- where: { specialist_id: specialistId, is_active: true },
- select: { id: true, identificador: true },
+ where: { specialist_id: specialistId },
+ select: {
+ id: true,
+ identificador: true,
+ is_active: true,
+ updated_at: true,
+ },
};
+ let products: Array<{
+ id: string;
+ identificador: string;
+ is_active: boolean;
+ updated_at: Date;
+ }>;
if (productType === ProductType.CAR) {
- return (client as PrismaService).car.findMany(query);
- }
- if (productType === ProductType.BOAT) {
- return (client as PrismaService).boat.findMany(query);
+ products = await (client as PrismaService).car.findMany(query);
+ } else if (productType === ProductType.BOAT) {
+ products = await (client as PrismaService).boat.findMany(query);
+ } else {
+ products = await (client as PrismaService).aircraft.findMany(query);
}
- return (client as PrismaService).aircraft.findMany(query);
+ return products.map((product) => ({
+ id: product.id,
+ identificador: product.identificador,
+ isActive: product.is_active ?? true,
+ updatedAt:
+ product.updated_at instanceof Date
+ ? product.updated_at.toISOString()
+ : '1970-01-01T00:00:00.000Z',
+ rowVersion: `test-double:${product.id}:${
+ product.updated_at instanceof Date
+ ? product.updated_at.toISOString()
+ : 'unknown'
+ }`,
+ }));
+ }
+
+ private async getActiveProductsByType(
+ productType: ProductType,
+ specialistId: string,
+ client: PrismaService | Prisma.TransactionClient = this.prisma,
+ ): Promise> {
+ const products = await this.getCatalogProductsByType(
+ productType,
+ specialistId,
+ client,
+ );
+ return products
+ .filter((product) => product.isActive)
+ .map(({ id, identificador }) => ({ id, identificador }));
}
private async refreshJobCounters(
jobId: string,
syncSummary?: { deactivatedIds: string[]; reactivatedCount: number },
+ client: PrismaService | Prisma.TransactionClient = this.prisma,
) {
- const items = await this.prisma.productImportJobItem.findMany({
+ const items = await (client as PrismaService).productImportJobItem.findMany({
where: { job_id: jobId },
select: {
status: true,
@@ -862,7 +1571,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
finalStatus = ProductImportJobStatus.FAILED;
}
- await this.prisma.productImportJob.update({
+ await (client as PrismaService).productImportJob.update({
where: { id: jobId },
data: {
status: finalStatus,
@@ -879,86 +1588,346 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
});
}
+ private async finalizeUnsynchronizedJob(
+ jobId: string,
+ syncSummary: { deactivatedIds: string[]; reactivatedCount: number },
+ leaseToken: string,
+ ): Promise {
+ await this.prisma.$transaction(async (tx) => {
+ await this.assertJobLeaseOwned(tx, jobId, leaseToken);
+ await this.refreshJobCounters(jobId, syncSummary, tx);
+ });
+ }
+
+ private async finalizeSynchronizedJob(
+ jobId: string,
+ input: {
+ productType: ProductType;
+ specialistId: string;
+ seenProductIds: Set;
+ snapshot: SynchronizePreviewSnapshot | null;
+ },
+ reactivatedCount: number,
+ leaseToken: string,
+ ): Promise {
+ await this.runSerializableWithRetry(async (tx) => {
+ await this.assertJobLeaseOwned(tx, jobId, leaseToken);
+ await this.lockProductCatalogForSnapshot(tx, input.productType);
+ const items = await tx.productImportJobItem.findMany({
+ where: { job_id: jobId },
+ select: {
+ status: true,
+ action: true,
+ product_id: true,
+ payload: true,
+ },
+ });
+ await this.assertLogicalCatalogMatches(
+ input.productType,
+ input.specialistId,
+ jobId,
+ input.snapshot,
+ items,
+ tx,
+ );
+ const deactivatedIds = await this.deactivateMissingProducts(
+ input.productType,
+ input.specialistId,
+ input.seenProductIds,
+ jobId,
+ input.snapshot,
+ tx,
+ );
+ await this.refreshJobCounters(
+ jobId,
+ { deactivatedIds, reactivatedCount },
+ tx,
+ );
+ });
+ }
+
+ private async lockProductCatalogForSnapshot(
+ tx: Prisma.TransactionClient,
+ productType: ProductType,
+ ): Promise {
+ if (productType === ProductType.CAR) {
+ await tx.$executeRaw`LOCK TABLE "Car" IN SHARE ROW EXCLUSIVE MODE`;
+ } else if (productType === ProductType.BOAT) {
+ await tx.$executeRaw`LOCK TABLE "Boat" IN SHARE ROW EXCLUSIVE MODE`;
+ } else {
+ await tx.$executeRaw`LOCK TABLE "Aircraft" IN SHARE ROW EXCLUSIVE MODE`;
+ }
+ }
+
+ private async assertSynchronizationSnapshotCurrent(
+ job: {
+ id: string;
+ product_type: ProductType;
+ specialist_id: string;
+ items: Array<{
+ payload: unknown;
+ status: ProductImportItemStatus;
+ action: string | null;
+ product_id: string | null;
+ }>;
+ },
+ snapshot: SynchronizePreviewSnapshot | null,
+ ): Promise {
+ if (!snapshot) {
+ throw this.synchronizePreviewStale();
+ }
+ const incomingIdentifiers = new Set(
+ job.items
+ .map((item) => {
+ const row = item.payload as unknown as ImportParsedRow;
+ return row.identificador?.trim();
+ })
+ .filter(Boolean),
+ );
+ await this.runSerializableWithRetry(async (tx) => {
+ await this.assertLogicalCatalogMatches(
+ job.product_type,
+ job.specialist_id,
+ job.id,
+ snapshot,
+ job.items,
+ tx,
+ );
+ const activeProducts = await this.getActiveProductsByType(
+ job.product_type,
+ job.specialist_id,
+ tx,
+ );
+ const alreadyDeactivatedIds = await this.getProductsDeactivatedByJob(
+ job.product_type,
+ job.specialist_id,
+ job.id,
+ tx,
+ );
+ const currentCandidateIds = [
+ ...activeProducts
+ .filter(
+ (product) => !incomingIdentifiers.has(product.identificador),
+ )
+ .map((product) => product.id),
+ ...alreadyDeactivatedIds,
+ ].sort();
+ this.assertCandidateIdsMatch(
+ currentCandidateIds,
+ snapshot.candidateIds,
+ );
+ });
+ }
+
+ private async assertLogicalCatalogMatches(
+ productType: ProductType,
+ specialistId: string,
+ jobId: string,
+ snapshot: SynchronizePreviewSnapshot | null,
+ items: Array<{
+ status: ProductImportItemStatus;
+ action: string | null;
+ product_id: string | null;
+ payload: unknown;
+ }>,
+ tx: Prisma.TransactionClient,
+ ): Promise {
+ if (
+ !snapshot?.catalogDigest ||
+ !Array.isArray(snapshot.catalogProducts)
+ ) {
+ throw this.synchronizePreviewStale();
+ }
+ const currentCatalog = await this.getCatalogProductsByType(
+ productType,
+ specialistId,
+ tx,
+ );
+ const originals = new Map(
+ snapshot.catalogProducts.map((product) => [product.id, product]),
+ );
+ const checkpointedItems = items.filter(
+ (item) =>
+ item.status === ProductImportItemStatus.COMPLETED ||
+ item.status === ProductImportItemStatus.COMPLETED_WITH_WARNINGS ||
+ item.status === ProductImportItemStatus.PROCESSING,
+ );
+ const effects = new Map();
+ for (const item of checkpointedItems) {
+ const effect = (item.payload as unknown as ImportItemPayload)
+ .__productImportEffect;
+ if (
+ effect &&
+ item.product_id === effect.productId &&
+ item.action === effect.action
+ ) {
+ effects.set(effect.productId, effect);
+ }
+ }
+ const currentProducts = new Map(
+ currentCatalog.map((product) => [product.id, product]),
+ );
+ for (const effect of effects.values()) {
+ if (
+ effect.action === 'CREATED' &&
+ (!currentProducts.has(effect.productId) ||
+ currentProducts.get(effect.productId)?.rowVersion !==
+ effect.rowVersion)
+ ) {
+ // Produto criado pelo CSV removido/alterado depois do checkpoint não
+ // existia no snapshot original e, sem esta guarda, desapareceria do
+ // catálogo lógico sem invalidar a sincronização.
+ throw this.synchronizePreviewStale();
+ }
+ }
+ const alreadyDeactivatedIds = new Set(
+ await this.getProductsDeactivatedByJob(
+ productType,
+ specialistId,
+ jobId,
+ tx,
+ ),
+ );
+ const logicalCatalog: CatalogProductSnapshot[] = [];
+ for (const product of currentCatalog) {
+ const effect = effects.get(product.id);
+ const wasDeactivatedByJob = alreadyDeactivatedIds.has(product.id);
+ if (!effect && !wasDeactivatedByJob) {
+ logicalCatalog.push(product);
+ continue;
+ }
+ const original = originals.get(product.id);
+ if (wasDeactivatedByJob) {
+ if (original) logicalCatalog.push(original);
+ } else if (effect && product.rowVersion !== effect.rowVersion) {
+ // Mudança posterior ao checkpoint não pertence a este job.
+ logicalCatalog.push(product);
+ } else if (original) {
+ logicalCatalog.push(original);
+ } else if (effect?.action !== 'CREATED') {
+ // Um UPDATED desconhecido não pode ser atribuído ao job com segurança.
+ logicalCatalog.push(product);
+ }
+ }
+ if (this.catalogDigest(logicalCatalog) !== snapshot.catalogDigest) {
+ throw this.synchronizePreviewStale();
+ }
+ }
+
private async deactivateMissingProducts(
productType: ProductType,
specialistId: string,
seenProductIds: Set,
jobId: string,
snapshot: SynchronizePreviewSnapshot | null,
+ tx: Prisma.TransactionClient,
): Promise {
if (!snapshot) {
throw this.synchronizePreviewStale();
}
- return this.prisma.$transaction(
- async (tx) => {
- const activeProducts = await this.getActiveProductsByType(
- productType,
- specialistId,
- tx,
- );
- const currentCandidateIds = activeProducts
- .map((product) => product.id)
- .filter((id) => !seenProductIds.has(id))
- .sort();
- const expectedCandidateIds = [...snapshot.candidateIds].sort();
- if (
- currentCandidateIds.length !== expectedCandidateIds.length ||
- currentCandidateIds.some(
- (id, index) => id !== expectedCandidateIds[index],
- )
- ) {
- throw this.synchronizePreviewStale();
- }
- if (expectedCandidateIds.length === 0) {
- return [];
- }
+ const activeProducts = await this.getActiveProductsByType(
+ productType,
+ specialistId,
+ tx,
+ );
+ const alreadyDeactivatedIds = await this.getProductsDeactivatedByJob(
+ productType,
+ specialistId,
+ jobId,
+ tx,
+ );
+ const currentCandidateIds = [
+ ...activeProducts
+ .map((product) => product.id)
+ .filter((id) => !seenProductIds.has(id)),
+ ...alreadyDeactivatedIds,
+ ].sort();
+ const expectedCandidateIds = [...snapshot.candidateIds].sort();
+ this.assertCandidateIdsMatch(currentCandidateIds, expectedCandidateIds);
+ if (expectedCandidateIds.length === 0) {
+ return [];
+ }
- for (const productId of expectedCandidateIds) {
- await acquireProductMonetaryLock(tx, { productType, productId });
- }
+ const data = {
+ is_active: false,
+ deactivated_at: new Date(),
+ deactivated_by_sync_job_id: jobId,
+ };
- const data = {
- is_active: false,
- deactivated_at: new Date(),
- deactivated_by_sync_job_id: jobId,
- };
+ if (productType === ProductType.CAR) {
+ await tx.car.updateMany({
+ where: {
+ id: { in: expectedCandidateIds },
+ specialist_id: specialistId,
+ is_active: true,
+ },
+ data,
+ });
+ } else if (productType === ProductType.BOAT) {
+ await tx.boat.updateMany({
+ where: {
+ id: { in: expectedCandidateIds },
+ specialist_id: specialistId,
+ is_active: true,
+ },
+ data,
+ });
+ } else {
+ await tx.aircraft.updateMany({
+ where: {
+ id: { in: expectedCandidateIds },
+ specialist_id: specialistId,
+ is_active: true,
+ },
+ data,
+ });
+ }
+ return expectedCandidateIds;
+ }
- if (productType === ProductType.CAR) {
- await tx.car.updateMany({
- where: {
- id: { in: expectedCandidateIds },
- specialist_id: specialistId,
- is_active: true,
- },
- data,
- });
- } else if (productType === ProductType.BOAT) {
- await tx.boat.updateMany({
- where: {
- id: { in: expectedCandidateIds },
- specialist_id: specialistId,
- is_active: true,
- },
- data,
- });
- } else {
- await tx.aircraft.updateMany({
- where: {
- id: { in: expectedCandidateIds },
- specialist_id: specialistId,
- is_active: true,
- },
- data,
- });
- }
- return expectedCandidateIds;
- },
- {
- isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
+ private async getProductsDeactivatedByJob(
+ productType: ProductType,
+ specialistId: string,
+ jobId: string,
+ client: PrismaService | Prisma.TransactionClient,
+ ): Promise {
+ const query = {
+ where: {
+ specialist_id: specialistId,
+ is_active: false,
+ deactivated_by_sync_job_id: jobId,
},
+ select: { id: true },
+ };
+ if (productType === ProductType.CAR) {
+ return (await (client as PrismaService).car.findMany(query)).map(
+ ({ id }) => id,
+ );
+ }
+ if (productType === ProductType.BOAT) {
+ return (await (client as PrismaService).boat.findMany(query)).map(
+ ({ id }) => id,
+ );
+ }
+ return (await (client as PrismaService).aircraft.findMany(query)).map(
+ ({ id }) => id,
);
}
+ private assertCandidateIdsMatch(
+ currentCandidateIds: string[],
+ expectedCandidateIds: string[],
+ ): void {
+ const current = [...currentCandidateIds].sort();
+ const expected = [...expectedCandidateIds].sort();
+ if (
+ current.length !== expected.length ||
+ current.some((id, index) => id !== expected[index])
+ ) {
+ throw this.synchronizePreviewStale();
+ }
+ }
+
private synchronizePreviewStale(): ConflictException {
return new ConflictException({
code: 'SYNCHRONIZE_PREVIEW_STALE',
@@ -998,6 +1967,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
productType: ProductType,
row: ImportParsedRow,
specialistId: string,
+ client: PrismaService | Prisma.TransactionClient = this.prisma,
): Promise {
row = this.normalizeProductRow(row);
this.validateRequiredProductFields(row);
@@ -1031,7 +2001,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
await this.validatePayload(data, CreateCarDto);
- const existing = await this.prisma.car.findFirst({
+ const existing = await (client as PrismaService).car.findFirst({
where: {
specialist_id: specialistId,
identificador,
@@ -1041,7 +2011,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
if (existing) {
const { specialist_id: _specialistId, ...updateData } = data;
const reactivated = !existing.is_active;
- await updateProductWithMonetaryLock(this.prisma, {
+ const updated = (await updateProductWithMonetaryLock(client, {
productType: ProductType.CAR,
productId: existing.id,
nextValue: data.valor,
@@ -1052,13 +2022,22 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
deactivated_at: null,
deactivated_by_sync_job_id: null,
},
- });
+ })) as { updated_at?: Date };
- return { productId: existing.id, action: 'UPDATED', reactivated };
+ return {
+ productId: existing.id,
+ action: 'UPDATED',
+ reactivated,
+ updatedAt: updated.updated_at?.toISOString(),
+ };
}
- const created = await this.prisma.car.create({ data });
- return { productId: created.id, action: 'CREATED' };
+ const created = await (client as PrismaService).car.create({ data });
+ return {
+ productId: created.id,
+ action: 'CREATED',
+ updatedAt: created.updated_at?.toISOString(),
+ };
}
if (productType === ProductType.BOAT) {
@@ -1086,7 +2065,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
await this.validatePayload(data, CreateBoatDto);
- const existing = await this.prisma.boat.findFirst({
+ const existing = await (client as PrismaService).boat.findFirst({
where: {
specialist_id: specialistId,
identificador,
@@ -1096,7 +2075,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
if (existing) {
const { specialist_id: _specialistId, ...updateData } = data;
const reactivated = !existing.is_active;
- await updateProductWithMonetaryLock(this.prisma, {
+ const updated = (await updateProductWithMonetaryLock(client, {
productType: ProductType.BOAT,
productId: existing.id,
nextValue: data.valor,
@@ -1107,13 +2086,22 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
deactivated_at: null,
deactivated_by_sync_job_id: null,
},
- });
+ })) as { updated_at?: Date };
- return { productId: existing.id, action: 'UPDATED', reactivated };
+ return {
+ productId: existing.id,
+ action: 'UPDATED',
+ reactivated,
+ updatedAt: updated.updated_at?.toISOString(),
+ };
}
- const created = await this.prisma.boat.create({ data });
- return { productId: created.id, action: 'CREATED' };
+ const created = await (client as PrismaService).boat.create({ data });
+ return {
+ productId: created.id,
+ action: 'CREATED',
+ updatedAt: created.updated_at?.toISOString(),
+ };
}
const data = {
@@ -1135,7 +2123,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
await this.validatePayload(data, CreateAircraftDto);
- const existing = await this.prisma.aircraft.findFirst({
+ const existing = await (client as PrismaService).aircraft.findFirst({
where: {
specialist_id: specialistId,
identificador,
@@ -1145,7 +2133,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
if (existing) {
const { specialist_id: _specialistId, ...updateData } = data;
const reactivated = !existing.is_active;
- await updateProductWithMonetaryLock(this.prisma, {
+ const updated = (await updateProductWithMonetaryLock(client, {
productType: ProductType.AIRCRAFT,
productId: existing.id,
nextValue: data.valor,
@@ -1156,13 +2144,22 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
deactivated_at: null,
deactivated_by_sync_job_id: null,
},
- });
+ })) as { updated_at?: Date };
- return { productId: existing.id, action: 'UPDATED', reactivated };
+ return {
+ productId: existing.id,
+ action: 'UPDATED',
+ reactivated,
+ updatedAt: updated.updated_at?.toISOString(),
+ };
}
- const created = await this.prisma.aircraft.create({ data });
- return { productId: created.id, action: 'CREATED' };
+ const created = await (client as PrismaService).aircraft.create({ data });
+ return {
+ productId: created.id,
+ action: 'CREATED',
+ updatedAt: created.updated_at?.toISOString(),
+ };
}
private normalizeProductRow(row: ImportParsedRow): ImportParsedRow {
@@ -1174,6 +2171,22 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy {
);
}
+ private validateUniqueIdentifiers(rows: ImportParsedRow[]): void {
+ const seen = new Set();
+ const duplicates = new Set();
+ for (const row of rows) {
+ const identifier = row.identificador?.trim();
+ if (!identifier) continue;
+ if (seen.has(identifier)) duplicates.add(identifier);
+ seen.add(identifier);
+ }
+ if (duplicates.size > 0) {
+ throw new BadRequestException(
+ `O CSV contém identificadores duplicados: ${[...duplicates].join(', ')}.`,
+ );
+ }
+ }
+
private validateRequiredProductFields(row: ImportParsedRow): void {
const missingFields = REQUIRED_PRODUCT_FIELDS.filter(
({ key }) => !row[key],
diff --git a/backend/src/features/product-import-jobs/product-sync-preview.postgres.spec.ts b/backend/src/features/product-import-jobs/product-sync-preview.postgres.spec.ts
index 86c3d89..3dbc129 100644
--- a/backend/src/features/product-import-jobs/product-sync-preview.postgres.spec.ts
+++ b/backend/src/features/product-import-jobs/product-sync-preview.postgres.spec.ts
@@ -6,6 +6,7 @@ import {
UserRole,
} from '@prisma/client';
import { ProductImportJobsService } from './product-import-jobs.service';
+import { acquireProductMonetaryLock } from '../products/product-monetary-lock';
const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL;
const describeWithPostgres = databaseUrl ? describe : describe.skip;
@@ -47,6 +48,7 @@ describeWithPostgres('product synchronization preview — PostgreSQL', () => {
});
beforeEach(async () => {
+ xlsx.parseCsv.mockReturnValue({ rows: [row] });
await prisma.productImportJob.deleteMany({
where: { specialist_id: specialistId },
});
@@ -85,11 +87,13 @@ describeWithPostgres('product synchronization preview — PostgreSQL', () => {
delete process.env.PRODUCT_IMPORT_PREVIEW_SECRET;
});
- function createService() {
+ function createService(
+ drive = { importImagesForProductFromFolder: jest.fn() } as any,
+ ) {
const service = new ProductImportJobsService(
prisma as any,
xlsx,
- { importImagesForProductFromFolder: jest.fn() } as any,
+ drive,
);
jest.spyOn(service as any, 'scheduleJob').mockImplementation(() => {});
return service;
@@ -147,6 +151,38 @@ describeWithPostgres('product synchronization preview — PostgreSQL', () => {
).resolves.toBe(0);
});
+ it('rejeita o POST se um produto do CSV saiu do catálogo sem mudar candidatos', async () => {
+ const service = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ await prisma.car.updateMany({
+ where: {
+ specialist_id: specialistId,
+ identificador: row.identificador,
+ },
+ data: { is_active: false, deactivated_at: new Date() },
+ });
+
+ await expect(
+ service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ ),
+ ).rejects.toMatchObject({
+ response: expect.objectContaining({ code: 'SYNCHRONIZE_PREVIEW_STALE' }),
+ });
+ await expect(
+ prisma.productImportJob.count({ where: { specialist_id: specialistId } }),
+ ).resolves.toBe(0);
+ });
+
it('não desativa nada se o catálogo mudar entre o POST e a execução', async () => {
const service = createService();
const file = Buffer.from('same-csv');
@@ -162,6 +198,13 @@ describeWithPostgres('product synchronization preview — PostgreSQL', () => {
ProductType.CAR,
options(preview.synchronizePreviewToken!),
);
+ await prisma.car.updateMany({
+ where: {
+ specialist_id: specialistId,
+ identificador: row.identificador,
+ },
+ data: { modelo: 'Antes do worker', valor: 123456 },
+ });
const productC = await prisma.car.create({
data: {
specialist_id: specialistId,
@@ -178,13 +221,24 @@ describeWithPostgres('product synchronization preview — PostgreSQL', () => {
const products = await prisma.car.findMany({
where: { specialist_id: specialistId },
- select: { id: true, identificador: true, is_active: true },
+ select: {
+ id: true,
+ identificador: true,
+ modelo: true,
+ valor: true,
+ is_active: true,
+ },
});
expect(products).toHaveLength(3);
expect(products.every((product) => product.is_active)).toBe(true);
expect(products.find((product) => product.id === productC.id)?.is_active).toBe(
true,
);
+ const kept = products.find(
+ (product) => product.identificador === row.identificador,
+ );
+ expect(kept?.modelo).toBe('Antes do worker');
+ expect(Number(kept?.valor)).toBe(123456);
await expect(
prisma.productImportJob.findUniqueOrThrow({
where: { id: accepted.jobId },
@@ -201,6 +255,58 @@ describeWithPostgres('product synchronization preview — PostgreSQL', () => {
});
});
+ it('não processa linhas se produto do CSV sair do catálogo antes do worker', async () => {
+ const service = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+ const matching = await prisma.car.findFirstOrThrow({
+ where: {
+ specialist_id: specialistId,
+ identificador: row.identificador,
+ },
+ });
+ await prisma.car.update({
+ where: { id: matching.id },
+ data: {
+ is_active: false,
+ deactivated_at: new Date(),
+ modelo: 'External change',
+ valor: 321654,
+ },
+ });
+
+ await (service as any).processJob(accepted.jobId);
+
+ const unchanged = await prisma.car.findUniqueOrThrow({
+ where: { id: matching.id },
+ });
+ expect(unchanged).toMatchObject({
+ is_active: false,
+ modelo: 'External change',
+ });
+ expect(Number(unchanged.valor)).toBe(321654);
+ await expect(
+ prisma.productImportJob.findUniqueOrThrow({
+ where: { id: accepted.jobId },
+ select: { status: true, success_items: true },
+ }),
+ ).resolves.toEqual({
+ status: ProductImportJobStatus.FAILED,
+ success_items: 0,
+ });
+ });
+
it('desativa somente o candidato consentido quando o snapshot permanece igual', async () => {
const service = createService();
const file = Buffer.from('same-csv');
@@ -239,4 +345,664 @@ describeWithPostgres('product synchronization preview — PostgreSQL', () => {
deactivated_items: 1,
});
});
+
+ it('relata alterações parciais se D surgir durante o processamento', async () => {
+ const service = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+ const realUpsert = (service as any).upsertProductFromRow.bind(service);
+ let productDId: string | undefined;
+ jest
+ .spyOn(service as any, 'upsertProductFromRow')
+ .mockImplementation(async (...args: unknown[]) => {
+ const result = await realUpsert(...args);
+ const productD = await prisma.car.create({
+ data: {
+ specialist_id: specialistId,
+ identificador: `NEW-D-DURING-${suffix}`,
+ marca: 'New',
+ modelo: 'D',
+ valor: 700000,
+ estado: 'MG',
+ ano: 2026,
+ },
+ });
+ productDId = productD.id;
+ return result;
+ });
+
+ await (service as any).processJob(accepted.jobId);
+
+ const products = await prisma.car.findMany({
+ where: { specialist_id: specialistId },
+ select: { id: true, identificador: true, modelo: true, is_active: true },
+ });
+ const kept = products.find(
+ (product) => product.identificador === row.identificador,
+ );
+ expect(kept).toMatchObject({ modelo: row.modelo, is_active: true });
+ expect(products.find((product) => product.id === productDId)).toMatchObject({
+ is_active: true,
+ });
+ expect(
+ products.find((product) => product.identificador.startsWith('STALE-B-')),
+ ).toMatchObject({ is_active: true });
+
+ const status = await service.getJobStatus(
+ accepted.jobId,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ specialistId,
+ );
+ expect(status).toMatchObject({
+ status: ProductImportJobStatus.COMPLETED_WITH_ERRORS,
+ deactivatedItems: 0,
+ errorMessage: expect.stringContaining('Importação parcial'),
+ result: {
+ message: expect.stringContaining('Importação parcial'),
+ updatedIds: [kept!.id],
+ deactivatedCount: 0,
+ },
+ });
+ });
+
+ it('detecta alteração externa de A depois do checkpoint e antes da finalização', async () => {
+ let keptId = '';
+ let leaseWasExtendedForDrive = false;
+ const drive = {
+ importImagesForProductFromFolder: jest.fn(async () => {
+ const [lease] = await prisma.$queryRaw<
+ Array<{ extended: boolean }>
+ >`
+ SELECT "processing_lease_expires_at" > NOW() + INTERVAL '20 minutes' AS "extended"
+ FROM "ProductImportJob"
+ WHERE "id" = ${acceptedJobId}::uuid
+ `;
+ leaseWasExtendedForDrive = lease?.extended === true;
+ await prisma.car.update({
+ where: { id: keptId },
+ data: { modelo: 'External after checkpoint', valor: 654321 },
+ });
+ return { failed: 0, warnings: [] };
+ }),
+ } as any;
+ const service = createService(drive);
+ let acceptedJobId = '';
+ const file = Buffer.from('same-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+ acceptedJobId = accepted.jobId;
+ const kept = await prisma.car.findFirstOrThrow({
+ where: { specialist_id: specialistId, identificador: row.identificador },
+ });
+ keptId = kept.id;
+ await prisma.productImportJobItem.updateMany({
+ where: { job_id: accepted.jobId },
+ data: { folder_url: 'https://drive.example/folder' },
+ });
+
+ await (service as any).processJob(accepted.jobId);
+
+ expect(leaseWasExtendedForDrive).toBe(true);
+
+ await expect(
+ prisma.car.findUniqueOrThrow({ where: { id: kept.id } }),
+ ).resolves.toMatchObject({
+ modelo: 'External after checkpoint',
+ is_active: true,
+ });
+ await expect(
+ prisma.productImportJob.findUniqueOrThrow({
+ where: { id: accepted.jobId },
+ select: { status: true, deactivated_items: true, error_message: true },
+ }),
+ ).resolves.toMatchObject({
+ status: ProductImportJobStatus.COMPLETED_WITH_ERRORS,
+ deactivated_items: 0,
+ error_message: expect.stringContaining('Importação parcial'),
+ });
+ });
+
+ it('retoma efeito checkpointado atomicamente sem repetir o upsert', async () => {
+ const service = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+ const kept = await prisma.car.findFirstOrThrow({
+ where: { specialist_id: specialistId, identificador: row.identificador },
+ });
+ const updated = await prisma.car.update({
+ where: { id: kept.id },
+ data: { modelo: row.modelo, valor: Number(row.valor) },
+ });
+ const [version] = await prisma.$queryRaw>`
+ SELECT xmin::text AS "rowVersion"
+ FROM "Car"
+ WHERE "id" = ${kept.id}::uuid
+ `;
+ await prisma.productImportJobItem.updateMany({
+ where: { job_id: accepted.jobId },
+ data: {
+ status: 'PROCESSING',
+ product_id: kept.id,
+ action: 'UPDATED',
+ payload: {
+ ...row,
+ __productImportEffect: {
+ productId: kept.id,
+ action: 'UPDATED',
+ rowVersion: version.rowVersion,
+ updatedAt: updated.updated_at.toISOString(),
+ },
+ },
+ },
+ });
+ const upsert = jest.spyOn(service as any, 'upsertProductFromRow');
+
+ await (service as any).processJob(accepted.jobId);
+
+ expect(upsert).not.toHaveBeenCalled();
+ await expect(
+ prisma.productImportJob.findUniqueOrThrow({
+ where: { id: accepted.jobId },
+ select: { status: true, deactivated_items: true },
+ }),
+ ).resolves.toEqual({
+ status: ProductImportJobStatus.COMPLETED,
+ deactivated_items: 1,
+ });
+ });
+
+ it('concede o claim distribuído do job a apenas um worker', async () => {
+ const first = createService();
+ const second = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await first.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await first.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+
+ const claims = await Promise.all([
+ (first as any).claimJob(accepted.jobId),
+ (second as any).claimJob(accepted.jobId),
+ ]);
+
+ expect(claims.filter(Boolean)).toHaveLength(1);
+ expect(claims.filter((claim) => claim === null)).toHaveLength(1);
+ });
+
+ it('impede worker antigo de gravar depois que outro assumiu o lease', async () => {
+ const staleWorker = createService();
+ const currentWorker = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await staleWorker.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await staleWorker.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+ const staleLease = await (staleWorker as any).claimJob(accepted.jobId);
+ expect(staleLease).toEqual(expect.any(String));
+ await prisma.$executeRaw`
+ UPDATE "ProductImportJob"
+ SET "processing_lease_expires_at" = NOW() - INTERVAL '1 second'
+ WHERE "id" = ${accepted.jobId}::uuid
+ `;
+ const currentLease = await (currentWorker as any).claimJob(accepted.jobId);
+ expect(currentLease).toEqual(expect.any(String));
+ const job = await prisma.productImportJob.findUniqueOrThrow({
+ where: { id: accepted.jobId },
+ include: { items: true },
+ });
+ const item = job.items[0];
+
+ await expect(
+ (staleWorker as any).checkpointProductUpsert(
+ job,
+ item,
+ { ...row, modelo: 'Stale worker mutation' },
+ staleLease,
+ ),
+ ).rejects.toThrow(/lease/i);
+ await (staleWorker as any).markJobFailedUnlessTerminal(
+ accepted.jobId,
+ 'stale worker failure',
+ staleLease,
+ );
+
+ await expect(
+ prisma.car.findFirstOrThrow({
+ where: { specialist_id: specialistId, identificador: row.identificador },
+ select: { modelo: true },
+ }),
+ ).resolves.toEqual({ modelo: row.modelo });
+ const leaseState = await prisma.$queryRaw<
+ Array<{ status: ProductImportJobStatus; processing_lease_token: string }>
+ >`
+ SELECT "status", "processing_lease_token"::text
+ FROM "ProductImportJob"
+ WHERE "id" = ${accepted.jobId}::uuid
+ `;
+ expect(leaseState).toEqual([
+ {
+ status: ProductImportJobStatus.PROCESSING,
+ processing_lease_token: currentLease,
+ },
+ ]);
+ });
+
+ it('detecta mudança externa mesmo quando updated_at coincide com o checkpoint', async () => {
+ const service = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+ const lease = await (service as any).claimJob(accepted.jobId);
+ const job = await prisma.productImportJob.findUniqueOrThrow({
+ where: { id: accepted.jobId },
+ include: { items: true },
+ });
+ const item = job.items[0];
+ await (service as any).checkpointProductUpsert(
+ job,
+ item,
+ item.payload,
+ lease,
+ );
+ const checkpointed = await prisma.productImportJobItem.findUniqueOrThrow({
+ where: { id: item.id },
+ });
+ const checkpointTimestamp = new Date(
+ (checkpointed.payload as any).__productImportEffect.updatedAt,
+ );
+ await prisma.car.update({
+ where: { id: checkpointed.product_id! },
+ data: {
+ modelo: 'External same timestamp',
+ valor: 987654,
+ updated_at: checkpointTimestamp,
+ },
+ });
+ await (service as any).releaseJobLease(accepted.jobId, lease);
+
+ await (service as any).processJob(accepted.jobId);
+
+ await expect(
+ prisma.car.findUniqueOrThrow({ where: { id: checkpointed.product_id! } }),
+ ).resolves.toMatchObject({
+ modelo: 'External same timestamp',
+ is_active: true,
+ });
+ await expect(
+ prisma.productImportJob.findUniqueOrThrow({
+ where: { id: accepted.jobId },
+ select: { status: true, deactivated_items: true, error_message: true },
+ }),
+ ).resolves.toMatchObject({
+ status: ProductImportJobStatus.COMPLETED_WITH_ERRORS,
+ deactivated_items: 0,
+ error_message: expect.stringContaining('Importação parcial'),
+ });
+ await expect(
+ prisma.productImportJobItem.findUniqueOrThrow({
+ where: { id: item.id },
+ select: { status: true, warnings: true },
+ }),
+ ).resolves.toMatchObject({
+ status: 'COMPLETED_WITH_WARNINGS',
+ warnings: expect.arrayContaining([
+ expect.stringContaining('catálogo mudou'),
+ ]),
+ });
+ const status = await service.getJobStatus(
+ accepted.jobId,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ specialistId,
+ );
+ expect(status.result.updatedIds).toContain(checkpointed.product_id);
+ });
+
+ it('não finaliza se produto criado pelo job for removido após o checkpoint', async () => {
+ const createdRow = {
+ ...row,
+ identificador: `CREATED-THEN-DELETED-${suffix}`,
+ modelo: 'Created then deleted',
+ };
+ xlsx.parseCsv.mockReturnValue({ rows: [createdRow] });
+ let createdId = '';
+ const drive = {
+ importImagesForProductFromFolder: jest.fn(async ({ product_id }) => {
+ createdId = product_id;
+ await prisma.car.delete({ where: { id: product_id } });
+ return { failed: 0, warnings: [] };
+ }),
+ } as any;
+ const service = createService(drive);
+ const file = Buffer.from('created-delete-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+ await prisma.productImportJobItem.updateMany({
+ where: { job_id: accepted.jobId },
+ data: { folder_url: 'https://drive.example/folder' },
+ });
+
+ await (service as any).processJob(accepted.jobId);
+
+ expect(createdId).toEqual(expect.any(String));
+ await expect(
+ prisma.car.count({ where: { id: createdId } }),
+ ).resolves.toBe(0);
+ await expect(
+ prisma.car.count({
+ where: { specialist_id: specialistId, is_active: true },
+ }),
+ ).resolves.toBe(2);
+ await expect(
+ prisma.productImportJob.findUniqueOrThrow({
+ where: { id: accepted.jobId },
+ select: { status: true, deactivated_items: true, error_message: true },
+ }),
+ ).resolves.toMatchObject({
+ status: ProductImportJobStatus.COMPLETED_WITH_ERRORS,
+ deactivated_items: 0,
+ error_message: expect.stringContaining('Importação parcial'),
+ });
+ });
+
+ it('não cria deadlock com uma mutação manual que já detém o lock monetário', async () => {
+ const service = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+ const candidate = await prisma.car.findFirstOrThrow({
+ where: {
+ specialist_id: specialistId,
+ identificador: { startsWith: 'STALE-B-' },
+ },
+ });
+ let advisoryReady!: () => void;
+ const advisoryAcquired = new Promise((resolve) => {
+ advisoryReady = resolve;
+ });
+ let allowManualUpdate!: () => void;
+ const manualUpdateGate = new Promise((resolve) => {
+ allowManualUpdate = resolve;
+ });
+ const manualUpdate = prisma.$transaction(async (tx) => {
+ await acquireProductMonetaryLock(tx, {
+ productType: ProductType.CAR,
+ productId: candidate.id,
+ });
+ advisoryReady();
+ await manualUpdateGate;
+ return tx.car.update({
+ where: { id: candidate.id },
+ data: { modelo: 'Manual after sync lock' },
+ });
+ });
+ await advisoryAcquired;
+
+ const realCatalogLock = (
+ service as any
+ ).lockProductCatalogForSnapshot.bind(service);
+ let catalogReady!: () => void;
+ const catalogLocked = new Promise((resolve) => {
+ catalogReady = resolve;
+ });
+ jest
+ .spyOn(service as any, 'lockProductCatalogForSnapshot')
+ .mockImplementation(async (...args: unknown[]) => {
+ const result = await realCatalogLock(...args);
+ catalogReady();
+ return result;
+ });
+ const processing = (service as any).processJob(accepted.jobId);
+ await catalogLocked;
+ allowManualUpdate();
+
+ await Promise.all([manualUpdate, processing]);
+
+ await expect(
+ prisma.productImportJob.findUniqueOrThrow({
+ where: { id: accepted.jobId },
+ select: { status: true },
+ }),
+ ).resolves.toEqual({ status: ProductImportJobStatus.COMPLETED });
+ });
+
+ it('retoma como COMPLETED quando o próprio job já desativou o candidato', async () => {
+ const service = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+ const [kept, candidate] = await Promise.all([
+ prisma.car.findFirstOrThrow({
+ where: {
+ specialist_id: specialistId,
+ identificador: row.identificador,
+ },
+ }),
+ prisma.car.findFirstOrThrow({
+ where: {
+ specialist_id: specialistId,
+ identificador: { startsWith: 'STALE-B-' },
+ },
+ }),
+ ]);
+ await prisma.$transaction([
+ prisma.car.update({
+ where: { id: candidate.id },
+ data: {
+ is_active: false,
+ deactivated_at: new Date(),
+ deactivated_by_sync_job_id: accepted.jobId,
+ },
+ }),
+ prisma.productImportJobItem.updateMany({
+ where: { job_id: accepted.jobId },
+ data: {
+ status: 'COMPLETED',
+ product_id: kept.id,
+ action: 'UPDATED',
+ processed_at: new Date(),
+ },
+ }),
+ prisma.productImportJob.update({
+ where: { id: accepted.jobId },
+ data: { status: ProductImportJobStatus.PROCESSING },
+ }),
+ ]);
+
+ await (service as any).processJob(accepted.jobId);
+
+ await expect(
+ prisma.productImportJob.findUniqueOrThrow({
+ where: { id: accepted.jobId },
+ select: {
+ status: true,
+ deactivated_items: true,
+ deactivated_product_ids: true,
+ error_message: true,
+ },
+ }),
+ ).resolves.toEqual({
+ status: ProductImportJobStatus.COMPLETED,
+ deactivated_items: 1,
+ deactivated_product_ids: [candidate.id],
+ error_message: null,
+ });
+ });
+
+ it('relata retomada parcial se D surgiu após C ter sido desativado pelo job', async () => {
+ const service = createService();
+ const file = Buffer.from('same-csv');
+ const preview = await service.previewCsvImport(
+ file,
+ ProductType.CAR,
+ specialistId,
+ 'SYNCHRONIZE',
+ );
+ const accepted = await service.createJobFromCsv(
+ file,
+ { id: adminId, role: UserRole.ADMIN } as any,
+ ProductType.CAR,
+ options(preview.synchronizePreviewToken!),
+ );
+ const [kept, candidate] = await Promise.all([
+ prisma.car.findFirstOrThrow({
+ where: {
+ specialist_id: specialistId,
+ identificador: row.identificador,
+ },
+ }),
+ prisma.car.findFirstOrThrow({
+ where: {
+ specialist_id: specialistId,
+ identificador: { startsWith: 'STALE-B-' },
+ },
+ }),
+ ]);
+ await prisma.$transaction([
+ prisma.car.update({
+ where: { id: candidate.id },
+ data: {
+ is_active: false,
+ deactivated_at: new Date(),
+ deactivated_by_sync_job_id: accepted.jobId,
+ },
+ }),
+ prisma.productImportJobItem.updateMany({
+ where: { job_id: accepted.jobId },
+ data: {
+ status: 'COMPLETED',
+ product_id: kept.id,
+ action: 'UPDATED',
+ processed_at: new Date(),
+ },
+ }),
+ prisma.productImportJob.update({
+ where: { id: accepted.jobId },
+ data: { status: ProductImportJobStatus.PROCESSING },
+ }),
+ ]);
+ const productD = await prisma.car.create({
+ data: {
+ specialist_id: specialistId,
+ identificador: `NEW-D-RESUME-${suffix}`,
+ marca: 'New',
+ modelo: 'D',
+ valor: 700000,
+ estado: 'MG',
+ ano: 2026,
+ },
+ });
+
+ await (service as any).processJob(accepted.jobId);
+
+ await expect(
+ prisma.car.findUniqueOrThrow({
+ where: { id: productD.id },
+ select: { is_active: true },
+ }),
+ ).resolves.toEqual({ is_active: true });
+ await expect(
+ prisma.productImportJob.findUniqueOrThrow({
+ where: { id: accepted.jobId },
+ select: {
+ status: true,
+ deactivated_items: true,
+ deactivated_product_ids: true,
+ error_message: true,
+ },
+ }),
+ ).resolves.toMatchObject({
+ status: ProductImportJobStatus.COMPLETED_WITH_ERRORS,
+ deactivated_items: 1,
+ deactivated_product_ids: [candidate.id],
+ error_message: expect.stringContaining('Importação parcial'),
+ });
+ });
});
diff --git a/backend/src/features/products/product-image-preparation.spec.ts b/backend/src/features/products/product-image-preparation.spec.ts
new file mode 100644
index 0000000..0b05aa5
--- /dev/null
+++ b/backend/src/features/products/product-image-preparation.spec.ts
@@ -0,0 +1,79 @@
+import {
+ cleanupPreparedProductImages,
+ prepareProductImages,
+} from './product-image-preparation';
+import { Logger } from '@nestjs/common';
+
+describe('product image preparation', () => {
+ it('remove somente uploads concluídos se um upload posterior falhar', async () => {
+ const s3 = {
+ uploadBase64Image: jest
+ .fn()
+ .mockResolvedValueOnce('cars/product/new-0.jpg')
+ .mockRejectedValueOnce(new Error('upload unavailable')),
+ deleteObjects: jest.fn().mockResolvedValue(undefined),
+ } as any;
+
+ await expect(
+ prepareProductImages(s3, 'cars', 'product', [
+ { data: 'first', is_primary: true },
+ { data: 'second', is_primary: false },
+ ]),
+ ).rejects.toThrow('upload unavailable');
+
+ expect(s3.deleteObjects).toHaveBeenCalledWith([
+ 'cars/product/new-0.jpg',
+ ]);
+ });
+
+ it('não chama S3 para uma compensação vazia', async () => {
+ const s3 = { deleteObjects: jest.fn() } as any;
+
+ await cleanupPreparedProductImages(s3, []);
+
+ expect(s3.deleteObjects).not.toHaveBeenCalled();
+ });
+
+ it('não mascara a falha original se a limpeza compensatória também falhar', async () => {
+ const logSpy = jest.spyOn(Logger.prototype, 'error').mockImplementation();
+ const s3 = {
+ uploadBase64Image: jest
+ .fn()
+ .mockResolvedValueOnce('cars/product/new-0.jpg')
+ .mockRejectedValueOnce(new Error('upload unavailable')),
+ deleteObjects: jest.fn().mockRejectedValue(new Error('cleanup unavailable')),
+ } as any;
+
+ await expect(
+ prepareProductImages(s3, 'cars', 'product', [
+ { data: 'first', is_primary: true },
+ { data: 'second', is_primary: false },
+ ]),
+ ).rejects.toThrow('upload unavailable');
+ logSpy.mockRestore();
+ });
+
+ it('gera chaves distintas para preparações concorrentes mesmo no mesmo milissegundo', async () => {
+ const dateSpy = jest.spyOn(Date, 'now').mockReturnValue(123456789);
+ const uploadedKeys: string[] = [];
+ const s3 = {
+ uploadBase64Image: jest.fn(async (_data: string, key: string) => {
+ uploadedKeys.push(key);
+ return key;
+ }),
+ deleteObjects: jest.fn(),
+ } as any;
+
+ await Promise.all([
+ prepareProductImages(s3, 'cars', 'same-product', [
+ { data: 'first', is_primary: true },
+ ]),
+ prepareProductImages(s3, 'cars', 'same-product', [
+ { data: 'second', is_primary: true },
+ ]),
+ ]);
+
+ expect(new Set(uploadedKeys).size).toBe(2);
+ dateSpy.mockRestore();
+ });
+});
diff --git a/backend/src/features/products/product-image-preparation.ts b/backend/src/features/products/product-image-preparation.ts
new file mode 100644
index 0000000..d9dd905
--- /dev/null
+++ b/backend/src/features/products/product-image-preparation.ts
@@ -0,0 +1,56 @@
+import { S3Service } from 'src/aws/s3.service';
+import { Logger } from '@nestjs/common';
+import { randomUUID } from 'node:crypto';
+
+const logger = new Logger('ProductImagePreparation');
+
+export type ProductImageInput = {
+ data: string;
+ is_primary: boolean;
+};
+
+export type PreparedProductImage = {
+ image_url: string;
+ is_primary: boolean;
+};
+
+export async function prepareProductImages(
+ s3Service: S3Service,
+ prefix: string,
+ productId: string,
+ images: ProductImageInput[] = [],
+): Promise {
+ const prepared: PreparedProductImage[] = [];
+ try {
+ for (let index = 0; index < images.length; index += 1) {
+ const key = `${prefix}/${productId}/${randomUUID()}-${index}.jpg`;
+ const imageUrl = await s3Service.uploadBase64Image(
+ images[index].data,
+ key,
+ );
+ prepared.push({
+ image_url: imageUrl,
+ is_primary: images[index].is_primary,
+ });
+ }
+ return prepared;
+ } catch (error) {
+ await cleanupPreparedProductImages(s3Service, prepared);
+ throw error;
+ }
+}
+
+export async function cleanupPreparedProductImages(
+ s3Service: S3Service,
+ prepared: PreparedProductImage[],
+): Promise {
+ if (prepared.length === 0) return;
+ try {
+ await s3Service.deleteObjects(prepared.map((image) => image.image_url));
+ } catch (error) {
+ logger.error(
+ `Falha ao compensar ${prepared.length} upload(s) de produto`,
+ error instanceof Error ? error.stack : undefined,
+ );
+ }
+}
diff --git a/backend/src/features/products/product-services-update-errors.spec.ts b/backend/src/features/products/product-services-update-errors.spec.ts
new file mode 100644
index 0000000..c7f930a
--- /dev/null
+++ b/backend/src/features/products/product-services-update-errors.spec.ts
@@ -0,0 +1,59 @@
+import { ConflictException, NotFoundException } from '@nestjs/common';
+import { Prisma, ProductCurrency } from '@prisma/client';
+import { CarsService } from '../cars/cars.service';
+import { BoatsService } from '../boats/boats.service';
+import { AircraftsService } from '../aircrafts/aircrafts.service';
+
+type ServiceFactory = (prisma: any) => {
+ update(id: string, dto: any): Promise;
+};
+
+const services: Array<[string, string, ServiceFactory]> = [
+ ['carro', 'car', (prisma) => new CarsService(prisma, {} as any)],
+ ['barco', 'boat', (prisma) => new BoatsService(prisma, {} as any)],
+ ['aeronave', 'aircraft', (prisma) => new AircraftsService(prisma, {} as any)],
+];
+
+describe.each(services)('%s — preserva erros HTTP no update', (_label, delegateName, factory) => {
+ const productId = '11111111-1111-4111-8111-111111111111';
+
+ function prismaWith(currentProduct: unknown, activeProcess: unknown) {
+ const delegate = {
+ findUnique: jest.fn().mockResolvedValue(currentProduct),
+ update: jest.fn(),
+ };
+ const tx = {
+ $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]),
+ [delegateName]: delegate,
+ process: { findFirst: jest.fn().mockResolvedValue(activeProcess) },
+ };
+ return {
+ ...tx,
+ $transaction: jest.fn(async (callback: any) => callback(tx)),
+ };
+ }
+
+ it('mantém NotFoundException em vez de converter para 500', async () => {
+ const service = factory(prismaWith(null, null));
+
+ await expect(service.update(productId, { modelo: 'Novo' })).rejects.toBeInstanceOf(
+ NotFoundException,
+ );
+ });
+
+ it('mantém ConflictException da trava monetária em vez de converter para 500', async () => {
+ const prisma = prismaWith(
+ {
+ id: productId,
+ valor: new Prisma.Decimal('100'),
+ currency: ProductCurrency.BRL,
+ },
+ { id: 'process-1' },
+ );
+ const service = factory(prisma);
+
+ await expect(service.update(productId, { valor: 200 })).rejects.toBeInstanceOf(
+ ConflictException,
+ );
+ });
+});
diff --git a/frontend/src/pages/admin/SpecialistJourneyProductsPage.test.tsx b/frontend/src/pages/admin/SpecialistJourneyProductsPage.test.tsx
new file mode 100644
index 0000000..5178c34
--- /dev/null
+++ b/frontend/src/pages/admin/SpecialistJourneyProductsPage.test.tsx
@@ -0,0 +1,71 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { MemoryRouter } from "react-router-dom";
+import SpecialistJourneyProductsPage from "./SpecialistJourneyProductsPage";
+import {
+ getAdminSpecialistProducts,
+ previewAdminCatalogCsv,
+} from "../../services/admin-specialist-journey.service";
+
+vi.mock("../../contexts/AdminSpecialistJourneyContext", () => ({
+ useAdminSpecialistJourney: () => ({
+ targetSpecialistId: "specialist-1",
+ specialist: { id: "specialist-1", name: "Ana", speciality: "CAR" },
+ }),
+}));
+
+vi.mock("../../services/admin-specialist-journey.service", async (original) => ({
+ ...(await original()),
+ getAdminSpecialistProducts: vi.fn(),
+ previewAdminCatalogCsv: vi.fn(),
+ importAdminCatalogCsv: vi.fn(),
+}));
+
+afterEach(cleanup);
+
+describe("SpecialistJourneyProductsPage", () => {
+ beforeEach(() => {
+ vi.mocked(getAdminSpecialistProducts).mockResolvedValue({
+ products: [],
+ pagination: { current_page: 1, total_pages: 1 } as any,
+ });
+ vi.mocked(previewAdminCatalogCsv).mockResolvedValue({
+ productType: "CAR",
+ targetSpecialistId: "specialist-1",
+ mode: "SYNCHRONIZE",
+ requiresExplicitConfirmation: true,
+ synchronizePreviewToken: "signed-token",
+ impact: {
+ incomingItems: 4,
+ activeItemsBefore: 8,
+ matchingItems: 3,
+ newOrReactivatedItems: 1,
+ deactivationCandidates: 5,
+ },
+ });
+ });
+
+ it("exibe exatamente o impacto devolvido pela prévia de sincronização", async () => {
+ render(
+
+
+ ,
+ );
+
+ fireEvent.change(screen.getByLabelText("Modo da importação"), {
+ target: { value: "SYNCHRONIZE" },
+ });
+ fireEvent.change(screen.getByLabelText("Arquivo CSV"), {
+ target: {
+ files: [new File(["csv"], "catalog.csv", { type: "text/csv" })],
+ },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Pré-visualizar impacto" }));
+
+ expect(
+ await screen.findByText(/4 linhas · 1 criações\/reativações · 3 atualizações/),
+ ).toBeTruthy();
+ expect(screen.getByText("5 desativações")).toBeTruthy();
+ });
+});
diff --git a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx
index e7168fd..c4f2c92 100644
--- a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx
+++ b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx
@@ -172,7 +172,7 @@ export default function SpecialistJourneyProductsPage() {
{preview && (
- {preview.impact.csvRows} linhas · {preview.impact.wouldCreate} criações · {preview.impact.wouldUpdate} atualizações ·