From fcd2e5e1e6501ef48447b3fa6c7061c1b8631534 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Tue, 13 Oct 2026 16:20:02 -0300 Subject: [PATCH 1/6] docs: plan Calendly modal removal --- ...026-10-13-remover-modal-global-calendly.md | 143 ++++++++++++++++++ ...13-remover-modal-global-calendly-design.md | 28 ++++ 2 files changed, 171 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-13-remover-modal-global-calendly.md create mode 100644 docs/superpowers/specs/2026-10-13-remover-modal-global-calendly-design.md diff --git a/docs/superpowers/plans/2026-10-13-remover-modal-global-calendly.md b/docs/superpowers/plans/2026-10-13-remover-modal-global-calendly.md new file mode 100644 index 0000000..61eba7e --- /dev/null +++ b/docs/superpowers/plans/2026-10-13-remover-modal-global-calendly.md @@ -0,0 +1,143 @@ +# Remove Global Calendly Modal 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:** Remover a interrupção global do Calendly e deixar explícito que especialistas podem anunciar produtos sem conectar uma conta. + +**Architecture:** `MainLayout` deixa de montar qualquer gate ou lembrete global do Calendly. A oferta de conexão permanece no cadastro concluído e no perfil, enquanto testes de composição protegem o layout e a mensagem opcional. + +**Tech Stack:** React 19, TypeScript 5.8, Vitest 4, Testing Library. + +## Global Constraints + +- Calendly permanece opcional e limitado a perfil e agendamentos. +- Cadastro manual e importação de produtos continuam inalterados. +- Executar Vitest com no máximo dois workers. +- Não alterar o backend. + +--- + +### Task 1: Remover o lembrete global do layout + +**Files:** +- Create: `frontend/src/layouts/MainLayout.test.tsx` +- Modify: `frontend/src/layouts/MainLayout.tsx` +- Delete: `frontend/src/components/calendly/RequireCalendlyModal.tsx` +- Delete: `frontend/src/components/calendly/RequireCalendlyModal.test.tsx` + +**Interfaces:** +- Consumes: `AuthContext` e `AppContext` já usados por `MainLayout`. +- Produces: layout que renderiza conteúdo de especialista sem consultar `getCalendlyOAuthStatus`. + +- [ ] **Step 1: Escrever o teste de regressão** + +Criar um teste jsdom que renderiza `MainLayout` com um usuário `SPECIALIST`, aguarda os efeitos React e verifica: + +```ts +expect(getCalendlyOAuthStatus).not.toHaveBeenCalled(); +expect(screen.queryByRole("dialog", { name: /Conecte seu Calendly/i })).toBeNull(); +``` + +- [ ] **Step 2: Confirmar a falha** + +Run: `cd frontend && npm test -- src/layouts/MainLayout.test.tsx --pool=forks --maxWorkers=2` + +Expected: FAIL porque o layout atual consulta o status OAuth e monta `RequireCalendlyModal`. + +- [ ] **Step 3: Implementar a correção mínima** + +Remover de `MainLayout.tsx`: + +```ts +import RequireCalendlyModal from "../components/calendly/RequireCalendlyModal"; +``` + +e: + +```tsx +{user?.role === "SPECIALIST" && } +``` + +Apagar o componente e seu teste, pois não restarão consumidores. + +- [ ] **Step 4: Confirmar o teste verde** + +Run: `cd frontend && npm test -- src/layouts/MainLayout.test.tsx --pool=forks --maxWorkers=2` + +Expected: PASS. + +### Task 2: Corrigir a mensagem pós-cadastro + +**Files:** +- Modify: `frontend/src/pages/auth/RegisterSpecialistPage.test.tsx` +- Modify: `frontend/src/pages/auth/RegisterSpecialistPage.tsx` + +**Interfaces:** +- Consumes: retorno bem-sucedido de `registerSpecialist`. +- Produces: confirmação que apresenta o Calendly como opção de automação de agendamentos. + +- [ ] **Step 1: Escrever o teste de regressão** + +Preencher o formulário válido, concluir o cadastro e verificar: + +```ts +expect(await screen.findByText(/Calendly é opcional/i)).toBeTruthy(); +expect(screen.queryByText(/para poder anunciar produtos/i)).toBeNull(); +``` + +- [ ] **Step 2: Confirmar a falha** + +Run: `cd frontend && npm test -- src/pages/auth/RegisterSpecialistPage.test.tsx --pool=forks --maxWorkers=2` + +Expected: FAIL porque a mensagem atual afirma que a conexão é necessária para anunciar. + +- [ ] **Step 3: Atualizar somente a mensagem** + +Usar o texto: + +```tsx +O Calendly é opcional. Conecte sua conta se quiser automatizar o agendamento de reuniões com clientes. +``` + +- [ ] **Step 4: Confirmar o teste verde** + +Run: `cd frontend && npm test -- src/pages/auth/RegisterSpecialistPage.test.tsx --pool=forks --maxWorkers=2` + +Expected: PASS. + +### Task 3: Verificar e preparar o PR + +**Files:** +- Verify: todos os arquivos alterados nas Tasks 1 e 2. + +**Interfaces:** +- Consumes: correção completa e testes focados verdes. +- Produces: branch verificável e PR contra `develop`. + +- [ ] **Step 1: Executar os testes frontend** + +Run: `cd frontend && npm test -- --pool=forks --maxWorkers=2` + +Expected: todas as suítes passam. + +- [ ] **Step 2: Executar o build** + +Run: `cd frontend && npm run build` + +Expected: TypeScript e Vite concluem com código 0. + +- [ ] **Step 3: Revisar o diff e referências restantes** + +Run: `git diff --check && rg -n "RequireCalendlyModal" frontend/src || true` + +Expected: nenhum erro de whitespace e nenhuma referência restante. + +- [ ] **Step 4: Commit, push e PR** + +```bash +git add docs/superpowers frontend/src +git commit -m "fix(frontend): remove Calendly modal from product flow" +git push -u origin codex/fix-calendly-product-modal +gh pr create --base develop --head codex/fix-calendly-product-modal +``` + diff --git a/docs/superpowers/specs/2026-10-13-remover-modal-global-calendly-design.md b/docs/superpowers/specs/2026-10-13-remover-modal-global-calendly-design.md new file mode 100644 index 0000000..611e0a2 --- /dev/null +++ b/docs/superpowers/specs/2026-10-13-remover-modal-global-calendly-design.md @@ -0,0 +1,28 @@ +# Remover o modal global de Calendly do fluxo de produtos + +## Objetivo + +Permitir que o especialista navegue e cadastre produtos sem qualquer interrupção relacionada ao Calendly. A integração continua opcional e acessível no perfil e nos fluxos de agendamento. + +## Causa raiz + +Os endpoints de produtos e a própria página de cadastro já não exigem Calendly. Porém, `MainLayout` ainda monta `RequireCalendlyModal` para todo especialista. Como a página de novo produto usa esse layout, o modal abre por cima do formulário e cria uma exigência prática antes que o usuário consiga interagir com o cadastro. O teste atual de `ProductFormPage` monta somente a página isolada e, por isso, não cobre essa composição. + +## Solução + +- Remover `RequireCalendlyModal` de `MainLayout` e apagar o componente sem consumidores. +- Manter a configuração do Calendly no perfil e os recursos de agendamento inalterados. +- Atualizar a confirmação do cadastro de especialista para declarar que o Calendly é opcional, sem associá-lo à permissão para anunciar produtos. +- Adicionar um teste de `MainLayout` com especialista sem Calendly para garantir que o layout não consulte o status OAuth nem apresente um diálogo global. +- Expandir o teste do cadastro de especialista para cobrir a mensagem exibida após o sucesso. + +## Tratamento de erros + +Nenhum novo tratamento é necessário. Ao remover a consulta global, falhas no endpoint de status do Calendly deixam de interferir na navegação do especialista. Erros do OAuth continuam tratados onde a conexão é iniciada explicitamente. + +## Fora do escopo + +- Alterar OAuth, webhooks ou sincronização do Calendly. +- Alterar agendamentos ou a página de perfil. +- Alterar autorização, validação ou persistência de produtos no backend. + From d9d3417c1f3efd2b0c8a3a0236a02a1ef51bb458 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Tue, 13 Oct 2026 16:20:13 -0300 Subject: [PATCH 2/6] fix(frontend): remove global Calendly blocker --- .../calendly/RequireCalendlyModal.test.tsx | 67 ------------- .../calendly/RequireCalendlyModal.tsx | 94 ------------------- frontend/src/layouts/MainLayout.test.tsx | 91 ++++++++++++++++++ frontend/src/layouts/MainLayout.tsx | 2 - .../auth/RegisterSpecialistPage.test.tsx | 47 +++++++++- .../src/pages/auth/RegisterSpecialistPage.tsx | 3 +- 6 files changed, 138 insertions(+), 166 deletions(-) delete mode 100644 frontend/src/components/calendly/RequireCalendlyModal.test.tsx delete mode 100644 frontend/src/components/calendly/RequireCalendlyModal.tsx create mode 100644 frontend/src/layouts/MainLayout.test.tsx diff --git a/frontend/src/components/calendly/RequireCalendlyModal.test.tsx b/frontend/src/components/calendly/RequireCalendlyModal.test.tsx deleted file mode 100644 index 87d6b06..0000000 --- a/frontend/src/components/calendly/RequireCalendlyModal.test.tsx +++ /dev/null @@ -1,67 +0,0 @@ -// @vitest-environment jsdom - -import { - cleanup, - fireEvent, - render, - screen, - waitFor, -} from "@testing-library/react"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import RequireCalendlyModal from "./RequireCalendlyModal"; -import { getCalendlyOAuthStatus } from "../../services/appointments.service"; - -vi.mock("../../store/authStateManager", () => ({ - useAuth: () => ({ - user: { id: "specialist-1", role: "SPECIALIST" }, - }), -})); - -vi.mock("../../services/appointments.service", () => ({ - getCalendlyOAuthStatus: vi.fn(), - getCalendlyAuthorizeUrl: vi.fn(), -})); - -describe("RequireCalendlyModal", () => { - beforeEach(() => { - sessionStorage.clear(); - vi.mocked(getCalendlyOAuthStatus).mockResolvedValue({ - connected: false, - calendly_user_uri: null, - expires_at: null, - is_active: false, - }); - }); - - afterEach(() => { - cleanup(); - vi.clearAllMocks(); - }); - - it("explains that Calendly is optional and allows continuing", async () => { - render(); - - expect( - await screen.findByRole("button", { name: "Continuar sem Calendly" }), - ).toBeTruthy(); - expect(screen.getByText(/Calendly é opcional/i)).toBeTruthy(); - expect(screen.queryByText(/fica bloqueado/i)).toBeNull(); - }); - - it("dismisses the reminder for the current browser session", async () => { - render(); - - fireEvent.click( - await screen.findByRole("button", { name: "Continuar sem Calendly" }), - ); - - expect(sessionStorage.getItem("calendly-modal-dismissed-session")).toBe( - "1", - ); - await waitFor(() => { - expect( - screen.queryByRole("button", { name: "Continuar sem Calendly" }), - ).toBeNull(); - }); - }); -}); diff --git a/frontend/src/components/calendly/RequireCalendlyModal.tsx b/frontend/src/components/calendly/RequireCalendlyModal.tsx deleted file mode 100644 index 5913e96..0000000 --- a/frontend/src/components/calendly/RequireCalendlyModal.tsx +++ /dev/null @@ -1,94 +0,0 @@ -import { useEffect, useState } from "react"; -import { Calendar } from "lucide-react"; -import { useAuth } from "../../store/authStateManager"; -import { - getCalendlyOAuthStatus, - getCalendlyAuthorizeUrl, -} from "../../services/appointments.service"; -import { Dialog, DialogContent } from "../ui/dialog"; -import { Alert } from "../ui/alert"; -import Button from "../ui/button"; - -const DISMISS_KEY = "calendly-modal-dismissed-session"; - -export default function RequireCalendlyModal() { - const { user } = useAuth(); - const [open, setOpen] = useState(false); - const [loading, setLoading] = useState(false); - const [error, setError] = useState(null); - - useEffect(() => { - if (user?.role !== "SPECIALIST") return; - if (sessionStorage.getItem(DISMISS_KEY) === "1") return; - - let cancelled = false; - getCalendlyOAuthStatus() - .then((status) => { - if (!cancelled && !status.is_active) { - setOpen(true); - } - }) - .catch(() => { - if (!cancelled) setOpen(true); - }); - - return () => { - cancelled = true; - }; - }, [user?.id, user?.role]); - - const handleConnect = async () => { - setLoading(true); - setError(null); - try { - const url = await getCalendlyAuthorizeUrl(); - window.location.href = url; - } catch (err) { - const e = err as { friendlyMessage?: string }; - setError(e.friendlyMessage || "Erro ao iniciar conexão com o Calendly."); - setLoading(false); - } - }; - - const handleDismiss = () => { - sessionStorage.setItem(DISMISS_KEY, "1"); - setOpen(false); - }; - - return ( - { if (!next) handleDismiss(); }}> - - - Conecte seu Calendly - - } - > -
-

