diff --git a/backend/src/features/dashboard/dashboard.service.spec.ts b/backend/src/features/dashboard/dashboard.service.spec.ts index f61b9a41..c876e564 100644 --- a/backend/src/features/dashboard/dashboard.service.spec.ts +++ b/backend/src/features/dashboard/dashboard.service.spec.ts @@ -3,9 +3,13 @@ import { DashboardService } from './dashboard.service'; function mkPrisma() { return { company: { count: jest.fn().mockResolvedValue(0) }, - process: { count: jest.fn().mockResolvedValue(0) }, + process: { + count: jest.fn().mockResolvedValue(0), + groupBy: jest.fn().mockResolvedValue([]), + }, user: { count: jest.fn().mockResolvedValue(0), + findUnique: jest.fn().mockResolvedValue(null), findMany: jest.fn().mockResolvedValue([]), }, car: { count: jest.fn().mockResolvedValue(0) }, @@ -23,13 +27,67 @@ function mkAdminDatabaseService(counts: any[] = []) { } function mkSvc(sales: any[] = [], counts: any[] = []) { + return mkSvcWithPrisma(mkPrisma(), sales, counts); +} + +function mkSvcWithPrisma( + prisma: ReturnType, + sales: any[] = [], + counts: any[] = [], +) { return new DashboardService( - mkPrisma(), + prisma, mkCommissionsService(sales), mkAdminDatabaseService(counts), ); } +describe('DashboardService — produtos ativos e totais', () => { + it('retorna ativos separados do total no dashboard administrativo', async () => { + const prisma = mkPrisma(); + prisma.car.count.mockImplementation(({ where }: any = {}) => + Promise.resolve(where?.is_active ? 2 : 3), + ); + prisma.boat.count.mockImplementation(({ where }: any = {}) => + Promise.resolve(where?.is_active ? 1 : 4), + ); + prisma.aircraft.count.mockImplementation(({ where }: any = {}) => + Promise.resolve(where?.is_active ? 5 : 6), + ); + + const result = await mkSvcWithPrisma(prisma).getAdminStats(); + + expect(result.totalProducts).toBe(13); + expect(result.activeProducts).toBe(8); + expect(prisma.car.count).toHaveBeenCalledWith({ + where: { is_active: true }, + }); + expect(prisma.boat.count).toHaveBeenCalledWith({ + where: { is_active: true }, + }); + expect(prisma.aircraft.count).toHaveBeenCalledWith({ + where: { is_active: true }, + }); + }); + + it('retorna ativos separados do total para o especialista', async () => { + const prisma = mkPrisma(); + prisma.user.findUnique.mockResolvedValue({ speciality: 'CAR' }); + prisma.car.count.mockImplementation(({ where }: any) => + Promise.resolve(where.is_active ? 2 : 5), + ); + + const result = + await mkSvcWithPrisma(prisma).getSpecialistStats('specialist-1'); + + expect(result.productsListed).toBe(5); + expect(result.activeProducts).toBe(2); + expect(prisma.car.count).toHaveBeenCalledWith({ + where: { specialist_id: 'specialist-1', is_active: true }, + }); + }); +}); + describe('DashboardService — getAdminStats sem conversionRate', () => { it('não retorna mais o campo conversionRate', async () => { const result = await mkSvc().getAdminStats(); diff --git a/backend/src/features/dashboard/dashboard.service.ts b/backend/src/features/dashboard/dashboard.service.ts index aee7a9bc..644ccf11 100644 --- a/backend/src/features/dashboard/dashboard.service.ts +++ b/backend/src/features/dashboard/dashboard.service.ts @@ -25,6 +25,9 @@ export class DashboardService { totalCars, totalBoats, totalAircrafts, + activeCars, + activeBoats, + activeAircrafts, salesByMonth, consultantsPerformance, sales, @@ -39,6 +42,9 @@ export class DashboardService { this.prisma.car.count(), this.prisma.boat.count(), this.prisma.aircraft.count(), + this.prisma.car.count({ where: { is_active: true } }), + this.prisma.boat.count({ where: { is_active: true } }), + this.prisma.aircraft.count({ where: { is_active: true } }), this.buildMonthlySalesData({}), this.getConsultantsPerformance(), this.commissionsService.listSales(), @@ -46,6 +52,7 @@ export class DashboardService { ]); const totalProducts = totalCars + totalBoats + totalAircrafts; + const activeProducts = activeCars + activeBoats + activeAircrafts; return { activeProcesses, @@ -53,6 +60,7 @@ export class DashboardService { totalClients, specialistsCount, totalProducts, + activeProducts, productsByType: { cars: totalCars, boats: totalBoats, @@ -110,8 +118,24 @@ export class DashboardService { }) : Promise.resolve(0); + const activeProductsPromise = + specialist?.speciality === 'CAR' + ? this.prisma.car.count({ + where: { specialist_id: specialistId, is_active: true }, + }) + : specialist?.speciality === 'BOAT' + ? this.prisma.boat.count({ + where: { specialist_id: specialistId, is_active: true }, + }) + : specialist?.speciality === 'AIRCRAFT' + ? this.prisma.aircraft.count({ + where: { specialist_id: specialistId, is_active: true }, + }) + : Promise.resolve(0); + const [ productsListed, + activeProducts, activeProcesses, completedSales, totalProcesses, @@ -119,6 +143,7 @@ export class DashboardService { processesByStatus, ] = await Promise.all([ productsListedPromise, + activeProductsPromise, this.prisma.process.count({ where: { specialist_id: specialistId, @@ -149,6 +174,7 @@ export class DashboardService { return { productsListed, + activeProducts, activeProcesses, completedSales, conversionRate, diff --git a/docs/e2e-evidence/commission-after.jpg b/docs/e2e-evidence/commission-after.jpg new file mode 100644 index 00000000..9420f2c6 Binary files /dev/null and b/docs/e2e-evidence/commission-after.jpg differ diff --git a/docs/e2e-evidence/commission-before.jpg b/docs/e2e-evidence/commission-before.jpg new file mode 100644 index 00000000..9c57a4f4 Binary files /dev/null and b/docs/e2e-evidence/commission-before.jpg differ diff --git a/docs/e2e-evidence/commission-total-value.md b/docs/e2e-evidence/commission-total-value.md new file mode 100644 index 00000000..0ce8f40b --- /dev/null +++ b/docs/e2e-evidence/commission-total-value.md @@ -0,0 +1,23 @@ +# Evidência E2E — valor total da comissão + +Data: 14 de outubro de 2026 + +Fluxo validado na rota real `/specialist/contracts/new`, com autenticação e dados de prefill fornecidos por uma API local controlada. + +## 1. Estado inicial + +Com a porcentagem em `0`, a prévia financeira permanece oculta. + +![Etapa de comissão antes do preenchimento](./commission-before.jpg) + +## 2. Resultado após o preenchimento + +Ao informar `10%` sobre uma venda de `R$ 100.000,00`, a mesma seção exibe: + +- Valor total da comissão: `R$ 10.000,00` +- Seu ganho estimado: `R$ 7.000,00` + +![Etapa de comissão mostrando o total e o ganho estimado](./commission-after.jpg) + +O DOM foi verificado pelos rótulos e valores exatos, e o console do navegador não registrou erros nem avisos durante o fluxo. + diff --git a/docs/superpowers/plans/2026-10-14-active-product-dashboard.md b/docs/superpowers/plans/2026-10-14-active-product-dashboard.md new file mode 100644 index 00000000..f11dd06e --- /dev/null +++ b/docs/superpowers/plans/2026-10-14-active-product-dashboard.md @@ -0,0 +1,218 @@ +# Active Product Dashboard 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:** Mostrar produtos ativos em destaque e o total de produtos como informação auxiliar em todos os dashboards que exibem esse indicador. + +**Architecture:** O serviço de dashboard continuará retornando as contagens totais existentes e acrescentará `activeProducts`, calculado no banco com `is_active: true`. Os dois dashboards consumirão o novo campo sem alterar os demais contratos; testes de serviço e de componente protegerão a regra e a apresentação. + +**Tech Stack:** NestJS, Prisma, Jest, React, TypeScript, Vitest, Testing Library, Vite. + +## Global Constraints + +- `totalProducts`, `productsListed` e `productsByType` mantêm a semântica atual para compatibilidade. +- `activeProducts` considera somente registros com `is_active: true`. +- O título visível é `Produtos ativos` e o auxiliar é ` produtos no total`. +- Testes JavaScript e TypeScript devem usar no máximo dois workers; testes focados são preferidos. + +--- + +### Task 1: Contagens distintas no backend + +**Files:** +- Modify: `backend/src/features/dashboard/dashboard.service.spec.ts` +- Modify: `backend/src/features/dashboard/dashboard.service.ts` + +**Interfaces:** +- Consumes: modelos Prisma `car`, `boat` e `aircraft`, todos com `is_active: boolean`. +- Produces: `getAdminStats(): Promise<{ totalProducts: number; activeProducts: number; ... }>` e `getSpecialistStats(specialistId): Promise<{ productsListed: number; activeProducts: number; ... }>`. + +- [x] **Step 1: Escrever testes que diferenciem ativos e total** + +Adicionar casos que configurem contagens diferentes para chamadas sem filtro e chamadas com `where.is_active: true`. Para especialista, verificar também `specialist_id`: + +```ts +it('retorna ativos separados do total no dashboard administrativo', async () => { + const prisma = mkPrisma(); + prisma.car.count.mockImplementation(({ where }: any = {}) => + Promise.resolve(where?.is_active ? 2 : 3), + ); + prisma.boat.count.mockImplementation(({ where }: any = {}) => + Promise.resolve(where?.is_active ? 1 : 4), + ); + prisma.aircraft.count.mockImplementation(({ where }: any = {}) => + Promise.resolve(where?.is_active ? 5 : 6), + ); + + const result = await mkSvcWithPrisma(prisma).getAdminStats(); + + expect(result.totalProducts).toBe(13); + expect(result.activeProducts).toBe(8); +}); + +it('retorna ativos separados do total para o especialista', async () => { + const prisma = mkPrisma(); + prisma.user.findUnique.mockResolvedValue({ speciality: 'CAR' }); + prisma.car.count.mockImplementation(({ where }: any) => + Promise.resolve(where.is_active ? 2 : 5), + ); + + const result = await mkSvcWithPrisma(prisma).getSpecialistStats('specialist-1'); + + expect(result.productsListed).toBe(5); + expect(result.activeProducts).toBe(2); + expect(prisma.car.count).toHaveBeenCalledWith({ + where: { specialist_id: 'specialist-1', is_active: true }, + }); +}); +``` + +- [x] **Step 2: Executar o teste e confirmar a falha esperada** + +Run: `cd backend && npm test -- dashboard.service.spec.ts --runInBand` + +Expected: FAIL porque `activeProducts` ainda não existe e a consulta filtrada ainda não é feita. + +- [x] **Step 3: Implementar as contagens ativas** + +No dashboard administrativo, executar em paralelo três novas contagens: + +```ts +this.prisma.car.count({ where: { is_active: true } }); +this.prisma.boat.count({ where: { is_active: true } }); +this.prisma.aircraft.count({ where: { is_active: true } }); +``` + +Somar os resultados em `activeProducts`. Para o especialista, criar uma segunda contagem da mesma especialidade, com: + +```ts +where: { specialist_id: specialistId, is_active: true } +``` + +Retornar `activeProducts` sem mudar o significado de `totalProducts` ou `productsListed`. + +- [x] **Step 4: Executar o teste focado e confirmar sucesso** + +Run: `cd backend && npm test -- dashboard.service.spec.ts --runInBand` + +Expected: PASS, sem falhas. + +- [x] **Step 5: Commitar a camada de dados** + +```bash +git add backend/src/features/dashboard/dashboard.service.ts backend/src/features/dashboard/dashboard.service.spec.ts +git commit -m "fix(dashboard): separate active and total products" +``` + +### Task 2: Apresentação no frontend + +**Files:** +- Modify: `frontend/src/services/dashboard.service.ts` +- Modify: `frontend/src/pages/admin/DashboardPage.tsx` +- Modify: `frontend/src/pages/specialist/SpecialistDashboard.tsx` +- Create: `frontend/src/pages/dashboard-product-counts.test.tsx` + +**Interfaces:** +- Consumes: `DashboardStats.activeProducts: number`, `DashboardStats.totalProducts: number`, `SpecialistDashboardStats.activeProducts: number` e `SpecialistDashboardStats.productsListed: number`. +- Produces: cards com título `Produtos ativos`, valor ativo em destaque e texto ` produtos no total`. + +- [x] **Step 1: Escrever testes de componente para os dois dashboards** + +Mockar os serviços de dashboard, gráficos e animações. Renderizar o admin com `activeProducts: 8`, `totalProducts: 13`; renderizar o especialista com `activeProducts: 2`, `productsListed: 5`. Verificar: + +```ts +expect(await screen.findByText('Produtos ativos')).toBeTruthy(); +expect(screen.getByText('8')).toBeTruthy(); +expect(screen.getByText('13 produtos no total')).toBeTruthy(); +``` + +e, no segundo caso: + +```ts +expect(await screen.findByText('Produtos ativos')).toBeTruthy(); +expect(screen.getByText('2')).toBeTruthy(); +expect(screen.getByText('5 produtos no total')).toBeTruthy(); +``` + +- [x] **Step 2: Executar o teste e confirmar a falha esperada** + +Run: `cd frontend && npm test -- src/pages/dashboard-product-counts.test.tsx --pool=forks --maxWorkers=2` + +Expected: FAIL porque os tipos e os cards ainda não usam `activeProducts`. + +- [x] **Step 3: Atualizar tipos e cards** + +Adicionar `activeProducts: number` às duas interfaces. No admin, alterar o KPI de produtos para: + +```ts +{ + icon: Package, + label: 'Produtos ativos', + value: stats?.activeProducts ?? 0, + sub: `${stats?.totalProducts ?? 0} produtos no total`, +} +``` + +No especialista, usar `stats?.activeProducts ?? 0` no destaque e `${stats?.productsListed ?? 0} produtos no total` no auxiliar. + +- [x] **Step 4: Executar o teste focado e confirmar sucesso** + +Run: `cd frontend && npm test -- src/pages/dashboard-product-counts.test.tsx --pool=forks --maxWorkers=2` + +Expected: PASS, sem falhas. + +- [x] **Step 5: Commitar a interface** + +```bash +git add frontend/src/services/dashboard.service.ts frontend/src/pages/admin/DashboardPage.tsx frontend/src/pages/specialist/SpecialistDashboard.tsx frontend/src/pages/dashboard-product-counts.test.tsx +git commit -m "fix(dashboard): highlight active products" +``` + +### Task 3: Verificação integrada e validação visual + +**Files:** +- Verify: `backend/src/features/dashboard/dashboard.service.ts` +- Verify: `frontend/src/pages/admin/DashboardPage.tsx` +- Verify: `frontend/src/pages/specialist/SpecialistDashboard.tsx` +- Create locally: `artifacts/e2e/active-product-dashboard/` + +**Interfaces:** +- Consumes: aplicação local, contas de administrador e especialista, base com produtos ativos e inativos. +- Produces: builds válidos e screenshots desktop/móvel dos dois dashboards. + +- [x] **Step 1: Executar testes focados em sequência** + +```bash +cd backend && npm test -- dashboard.service.spec.ts --runInBand +cd frontend && npm test -- src/pages/dashboard-product-counts.test.tsx --pool=forks --maxWorkers=2 +``` + +Expected: os dois comandos terminam com zero falhas. + +- [x] **Step 2: Executar builds em sequência** + +```bash +cd backend && npm run build +cd frontend && npm run build +``` + +Expected: ambos terminam com exit code 0. + +- [x] **Step 3: Preparar dados e iniciar aplicação** + +Usar a configuração local documentada no repositório, garantir pelo menos um produto inativo e iniciar backend e frontend sem executar processos pesados em paralelo com testes ou builds. + +- [x] **Step 4: Validar no navegador** + +Entrar como administrador e especialista. Em cada dashboard, confirmar visualmente: + +- título `Produtos ativos`; +- número principal igual à contagem ativa preparada; +- auxiliar igual ao total, incluindo o produto inativo; +- ausência de corte ou sobreposição em desktop e viewport móvel. + +Salvar evidências em `artifacts/e2e/active-product-dashboard/` ou anexá-las diretamente ao relatório da execução quando o navegador não oferecer persistência local. + +- [x] **Step 5: Revisar diff e publicar** + +Revisar mudanças contra `origin/main`, executar novamente os comandos de verificação finais, enviar `codex/active-product-dashboard` e abrir PR com regra, testes e evidências visuais descritos no corpo. diff --git a/docs/superpowers/specs/2026-10-14-active-product-dashboard-design.md b/docs/superpowers/specs/2026-10-14-active-product-dashboard-design.md new file mode 100644 index 00000000..4fc05ef4 --- /dev/null +++ b/docs/superpowers/specs/2026-10-14-active-product-dashboard-design.md @@ -0,0 +1,56 @@ +# Produtos ativos nos dashboards + +## Objetivo + +Corrigir a divergência entre produtos ativos e produtos cadastrados nos dashboards que exibem essa informação. A quantidade em destaque deve representar somente produtos ativos, enquanto o texto auxiliar deve informar a quantidade total de produtos, incluindo ativos e inativos. + +## Escopo + +A alteração abrange os dois dashboards que hoje exibem quantidade de produtos: + +- dashboard administrativo; +- dashboard do especialista. + +O dashboard de escritório não exibe quantidade de produtos e, portanto, não será alterado. + +## Regra de negócio + +- Produto ativo é aquele cujo campo `is_active` é `true`. +- Total de produtos inclui registros ativos e inativos. +- No dashboard administrativo, as quantidades agregam carros, embarcações e aeronaves de todos os especialistas. +- No dashboard do especialista, as quantidades consideram apenas os produtos vinculados ao especialista e à especialidade dele. + +## Contrato da API + +Para preservar compatibilidade, os campos existentes continuarão representando o total cadastrado: + +- `totalProducts` no dashboard administrativo; +- `productsListed` no dashboard do especialista; +- `productsByType` continuará disponível no dashboard administrativo com as contagens totais por categoria. + +As duas respostas receberão o campo `activeProducts`, que contém a contagem filtrada por `is_active: true`. + +## Interface + +Nos dois dashboards, o card passará a exibir: + +- título: `Produtos ativos`; +- valor principal: `activeProducts`; +- texto auxiliar: ` produtos no total`. + +O dashboard administrativo deixará de exibir no card a divisão por categoria, mas a informação continuará disponível na API para consumidores existentes. + +Durante o carregamento, os skeletons existentes serão preservados. Na ausência de dados, as quantidades exibidas serão zero. + +## Testes e validação + +- Testes unitários do backend verificarão que produtos ativos e totais usam filtros distintos nos dois endpoints. +- Testes de componentes do frontend verificarão o título, o valor em destaque e o texto auxiliar nos dashboards administrativo e do especialista. +- Build de backend e frontend confirmará a consistência de tipos. +- Um percurso E2E no navegador validará visualmente os dois dashboards em larguras desktop e móvel, registrando screenshots no diretório de evidências do projeto. + +## Fora de escopo + +- Alterar a listagem ou o processo de ativação/inativação de produtos. +- Remover os campos antigos da API. +- Adicionar o indicador a dashboards que atualmente não mostram produtos. diff --git a/frontend/src/pages/admin/DashboardPage.tsx b/frontend/src/pages/admin/DashboardPage.tsx index f885d739..14fb64d7 100644 --- a/frontend/src/pages/admin/DashboardPage.tsx +++ b/frontend/src/pages/admin/DashboardPage.tsx @@ -112,11 +112,9 @@ export default function DashboardPage() { }, { icon: Package, - label: "Produtos Cadastrados", - value: stats?.totalProducts ?? 0, - sub: `${stats?.productsByType.cars ?? 0} carros · ${ - stats?.productsByType.boats ?? 0 - } embarcações · ${stats?.productsByType.aircrafts ?? 0} aeronaves`, + label: "Produtos ativos", + value: stats?.activeProducts ?? 0, + sub: `${stats?.totalProducts ?? 0} produtos no total`, }, ]; diff --git a/frontend/src/pages/dashboard-product-counts.test.tsx b/frontend/src/pages/dashboard-product-counts.test.tsx new file mode 100644 index 00000000..47fd25e8 --- /dev/null +++ b/frontend/src/pages/dashboard-product-counts.test.tsx @@ -0,0 +1,127 @@ +// @vitest-environment jsdom +import { cleanup, render, screen } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { MemoryRouter } from "react-router-dom"; +import DashboardPage from "./admin/DashboardPage"; +import SpecialistDashboard from "./specialist/SpecialistDashboard"; +import { AppContext } from "../contexts/AppContext"; +import { + getDashboardStats, + getSpecialistDashboardStats, +} from "../services/dashboard.service"; + +vi.mock("../services/dashboard.service", () => ({ + getDashboardStats: vi.fn(), + getSpecialistDashboardStats: vi.fn(), +})); + +vi.mock("../store/authStateManager", () => ({ + useAuth: (selector: (state: object) => unknown) => + selector({ + user: { + id: "specialist-1", + name: "Ana", + speciality: "CAR", + }, + }), +})); + +vi.mock("framer-motion", () => ({ + motion: { + div: ({ children }: { children: ReactNode }) =>
{children}
, + }, + useReducedMotion: () => true, +})); + +vi.mock("recharts", () => { + const Chart = ({ children }: { children?: ReactNode }) =>
{children}
; + return { + LineChart: Chart, + Line: Chart, + XAxis: Chart, + YAxis: Chart, + CartesianGrid: Chart, + Tooltip: Chart, + Legend: Chart, + ResponsiveContainer: Chart, + PieChart: Chart, + Pie: Chart, + Cell: Chart, + }; +}); + +vi.mock("../components/commission/CommissionMiniCalculator", () => ({ + CommissionMiniCalculator: () =>
, +})); + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +describe("contagem de produtos nos dashboards", () => { + it("destaca ativos e informa o total no dashboard administrativo", async () => { + vi.mocked(getDashboardStats).mockResolvedValue({ + activeProcesses: 1, + activeCompanies: 1, + totalClients: 1, + specialistsCount: 1, + totalProducts: 13, + activeProducts: 8, + productsByType: { cars: 3, boats: 4, aircrafts: 6 }, + salesByMonth: [], + consultantsPerformance: [], + commissionSummary: { + totalPaid: 0, + thisMonth: 0, + avgTicket: 0, + recentSales: [], + }, + databaseCounts: [], + }); + + render( + + + + + , + ); + + expect(await screen.findByText("Produtos ativos")).toBeTruthy(); + expect(screen.getByText("8")).toBeTruthy(); + expect(screen.getByText("13 produtos no total")).toBeTruthy(); + }); + + it("destaca ativos e informa o total no dashboard do especialista", async () => { + vi.mocked(getSpecialistDashboardStats).mockResolvedValue({ + productsListed: 5, + activeProducts: 2, + activeProcesses: 1, + completedSales: 1, + conversionRate: 50, + salesByMonth: [], + processesByStatus: [], + }); + + render( + + + , + ); + + expect(await screen.findByText("Produtos ativos")).toBeTruthy(); + expect(screen.getByText("2")).toBeTruthy(); + expect(screen.getByText("5 produtos no total")).toBeTruthy(); + }); +}); diff --git a/frontend/src/pages/specialist/ContractCommissionStep.test.tsx b/frontend/src/pages/specialist/ContractCommissionStep.test.tsx index e1ece79f..70777eb8 100644 --- a/frontend/src/pages/specialist/ContractCommissionStep.test.tsx +++ b/frontend/src/pages/specialist/ContractCommissionStep.test.tsx @@ -25,6 +25,7 @@ function TestCommissionStep({ productLabel="veículo" currency={currency} vehiclePrice={100_000} + totalCommissionValue={10_000} specialistValue={7_000} showEarningsPreview={showEarningsPreview} onContinue={vi.fn()} @@ -36,14 +37,19 @@ function TestCommissionStep({ describe("ContractCommissionStep", () => { afterEach(cleanup); - it("mostra somente o ganho estimado do especialista em BRL", () => { + it("mostra o valor total da comissão e o ganho estimado em BRL", () => { render(); + expect(screen.getByText("Valor total da comissão")).toBeTruthy(); + expect( + screen.getByText( + formatCurrency(10_000, "BRL").replace(/\u00a0/g, " "), + ), + ).toBeTruthy(); expect(screen.getByText("Seu ganho estimado")).toBeTruthy(); expect( screen.getByText(formatCurrency(7_000, "BRL").replace(/\u00a0/g, " ")), ).toBeTruthy(); - expect(screen.queryByText("Comissão total")).toBeNull(); expect(screen.queryByText("Valor líquido do vendedor")).toBeNull(); expect(screen.queryByText("Distribuição da comissão")).toBeNull(); expect(screen.queryByText("Plataforma")).toBeNull(); @@ -64,6 +70,7 @@ describe("ContractCommissionStep", () => { ); expect(screen.queryByText("Seu ganho estimado")).toBeNull(); + expect(screen.queryByText("Valor total da comissão")).toBeNull(); expect(screen.queryByText(formatCurrency(7_000, "BRL"))).toBeNull(); }); }); diff --git a/frontend/src/pages/specialist/ContractCommissionStep.tsx b/frontend/src/pages/specialist/ContractCommissionStep.tsx index 9db0aac5..e1a1c446 100644 --- a/frontend/src/pages/specialist/ContractCommissionStep.tsx +++ b/frontend/src/pages/specialist/ContractCommissionStep.tsx @@ -21,6 +21,7 @@ interface Props { productLabel: string; currency: ProductCurrency; vehiclePrice: number; + totalCommissionValue: number; specialistValue: number; showEarningsPreview: boolean; onContinue: () => void; @@ -33,6 +34,7 @@ export default function ContractCommissionStep({ productLabel, currency, vehiclePrice, + totalCommissionValue, specialistValue, showEarningsPreview, onContinue, @@ -101,10 +103,22 @@ export default function ContractCommissionStep({ {showEarningsPreview && (
-

Seu ganho estimado

-

- {formatCurrency(specialistValue, currency)} -

+
+
+

+ Valor total da comissão +

+

+ {formatCurrency(totalCommissionValue, currency)} +

+
+
+

Seu ganho estimado

+

+ {formatCurrency(specialistValue, currency)} +

+
+
)} diff --git a/frontend/src/pages/specialist/CreateContractPage.tsx b/frontend/src/pages/specialist/CreateContractPage.tsx index 6398b6c2..bddf7664 100644 --- a/frontend/src/pages/specialist/CreateContractPage.tsx +++ b/frontend/src/pages/specialist/CreateContractPage.tsx @@ -820,6 +820,7 @@ export default function CreateContractPage() { productLabel={getProductTypeLabel(prefillData.product_type)} currency={prefillData.currency} vehiclePrice={vehiclePrice || 0} + totalCommissionValue={totalCommissionValue} specialistValue={specialistValue} showEarningsPreview={ vehiclePrice > 0 && diff --git a/frontend/src/pages/specialist/SpecialistDashboard.tsx b/frontend/src/pages/specialist/SpecialistDashboard.tsx index 5cc74e09..03915465 100644 --- a/frontend/src/pages/specialist/SpecialistDashboard.tsx +++ b/frontend/src/pages/specialist/SpecialistDashboard.tsx @@ -88,11 +88,9 @@ export default function SpecialistDashboard() { {/* Cards de Estatísticas */}
- {/* Card 1: Produtos Cadastrados */} + {/* Card 1: Produtos ativos */}
-

- Produtos Cadastrados -

+

Produtos ativos

{isLoading ? ( <> @@ -101,9 +99,11 @@ export default function SpecialistDashboard() { ) : ( <>

- {stats?.productsListed || 0} + {stats?.activeProducts ?? 0} +

+

+ {stats?.productsListed ?? 0} produtos no total

-

Total de produtos

)}
diff --git a/frontend/src/services/dashboard.service.ts b/frontend/src/services/dashboard.service.ts index c04e7f4a..4e75a51a 100644 --- a/frontend/src/services/dashboard.service.ts +++ b/frontend/src/services/dashboard.service.ts @@ -7,6 +7,7 @@ export interface DashboardStats { totalClients: number; specialistsCount: number; totalProducts: number; + activeProducts: number; productsByType: { cars: number; boats: number; aircrafts: number }; salesByMonth: MonthData[]; consultantsPerformance: ConsultantPerformanceData[]; @@ -39,6 +40,7 @@ export interface ConsultantPerformanceData { export interface SpecialistDashboardStats { productsListed: number; + activeProducts: number; activeProcesses: number; completedSales: number; conversionRate: number;