- O Calendly é opcional e facilita o agendamento automático de - reuniões com seus clientes. -

- -

- Você pode continuar sem Calendly, cadastrar produtos e receber - solicitações normalmente pela plataforma. -

- - {error && {error}} - -
- - -
-
-
-
- ); -} diff --git a/frontend/src/layouts/MainLayout.test.tsx b/frontend/src/layouts/MainLayout.test.tsx new file mode 100644 index 0000000..fc14170 --- /dev/null +++ b/frontend/src/layouts/MainLayout.test.tsx @@ -0,0 +1,91 @@ +// @vitest-environment jsdom + +import { act, cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { AppContext, type AppContextProps } from "../contexts/AppContext"; +import { + AuthContext, + type AuthContextProps, +} from "../contexts/AuthContext"; +import { getCalendlyOAuthStatus } from "../services/appointments.service"; +import MainLayout from "./MainLayout"; + +const state = vi.hoisted(() => ({ + user: { + id: "specialist-1", + name: "Especialista", + surname: "Teste", + email: "specialist@example.com", + cpf: "12345678000199", + rg: "123456789", + role: "SPECIALIST" as const, + speciality: "CAR" as const, + }, +})); + +vi.mock("./Header", () => ({ default: () =>
Cabeçalho
})); +vi.mock("./Sidebar", () => ({ default: () => })); +vi.mock("../hooks/use-is-mobile", () => ({ useIsMobile: () => false })); +vi.mock("../store/authStateManager", () => ({ + useAuth: () => ({ user: state.user }), +})); +vi.mock("../services/appointments.service", () => ({ + getCalendlyOAuthStatus: vi.fn().mockResolvedValue({ + connected: false, + calendly_user_uri: null, + expires_at: null, + is_active: false, + }), + getCalendlyAuthorizeUrl: vi.fn(), +})); + +const appContext: AppContextProps = { + isSidebarCollapsed: false, + setSidebarCollapsed: vi.fn(), + isSidebarDesktopCollapsed: false, + toggleSidebarDesktopCollapsed: vi.fn(), + searchTerm: "", + setSearchTerm: vi.fn(), +}; + +const authContext: AuthContextProps = { + user: state.user, + accessToken: "token", + login: vi.fn(), + register: vi.fn(), + validateReferralToken: vi.fn(), + logout: vi.fn(), + loading: false, + refreshUser: vi.fn(), + verifyToken: vi.fn(), +}; + +afterEach(() => { + cleanup(); + sessionStorage.clear(); + vi.clearAllMocks(); +}); + +describe("MainLayout", () => { + it("não consulta nem bloqueia o especialista com um modal global do Calendly", async () => { + render( + + + +
Formulário de produto
+
+
+
, + ); + + await act(async () => { + await Promise.resolve(); + }); + + expect(screen.getByText("Formulário de produto")).toBeTruthy(); + expect(getCalendlyOAuthStatus).not.toHaveBeenCalled(); + expect( + screen.queryByRole("dialog", { name: /Conecte seu Calendly/i }), + ).toBeNull(); + }); +}); diff --git a/frontend/src/layouts/MainLayout.tsx b/frontend/src/layouts/MainLayout.tsx index 70bbcb0..af1b848 100644 --- a/frontend/src/layouts/MainLayout.tsx +++ b/frontend/src/layouts/MainLayout.tsx @@ -4,7 +4,6 @@ import { AppContext } from "../contexts/AppContext"; import { useIsMobile } from "../hooks/use-is-mobile"; import { AuthContext } from "../contexts/AuthContext"; -import RequireCalendlyModal from "../components/calendly/RequireCalendlyModal"; import RequireGoogleMeetModal from "../components/meetings/RequireGoogleMeetModal"; interface MainLayoutProps { @@ -48,7 +47,6 @@ import RequireGoogleMeetModal from "../components/meetings/RequireGoogleMeetModa {children} - {user?.role === "SPECIALIST" && } {user?.role === "ADMIN" && } ); diff --git a/frontend/src/pages/auth/RegisterSpecialistPage.test.tsx b/frontend/src/pages/auth/RegisterSpecialistPage.test.tsx index 9bfe0a3..cb9f267 100644 --- a/frontend/src/pages/auth/RegisterSpecialistPage.test.tsx +++ b/frontend/src/pages/auth/RegisterSpecialistPage.test.tsx @@ -1,8 +1,11 @@ // @vitest-environment jsdom -import { cleanup, render, screen } from "@testing-library/react"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import RegisterSpecialistPage from "./RegisterSpecialistPage"; -import { validateSpecialistInvite } from "../../services/specialists.service"; +import { + registerSpecialist, + validateSpecialistInvite, +} from "../../services/specialists.service"; vi.mock("react-router-dom", () => ({ useNavigate: () => vi.fn(), @@ -55,4 +58,44 @@ describe("RegisterSpecialistPage", () => { ), ).toBeTruthy(); }); + + it("apresenta o Calendly como opcional após criar a conta", async () => { + vi.mocked(validateSpecialistInvite).mockResolvedValue({ + email: "especialista@example.com", + speciality: "CAR", + commission_rate: 25, + }); + vi.mocked(registerSpecialist).mockResolvedValue({ + access_token: "access-token", + user: { + id: "specialist-1", + name: "Maria", + surname: "Silva", + email: "especialista@example.com", + cpf: "12345678000199", + rg: "123456789", + role: "SPECIALIST", + speciality: "CAR", + }, + }); + + const { container } = render(); + + await screen.findByText("Especialidade:"); + const textInputs = container.querySelectorAll( + 'input[type="text"]:not([readonly])', + ); + fireEvent.change(textInputs[0], { target: { value: "Maria" } }); + fireEvent.change(textInputs[1], { target: { value: "Silva" } }); + fireEvent.change(textInputs[2], { target: { value: "12345678000199" } }); + fireEvent.change(textInputs[3], { target: { value: "123456789" } }); + fireEvent.change(textInputs[4], { target: { value: "11999999999" } }); + fireEvent.change(container.querySelector('input[type="password"]')!, { + target: { value: "senha123" }, + }); + fireEvent.click(screen.getByRole("button", { name: "Criar conta" })); + + expect(await screen.findByText(/Calendly é opcional/i)).toBeTruthy(); + expect(screen.queryByText(/para poder anunciar produtos/i)).toBeNull(); + }); }); diff --git a/frontend/src/pages/auth/RegisterSpecialistPage.tsx b/frontend/src/pages/auth/RegisterSpecialistPage.tsx index 7862811..6f92c3b 100644 --- a/frontend/src/pages/auth/RegisterSpecialistPage.tsx +++ b/frontend/src/pages/auth/RegisterSpecialistPage.tsx @@ -162,7 +162,8 @@ export default function RegisterSpecialistPage() {

Sua conta de especialista em{" "} {speciality ? SPECIALITY_LABEL[speciality] : ""} foi criada. - Conecte seu Calendly para poder anunciar produtos na plataforma. + O Calendly é opcional. Conecte sua conta se quiser automatizar o + agendamento de reuniões com clientes.

{calendlyError && (

{calendlyError}

From 3f9bc35f25213a6dfbbd7baf3902fcf5e50497b3 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Tue, 13 Oct 2026 16:23:43 -0300 Subject: [PATCH 3/6] fix(import): handle empty product cells per row --- .../product-import-jobs.service.spec.ts | 159 ++++++++++++++++++ .../product-import-jobs.service.ts | 90 +++++++--- 2 files changed, 223 insertions(+), 26 deletions(-) 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 218b4e5..75efd7a 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,165 @@ import { ProductImportJobsService } from './product-import-jobs.service'; import { Prisma, ProductCurrency, ProductType } from '@prisma/client'; describe('ProductImportJobsService', () => { + const validCarRow = { + marca: 'Ferrari', + modelo: 'Roma', + identificador: 'FERRARI-ROMA-1', + valor: '1000000', + estado: 'SP', + ano: '2024', + }; + + it.each([ + ['identificador', '-', 'Identificador do veículo faltando'], + ['marca', ' - ', 'Marca do veículo faltando'], + ['modelo', '-', 'Nome do veículo faltando'], + ['valor', ' ', 'Valor do veículo faltando'], + ['estado', '-', 'Estado do veículo faltando'], + ['ano', ' - ', 'Ano do veículo faltando'], + ])( + 'trata %s com marcador de ausência como erro natural da linha', + async (field, emptyValue, expectedMessage) => { + const prisma = { + car: { findFirst: jest.fn(), create: jest.fn() }, + } as any; + const service = new ProductImportJobsService( + prisma, + {} as any, + {} as any, + ); + + await expect( + (service as any).upsertProductFromRow( + ProductType.CAR, + { ...validCarRow, [field]: emptyValue }, + '00000000-0000-4000-8000-000000000001', + ), + ).rejects.toThrow(expectedMessage); + expect(prisma.car.create).not.toHaveBeenCalled(); + }, + ); + + it('trata hífen em campos opcionais como célula não preenchida', async () => { + const create = jest.fn().mockResolvedValue({ id: 'uuid-1' }); + const prisma = { + car: { findFirst: jest.fn().mockResolvedValue(null), create }, + } as any; + const service = new ProductImportJobsService(prisma, {} as any, {} as any); + + await expect( + (service as any).upsertProductFromRow( + ProductType.CAR, + { + ...validCarRow, + currency: '-', + cor: ' - ', + km: '-', + cambio: ' ', + }, + '00000000-0000-4000-8000-000000000001', + ), + ).resolves.toEqual({ productId: 'uuid-1', action: 'CREATED' }); + + expect(create).toHaveBeenCalledWith({ + data: expect.objectContaining({ + currency: undefined, + cor: undefined, + km: undefined, + cambio: undefined, + }), + }); + }); + + it('não inativa produtos ausentes quando alguma linha falha', async () => { + const prisma = { + productImportJob: { + findUnique: jest.fn().mockResolvedValue({ + id: 'job-1', + product_type: ProductType.CAR, + specialist_id: '00000000-0000-4000-8000-000000000001', + status: 'PENDING', + started_at: null, + items: [ + { + id: 'item-1', + status: 'PENDING', + payload: validCarRow, + folder_url: null, + }, + { + id: 'item-2', + status: 'PENDING', + payload: { ...validCarRow, modelo: '-' }, + folder_url: null, + }, + ], + }), + update: jest.fn().mockResolvedValue({}), + }, + productImportJobItem: { + update: jest.fn().mockResolvedValue({}), + }, + car: { + findFirst: jest.fn().mockResolvedValue(null), + create: jest.fn().mockResolvedValue({ id: 'product-1' }), + }, + } as any; + const service = new ProductImportJobsService(prisma, {} as any, {} as any); + 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-1'); + + expect(deactivateMissingProducts).not.toHaveBeenCalled(); + expect(refreshJobCounters).toHaveBeenCalledWith('job-1', { + deactivatedIds: [], + reactivatedCount: 0, + }); + expect(prisma.productImportJobItem.update).toHaveBeenCalledWith({ + where: { id: 'item-2' }, + data: expect.objectContaining({ + status: 'FAILED', + error_message: 'Nome do veículo faltando', + }), + }); + }); + + it('relata a linha não importada com erro em linguagem natural', () => { + const service = new ProductImportJobsService( + {} as any, + {} as any, + {} as any, + ); + + const result = (service as any).buildImportResponse([ + { + row_number: 7, + status: 'FAILED', + payload: { ...validCarRow, modelo: '-' }, + action: null, + product_id: null, + error_message: 'Nome do veículo faltando', + warnings: null, + }, + ]); + + expect(result).toMatchObject({ + success: false, + errorCount: 1, + errorRows: [ + { + row: 7, + reason: 'Nome do veículo faltando', + }, + ], + }); + }); + it('lanca erro quando identificador vem vazio', async () => { const prisma = { car: { findFirst: jest.fn(), create: jest.fn() } } as any; const service = new ProductImportJobsService(prisma, {} as any, {} 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 198fc14..9559e35 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 @@ -48,6 +48,15 @@ type UpsertResult = { reactivated?: boolean; }; +const REQUIRED_PRODUCT_FIELDS = [ + { key: 'identificador', label: 'Identificador do veículo' }, + { key: 'marca', label: 'Marca do veículo' }, + { key: 'modelo', label: 'Nome do veículo' }, + { key: 'valor', label: 'Valor do veículo' }, + { key: 'estado', label: 'Estado do veículo' }, + { key: 'ano', label: 'Ano do veículo' }, +] as const; + @Injectable() export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(ProductImportJobsService.name); @@ -107,6 +116,8 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }); } + const normalizedRows = rows.map((row) => this.normalizeProductRow(row)); + let createdJob; try { createdJob = await this.prisma.productImportJob.create({ @@ -114,10 +125,10 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { product_type: productType, specialist_id: user.id, status: ProductImportJobStatus.PENDING, - total_items: rows.length, + total_items: normalizedRows.length, items: { createMany: { - data: rows.map((row, index) => ({ + data: normalizedRows.map((row, index) => ({ row_number: index + 2, payload: row, folder_url: row.folder_url?.trim() || null, @@ -304,6 +315,9 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { try { const seenProductIds = new Set(); let reactivatedCount = 0; + let hasFailedItems = job.items.some( + (item) => item.status === ProductImportItemStatus.FAILED, + ); for (const item of job.items) { if ( @@ -373,6 +387,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }, }); } catch (error) { + hasFailedItems = true; await this.prisma.productImportJobItem.update({ where: { id: item.id }, data: { @@ -385,12 +400,14 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { } } - const deactivatedIds = await this.deactivateMissingProducts( - job.product_type, - job.specialist_id, - seenProductIds, - job.id, - ); + const deactivatedIds = hasFailedItems + ? [] + : await this.deactivateMissingProducts( + job.product_type, + job.specialist_id, + seenProductIds, + job.id, + ); await this.refreshJobCounters(jobId, { deactivatedIds, @@ -549,17 +566,15 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { row: ImportParsedRow, specialistId: string, ): Promise { + row = this.normalizeProductRow(row); + this.validateRequiredProductFields(row); + // Normaliza uma vez só: a busca do produto existente usava o valor com // trim e a gravação usava o valor cru, então " ABC " seria gravado como // " ABC " e nunca mais reencontrado — cada reimport criaria uma duplicata. // Hoje o parseCsv já entrega tudo trimado, mas a divergência ficava // armada para qualquer chamador que não passe pelo CSV. - const identificador = row.identificador?.trim(); - if (!identificador) { - throw new BadRequestException( - 'identificador é obrigatório e não pode ser vazio', - ); - } + const identificador = row.identificador; if (productType === ProductType.CAR) { const data = { @@ -567,9 +582,9 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { modelo: row.modelo, identificador, valor: Number(row.valor), - currency: (row.currency || ProductCurrency.BRL) - .trim() - .toUpperCase() as ProductCurrency, + currency: row.currency + ? (row.currency.toUpperCase() as ProductCurrency) + : undefined, estado: row.estado, ano: Number(row.ano), cor: row.cor || undefined, @@ -591,7 +606,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }); if (existing) { - const { specialist_id, ...updateData } = data; + const { specialist_id: _specialistId, ...updateData } = data; const reactivated = !existing.is_active; await updateProductWithMonetaryLock(this.prisma, { productType: ProductType.CAR, @@ -619,9 +634,9 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { modelo: row.modelo, identificador, valor: Number(row.valor), - currency: (row.currency || ProductCurrency.BRL) - .trim() - .toUpperCase() as ProductCurrency, + currency: row.currency + ? (row.currency.toUpperCase() as ProductCurrency) + : undefined, estado: row.estado, ano: Number(row.ano), fabricante: row.fabricante || undefined, @@ -646,7 +661,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }); if (existing) { - const { specialist_id, ...updateData } = data; + const { specialist_id: _specialistId, ...updateData } = data; const reactivated = !existing.is_active; await updateProductWithMonetaryLock(this.prisma, { productType: ProductType.BOAT, @@ -673,9 +688,9 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { modelo: row.modelo, identificador, valor: Number(row.valor), - currency: (row.currency || ProductCurrency.BRL) - .trim() - .toUpperCase() as ProductCurrency, + currency: row.currency + ? (row.currency.toUpperCase() as ProductCurrency) + : undefined, estado: row.estado, ano: Number(row.ano), categoria: row.categoria || undefined, @@ -695,7 +710,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }); if (existing) { - const { specialist_id, ...updateData } = data; + const { specialist_id: _specialistId, ...updateData } = data; const reactivated = !existing.is_active; await updateProductWithMonetaryLock(this.prisma, { productType: ProductType.AIRCRAFT, @@ -717,6 +732,29 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { return { productId: created.id, action: 'CREATED' }; } + private normalizeProductRow(row: ImportParsedRow): ImportParsedRow { + return Object.fromEntries( + Object.entries(row).map(([key, rawValue]) => { + const value = String(rawValue ?? '').trim(); + return [key, value === '-' ? '' : value]; + }), + ); + } + + private validateRequiredProductFields(row: ImportParsedRow): void { + const missingFields = REQUIRED_PRODUCT_FIELDS.filter( + ({ key }) => !row[key], + ); + + if (missingFields.length === 0) { + return; + } + + throw new BadRequestException( + missingFields.map(({ label }) => `${label} faltando`).join('; '), + ); + } + private async validatePayload( payload: Record, dtoClass: new () => T, From 1740273b53384d8034782ba870c59c84dad11d88 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Tue, 13 Oct 2026 16:27:08 -0300 Subject: [PATCH 4/6] fix(appointments): allow consultancy with existing process --- .../appointments/appointments.service.spec.ts | 128 +++++++++++++++++- .../appointments/appointments.service.ts | 41 ++++-- 2 files changed, 154 insertions(+), 15 deletions(-) diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts index 184f125..230e07f 100644 --- a/backend/src/features/appointments/appointments.service.spec.ts +++ b/backend/src/features/appointments/appointments.service.spec.ts @@ -392,11 +392,55 @@ describe('AppointmentsService.createPending — integridade das partes', () => { ).rejects.toThrow(BadRequestException); }); + it('preserva o bloqueio preliminar de agendamento com produto', async () => { + const client = { + id: 'client-1', + name: 'Client', + role: UserRole.CUSTOMER, + }; + const specialist = { + id: 'specialist-1', + name: 'Specialist', + role: UserRole.SPECIALIST, + speciality: ProductType.CAR, + }; + const existing = { + id: 'existing-product-appointment', + status: StatusAgendamento.PENDING, + }; + const prisma = { + user: { + findUnique: jest + .fn() + .mockResolvedValueOnce(client) + .mockResolvedValueOnce(specialist), + }, + appointment: { findFirst: jest.fn().mockResolvedValue(existing) }, + $transaction: jest.fn(), + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + await expect( + service.createPending( + { + client_id: client.id, + specialist_id: specialist.id, + product_type: ProductType.CAR, + product_id: 'product-1', + }, + client.id, + UserRole.CUSTOMER, + ), + ).rejects.toThrow(ConflictException); + + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + it.each([ [undefined, AppointmentSchedulingMethod.CALENDLY], [AppointmentSchedulingMethod.EMAIL, AppointmentSchedulingMethod.EMAIL], ])( - 'locks active-process dedup and persists pending source %s as %s', + 'permite consultoria com processo existente e persiste a origem %s como %s', async (inputMethod, expectedMethod) => { const client = { id: 'client-1', @@ -409,6 +453,11 @@ describe('AppointmentsService.createPending — integridade das partes', () => { role: UserRole.SPECIALIST, speciality: ProductType.CAR, }; + const appointmentFindFirst = jest.fn().mockResolvedValue(null); + const processFindFirst = jest.fn().mockResolvedValue({ + id: 'active-process-1', + status: ProcessStatus.SCHEDULING, + }); const tx = { $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), user: { findUnique: jest.fn().mockResolvedValue(specialist) }, @@ -416,10 +465,10 @@ describe('AppointmentsService.createPending — integridade das partes', () => { boat: { findUnique: jest.fn() }, aircraft: { findUnique: jest.fn() }, appointment: { - findFirst: jest.fn().mockResolvedValue(null), + findFirst: appointmentFindFirst, create: jest.fn().mockRejectedValue(new Error('stop after checks')), }, - process: { findFirst: jest.fn().mockResolvedValue(null) }, + process: { findFirst: processFindFirst }, }; const prisma = { user: { @@ -449,7 +498,21 @@ describe('AppointmentsService.createPending — integridade das partes', () => { expect.anything(), 'process-dedup:client-1:specialist-1:CONSULTANCY:none', ); - expect(tx.process.findFirst).toHaveBeenCalledTimes(1); + 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(tx.$queryRaw.mock.invocationCallOrder[0]).toBeLessThan( + appointmentFindFirst.mock.invocationCallOrder[0], + ); expect(tx.appointment.create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ @@ -459,6 +522,63 @@ describe('AppointmentsService.createPending — integridade das partes', () => { ); }, ); + + it.each([StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED])( + 'bloqueia consultoria quando a revalidação encontra agendamento %s', + async (status) => { + const client = { + id: 'client-1', + name: 'Client', + role: UserRole.CUSTOMER, + }; + const specialist = { + id: 'specialist-1', + name: 'Specialist', + role: UserRole.SPECIALIST, + speciality: ProductType.CAR, + }; + const existing = { + id: 'concurrent-appointment-1', + status, + product_type: null, + product_id: null, + }; + const appointmentCreate = jest.fn(); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + user: { findUnique: jest.fn().mockResolvedValue(specialist) }, + car: { findUnique: jest.fn() }, + boat: { findUnique: jest.fn() }, + aircraft: { findUnique: jest.fn() }, + appointment: { + findFirst: jest.fn().mockResolvedValue(existing), + create: appointmentCreate, + }, + process: { findFirst: jest.fn().mockResolvedValue(null) }, + }; + const prisma = { + user: { + findUnique: jest + .fn() + .mockResolvedValueOnce(client) + .mockResolvedValueOnce(specialist), + }, + appointment: { findFirst: jest.fn().mockResolvedValue(null) }, + $transaction: jest.fn(async (callback: any) => callback(tx)), + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + await expect( + service.createPending( + { client_id: client.id, specialist_id: specialist.id }, + client.id, + UserRole.CUSTOMER, + ), + ).rejects.toThrow(ConflictException); + + expect(appointmentCreate).not.toHaveBeenCalled(); + }, + ); }); describe('AppointmentsService.updateStatus — snapshot da negociação', () => { diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 407a388..5837fd6 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -40,7 +40,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 { + acquireActiveProcessDedupLock, + lockAndAssertNoActiveProcess, +} from 'src/features/processes/process-dedup-lock'; import { acquireSpecialistScheduleLock, assertSpecialistScheduleAvailable, @@ -1312,11 +1315,14 @@ export class AppointmentsService { existingWhere.product_id = dto.product_id; } - const existing = await this.prisma.appointment.findFirst({ - where: existingWhere, - }); + const assertNoDuplicateAppointment = (existing: any): void => { + if (!existing) { + this.logger.log( + `[createPending] ✓ Nenhum agendamento duplicado encontrado`, + ); + return; + } - if (existing) { this.logger.error( `[createPending] ERRO: Agendamento duplicado encontrado: ${existing.id}`, ); @@ -1333,10 +1339,12 @@ export class AppointmentsService { }, }, }); - } - this.logger.log( - `[createPending] ✓ Nenhum agendamento duplicado encontrado`, - ); + }; + + const existing = await this.prisma.appointment.findFirst({ + where: existingWhere, + }); + assertNoDuplicateAppointment(existing); // Validar produto apenas se fornecido (não é consultoria) let product: any = null; @@ -1383,12 +1391,23 @@ export class AppointmentsService { productId: dto.product_id, }); - await lockAndAssertNoActiveProcess(tx, { + const processScope = { clientId: dto.client_id, specialistId: dto.specialist_id, productType: isConsultancy ? null : dto.product_type, productId: isConsultancy ? null : dto.product_id, - }); + }; + + if (isConsultancy) { + await acquireActiveProcessDedupLock(tx, processScope); + const existingAfterLock = await tx.appointment.findFirst({ + where: existingWhere, + }); + assertNoDuplicateAppointment(existingAfterLock); + } else { + await lockAndAssertNoActiveProcess(tx, processScope); + } + const pendingDateTime = dto.appointment_datetime ? parseDate(String(dto.appointment_datetime)) : null; From ce8280710c5b4a950c2190f4c9c160cbf142929d Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Tue, 13 Oct 2026 18:57:07 -0300 Subject: [PATCH 5/6] fix(import): correct identifier tip formatting --- .../components/shared/XlsxImporter.test.tsx | 35 +++++++++++++++++++ .../src/components/shared/XlsxImporter.tsx | 10 +++--- 2 files changed, 41 insertions(+), 4 deletions(-) create mode 100644 frontend/src/components/shared/XlsxImporter.test.tsx diff --git a/frontend/src/components/shared/XlsxImporter.test.tsx b/frontend/src/components/shared/XlsxImporter.test.tsx new file mode 100644 index 0000000..c9377b6 --- /dev/null +++ b/frontend/src/components/shared/XlsxImporter.test.tsx @@ -0,0 +1,35 @@ +// @vitest-environment jsdom + +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { XlsxImporter } from "./XlsxImporter"; + +afterEach(cleanup); + +describe("XlsxImporter", () => { + it("mantém a dica do identificador em uma única frase com espaços e acentos", () => { + render( + , + ); + + const tip = screen.getByText( + (_, element) => + element?.tagName === "LI" && + element.textContent?.includes("Produtos com") === true && + element.textContent?.includes("identificador") === true, + ); + const sentence = tip.children[1]; + + expect(sentence?.tagName).toBe("SPAN"); + expect(sentence?.textContent).toBe( + "Produtos com o mesmo identificador serão atualizados em vez de duplicados (marca e modelo podem se repetir entre produtos diferentes).", + ); + expect(sentence?.querySelector("strong")?.textContent).toBe( + "identificador", + ); + }); +}); diff --git a/frontend/src/components/shared/XlsxImporter.tsx b/frontend/src/components/shared/XlsxImporter.tsx index 1f4b081..dcf37ba 100644 --- a/frontend/src/components/shared/XlsxImporter.tsx +++ b/frontend/src/components/shared/XlsxImporter.tsx @@ -336,10 +336,12 @@ export function XlsxImporter({
  • - Produtos com mesmo{" "} - identificador serao - atualizados ao inves de duplicados (marca e modelo podem se - repetir entre produtos diferentes). + + Produtos com o mesmo{" "} + identificador{" "} + serão atualizados em vez de duplicados (marca e modelo podem + se repetir entre produtos diferentes). +
  • From ecedb095008b054d6109baadfa5832892883a546 Mon Sep 17 00:00:00 2001 From: Messias-Olivindo Date: Wed, 14 Oct 2026 07:34:33 -0300 Subject: [PATCH 6/6] fix(appointments): preserve consultancy lifecycle --- .../appointments/appointments.service.spec.ts | 103 ++++++++++++++++++ .../appointments/appointments.service.ts | 54 +++++++-- ...ocesses-dedup-concurrency.postgres.spec.ts | 17 ++- .../processes/processes.service.spec.ts | 48 +++++++- .../features/processes/processes.service.ts | 40 ++++++- 5 files changed, 243 insertions(+), 19 deletions(-) diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts index 230e07f..4f75642 100644 --- a/backend/src/features/appointments/appointments.service.spec.ts +++ b/backend/src/features/appointments/appointments.service.spec.ts @@ -996,6 +996,109 @@ describe('AppointmentsService.confirmPending — snapshot da negociação', () = expect(prisma.$transaction).not.toHaveBeenCalled(); }); + it('confirma consultoria mesmo quando existe processo ativo anterior', async () => { + 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', + role: UserRole.SPECIALIST, + speciality: ProductType.CAR, + }; + const currentProcess = { + id: 'current-process-1', + client_id: client.id, + specialist_id: specialist.id, + status: ProcessStatus.SCHEDULING, + notes: 'Consultoria atual', + product_type: null, + car_id: null, + boat_id: null, + aircraft_id: null, + negotiation_currency: null, + negotiation_product_value: null, + updated_at: new Date('2026-01-01T00:00:00.000Z'), + car: null, + boat: null, + aircraft: null, + }; + const appointment = { + id: 'appointment-1', + client_id: client.id, + specialist_id: specialist.id, + product_type: null, + product_id: null, + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + notes: null, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + created_at: new Date('2026-01-01T00:00:00.000Z'), + updated_at: new Date('2026-01-01T00:00:00.000Z'), + client, + specialist, + process: currentProcess, + }; + const processFindFirst = jest.fn().mockResolvedValue({ + id: 'older-active-process', + status: ProcessStatus.NEGOTIATION, + }); + const appointmentFindFirst = jest.fn().mockResolvedValue(null); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + user: { findUnique: jest.fn().mockResolvedValue(specialist) }, + car: { findUnique: jest.fn() }, + boat: { findUnique: jest.fn() }, + aircraft: { findUnique: jest.fn() }, + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + findFirst: appointmentFindFirst, + update: jest.fn().mockResolvedValue({ + ...appointment, + status: StatusAgendamento.SCHEDULED, + }), + }, + process: { + findFirst: processFindFirst, + create: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + findUniqueOrThrow: jest.fn().mockResolvedValue(currentProcess), + }, + processStatusHistory: { create: jest.fn().mockResolvedValue({}) }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const notifications = { + sendAppointmentConfirmedEmail: jest.fn().mockResolvedValue(undefined), + } as any; + const service = new AppointmentsService(prisma, notifications, {} as any); + + await expect( + service.confirmPending(appointment.id, specialist.id), + ).resolves.toMatchObject({ id: appointment.id }); + + 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], + }, + }, + }); + }); + it.each([ [false, ProductCurrency.BRL], [false, ProductCurrency.USD], diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 5837fd6..0d26229 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -1673,16 +1673,50 @@ export class AppointmentsService { productId: appointment.product_id, }); - await lockAndAssertNoActiveProcess( - tx, - { - clientId: appointment.client_id, - specialistId: appointment.specialist_id, - productType: appointment.product_type, - productId: appointment.product_id, - }, - appointment.process?.id, - ); + const processScope = { + clientId: appointment.client_id, + specialistId: appointment.specialist_id, + productType: appointment.product_type, + productId: appointment.product_id, + }; + const isConsultancy = + !appointment.product_type || !appointment.product_id; + + if (isConsultancy) { + await acquireActiveProcessDedupLock(tx, processScope); + const existingAppointment = await tx.appointment.findFirst({ + where: { + id: { not: appointmentId }, + client_id: appointment.client_id, + specialist_id: appointment.specialist_id, + product_type: null, + product_id: null, + status: { + in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], + }, + }, + }); + if (existingAppointment) { + throw new ConflictException({ + success: false, + error: { + code: 409, + message: + 'Já existe um agendamento de consultoria pendente com este especialista', + details: { + existing_id: existingAppointment.id, + existing_status: existingAppointment.status, + }, + }, + }); + } + } else { + await lockAndAssertNoActiveProcess( + tx, + processScope, + appointment.process?.id, + ); + } await acquireSpecialistScheduleLock(tx, appointment.specialist_id); const lockedAppointment = await tx.appointment.findUnique({ 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 0859143..f370317 100644 --- a/backend/src/features/processes/processes-dedup-concurrency.postgres.spec.ts +++ b/backend/src/features/processes/processes-dedup-concurrency.postgres.spec.ts @@ -226,7 +226,7 @@ describeWithPostgres('process active dedup lock — PostgreSQL concurrency', () }); }, 15_000); - it('shares the dedup lock between public create and create-on-behalf', async () => { + 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(); @@ -275,9 +275,16 @@ describeWithPostgres('process active dedup lock — PostgreSQL concurrency', () const outcomes = await Promise.allSettled([publicCreate, behalfCreate]); expect(bothAttemptedBeforeCompletion).toBe(true); - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); + 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); }); diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts index 8c38283..1d30814 100644 --- a/backend/src/features/processes/processes.service.spec.ts +++ b/backend/src/features/processes/processes.service.spec.ts @@ -267,7 +267,10 @@ describe('ProcessesService.createOnBehalfOfClient', () => { car: { findUnique: jest.fn().mockResolvedValue(product) }, boat: { findUnique: jest.fn().mockResolvedValue(product) }, aircraft: { findUnique: jest.fn().mockResolvedValue(product) }, - appointment: { create: appointmentCreate }, + appointment: { + findFirst: jest.fn().mockResolvedValue(null), + create: appointmentCreate, + }, process: { findFirst: jest.fn().mockResolvedValue(null), create: processCreate, @@ -362,6 +365,49 @@ describe('ProcessesService.createOnBehalfOfClient', () => { expect(data.notes).toContain('Consultoria'); }); + it('permite consultoria em nome do cliente mesmo com processo ativo anterior', 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: { + client_id: clientId, + specialist_id: specialistId, + product_type: null, + product_id: null, + status: { + in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], + }, + }, + }); + expect(appointmentCreate).toHaveBeenCalled(); + }); + + it('rejeita consultoria duplicada em nome do cliente', async () => { + const { service, appointmentCreate, tx } = mkService(); + tx.appointment.findFirst.mockResolvedValue({ + id: 'existing-appointment-1', + status: StatusAgendamento.PENDING, + }); + + await expect( + service.createOnBehalfOfClient({ + ...base, + product_id: undefined, + actorLabel: 'consultor', + }), + ).rejects.toThrow(ConflictException); + + expect(appointmentCreate).not.toHaveBeenCalled(); + }); + it('especialista inexistente é rejeitado', async () => { const { service } = mkService(null); diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts index 155811d..81f2181 100644 --- a/backend/src/features/processes/processes.service.ts +++ b/backend/src/features/processes/processes.service.ts @@ -33,7 +33,10 @@ import { lockNegotiationProductMoney, } from '../products/product-monetary-lock'; import { validateSpecialistProductAssociation } from '../products/product-association-validator'; -import { lockAndAssertNoActiveProcess } from './process-dedup-lock'; +import { + acquireActiveProcessDedupLock, + lockAndAssertNoActiveProcess, +} from './process-dedup-lock'; import { parseDate, isFutureDate } from 'src/shared/utils/date.utils'; import { acquireSpecialistScheduleLock, @@ -449,12 +452,43 @@ export class ProcessesService { productId: isConsultancy ? null : input.product_id, }); - await lockAndAssertNoActiveProcess(tx, { + const processScope = { clientId: input.client_id, specialistId: input.specialist_id, productType: isConsultancy ? null : input.product_type, productId: isConsultancy ? null : input.product_id, - }); + }; + + if (isConsultancy) { + await acquireActiveProcessDedupLock(tx, processScope); + const existingAppointment = await tx.appointment.findFirst({ + where: { + client_id: input.client_id, + specialist_id: input.specialist_id, + product_type: null, + product_id: null, + status: { + in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], + }, + }, + }); + if (existingAppointment) { + throw new ConflictException({ + success: false, + error: { + code: 409, + message: + 'Já existe um agendamento de consultoria pendente com este especialista', + details: { + existing_id: existingAppointment.id, + existing_status: existingAppointment.status, + }, + }, + }); + } + } else { + await lockAndAssertNoActiveProcess(tx, processScope); + } const appointmentData: any = { client_id: input.client_id,