From 4e1b1efadad6f65418cd2162bd259d111332b0af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius?= Date: Thu, 29 Oct 2026 19:46:02 -0300 Subject: [PATCH 01/11] feat(appointments): return customer's product process stage in check GET /appointments/check now resolves the customer's process for the product instead of only a PENDING/SCHEDULED appointment. `exists` keeps meaning "active process" (anti-duplication guard), so advanced processes (NEGOTIATION onwards) no longer look absent. A new `process` block carries status, is_active and status history (status + changed_at only), falling back to the most recent COMPLETED/REJECTED process when none is active. Appointment fields are null when there is no current appointment. Refs #253 --- .../appointments/appointments.service.spec.ts | 354 ++++++++++++------ .../appointments/appointments.service.ts | 108 +++--- .../entities/appointment.response.ts | 21 +- backend/test/email-scheduling.e2e-spec.ts | 14 +- 4 files changed, 327 insertions(+), 170 deletions(-) diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts index a2afbfa..35d13a2 100644 --- a/backend/src/features/appointments/appointments.service.spec.ts +++ b/backend/src/features/appointments/appointments.service.spec.ts @@ -462,30 +462,27 @@ describe('AppointmentsService.createPending — associação e atomicidade', () Object.entries(where).every(([key, value]) => value !== null && typeof value === 'object' && 'in' in value ? (value.in as unknown[]).includes(row[key]) - : row[key] === value, + : value !== null && typeof value === 'object' && 'notIn' in value + ? !(value.notIn 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; + prisma.process.findFirst = jest.fn(async ({ where }) => { + const rows = reverse ? [...storedProcesses].reverse() : storedProcesses; + const process = rows.find((row) => matches(row, where)); + if (!process) return null; + return { + ...process, + appointment: + storedAppointments.find( + (appointment) => appointment.id === process.appointment_id, + ) ?? null, + specialist: { email: specialist.email }, + ProcessStatusHistory: [], + }; }); await service.createPending(dto, client.id, UserRole.CUSTOMER); @@ -511,6 +508,13 @@ describe('AppointmentsService.createPending — associação e atomicidade', () appointment_status: StatusAgendamento.PENDING, scheduling_method: AppointmentSchedulingMethod.EMAIL, appointment_datetime: new Date(dto.appointment_datetime!), + specialist_contact_email: specialist.email, + process: { + id: replacement.process_id, + status: ProcessStatus.SCHEDULING, + is_active: true, + status_history: [], + }, }); storedProcesses[1].status = ProcessStatus.REJECTED; @@ -521,7 +525,13 @@ describe('AppointmentsService.createPending — associação e atomicidade', () ProductType.CAR, activeProduct.id, ), - ).toEqual({ exists: false }); + ).toEqual({ + exists: false, + process: expect.objectContaining({ + status: ProcessStatus.REJECTED, + is_active: false, + }), + }); }, ); @@ -893,34 +903,65 @@ describe('AppointmentsService.createPending — associação e atomicidade', () ); }); -describe('AppointmentsService.findExistingAppointment — own minimal projection', () => { - const ownedAppointment = { - id: 'appointment-1', +describe('AppointmentsService.findExistingAppointment — processo do cliente no produto', () => { + const history = [ + { + status: ProcessStatus.SCHEDULING, + changed_at: new Date('2099-01-01T10:00:00.000Z'), + }, + { + status: ProcessStatus.NEGOTIATION, + changed_at: new Date('2099-01-02T10:00:00.000Z'), + }, + ]; + const ownedProcess = { + id: 'process-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', + status: ProcessStatus.SCHEDULING, + appointment: { + id: 'appointment-1', + client_id: 'client-1', + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), }, - specialist: { - id: 'specialist-1', - name: 'Specialist', - email: 'specialist@example.com', + specialist: { email: 'specialist@example.com' }, + ProcessStatusHistory: history.slice(0, 1), + }; + const expectedSelect = { + id: true, + client_id: true, + status: true, + appointment: { + select: { + id: true, + client_id: true, + status: true, + scheduling_method: true, + appointment_datetime: true, + }, + }, + specialist: { select: { email: true } }, + ProcessStatusHistory: { + select: { status: true, changed_at: true }, + orderBy: { changed_at: 'asc' }, }, - notes: 'private-notes', - created_at: new Date(), - updated_at: new Date(), }; - function harness(appointment: any) { + const scope = { + client_id: 'client-1', + specialist_id: 'specialist-1', + product_type: ProductType.CAR, + car_id: 'car-1', + removed_at: null, + }; + function harness(active: any, terminal: any = null) { const prisma = { - appointment: { findFirst: jest.fn().mockResolvedValue(appointment) }, + process: { + findFirst: jest + .fn() + .mockResolvedValueOnce(active) + .mockResolvedValueOnce(terminal), + }, car: { findUnique: jest.fn().mockResolvedValue({ id: 'car-1' }) }, } as any; return { @@ -928,109 +969,178 @@ describe('AppointmentsService.findExistingAppointment — own minimal projection service: new AppointmentsService(prisma, {} as any, {} as any), }; } + const check = (service: AppointmentsService) => + service.findExistingAppointment( + 'client-1', + 'specialist-1', + ProductType.CAR, + 'car-1', + ); + it.each([ - ownedAppointment, + ownedProcess, { - ...ownedAppointment, - scheduling_method: null, - appointment_datetime: null, + ...ownedProcess, + appointment: { + ...ownedProcess.appointment, + 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({ + 'returns the owned active process with its current appointment', + async (process) => { + const { prisma, service } = harness(process); + expect(await check(service)).toEqual({ exists: true, - appointment_id: appointment.id, + appointment_id: 'appointment-1', process_id: 'process-1', - appointment_status: appointment.status, - scheduling_method: appointment.scheduling_method, - appointment_datetime: appointment.appointment_datetime, - ...(appointment.scheduling_method === AppointmentSchedulingMethod.EMAIL + appointment_status: StatusAgendamento.PENDING, + scheduling_method: process.appointment.scheduling_method, + appointment_datetime: process.appointment.appointment_datetime, + ...(process.appointment.scheduling_method === + AppointmentSchedulingMethod.EMAIL ? { specialist_contact_email: 'specialist@example.com' } : {}), + process: { + id: 'process-1', + status: ProcessStatus.SCHEDULING, + is_active: true, + status_history: history.slice(0, 1), + }, }); - expect(prisma.appointment.findFirst).toHaveBeenCalledWith({ - where: expect.objectContaining({ - client_id: 'client-1', - 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', - removed_at: null, - status: { - in: [ - ProcessStatus.SCHEDULING, - ProcessStatus.NEGOTIATION, - ProcessStatus.PROCESSING_CONTRACT, - ProcessStatus.DOCUMENTATION, - ], - }, - }, + expect(prisma.process.findFirst).toHaveBeenCalledTimes(1); + expect(prisma.process.findFirst).toHaveBeenCalledWith({ + where: { + ...scope, + status: { + in: [ + ProcessStatus.SCHEDULING, + ProcessStatus.NEGOTIATION, + ProcessStatus.PROCESSING_CONTRACT, + ProcessStatus.DOCUMENTATION, + ], }, - }), - select: { - id: true, - client_id: true, - status: true, - scheduling_method: true, - appointment_datetime: true, - process: { select: { id: true, client_id: true } }, - specialist: { select: { email: true } }, }, + select: expectedSelect, }); expect(prisma.car.findUnique).not.toHaveBeenCalled(); }, ); + + it.each([StatusAgendamento.COMPLETED, StatusAgendamento.CANCELLED])( + 'keeps blocking an advanced process whose appointment is %s, without appointment data', + async (appointmentStatus) => { + const { service } = harness({ + ...ownedProcess, + status: ProcessStatus.NEGOTIATION, + appointment: { ...ownedProcess.appointment, status: appointmentStatus }, + ProcessStatusHistory: history, + }); + expect(await check(service)).toEqual({ + exists: true, + appointment_id: null, + process_id: 'process-1', + appointment_status: null, + scheduling_method: null, + appointment_datetime: null, + process: { + id: 'process-1', + status: ProcessStatus.NEGOTIATION, + is_active: true, + status_history: history, + }, + }); + }, + ); + it('não expõe contato do especialista para pedido CALENDLY', async () => { const { service } = harness({ - ...ownedAppointment, - scheduling_method: AppointmentSchedulingMethod.CALENDLY, + ...ownedProcess, + appointment: { + ...ownedProcess.appointment, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + }, }); + expect(await check(service)).not.toHaveProperty('specialist_contact_email'); + }); - const result = await service.findExistingAppointment( - 'client-1', - 'specialist-1', - ProductType.CAR, - 'car-1', - ); + it.each([ProcessStatus.COMPLETED, ProcessStatus.REJECTED])( + 'returns the latest %s process without unlocking appointment data', + async (status) => { + const { prisma, service } = harness(null, { + ...ownedProcess, + status, + ProcessStatusHistory: history, + }); + expect(await check(service)).toEqual({ + exists: false, + process: { + id: 'process-1', + status, + is_active: false, + status_history: history, + }, + }); + expect(prisma.process.findFirst).toHaveBeenLastCalledWith({ + where: { + ...scope, + status: { + notIn: [ + ProcessStatus.SCHEDULING, + ProcessStatus.NEGOTIATION, + ProcessStatus.PROCESSING_CONTRACT, + ProcessStatus.DOCUMENTATION, + ], + }, + }, + orderBy: { updated_at: 'desc' }, + select: expectedSelect, + }); + }, + ); - expect(result).not.toHaveProperty('specialist_contact_email'); - }); it.each([ - null, - { ...ownedAppointment, client_id: 'another-client' }, - { ...ownedAppointment, process: null }, - { - ...ownedAppointment, - process: { id: 'private-process', client_id: 'another-client' }, - }, + [null, null], + [{ ...ownedProcess, client_id: 'another-client' }, null], + [ + null, + { + ...ownedProcess, + status: ProcessStatus.REJECTED, + 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 }); + 'fails closed for missing or unowned process %#', + async (active, terminal) => { + const { service } = harness(active, terminal); + expect(await check(service)).toEqual({ exists: false, process: null }); }, ); + + it('omits appointment data from another client on an owned process', async () => { + const { service } = harness({ + ...ownedProcess, + appointment: { ...ownedProcess.appointment, client_id: 'another-client' }, + }); + expect(await check(service)).toMatchObject({ + exists: true, + appointment_id: null, + appointment_status: null, + }); + expect( + await check( + harness({ + ...ownedProcess, + appointment: { + ...ownedProcess.appointment, + client_id: 'another-client', + }, + }).service, + ), + ).not.toHaveProperty('specialist_contact_email'); + }); }); describe('AppointmentsService.createPending — integridade das partes', () => { diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 0b894b1..8e3051b 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -23,6 +23,7 @@ import { SpecialistResponseDto, ProductResponseDto, ExistingAppointmentCheck, + ProductProcessSummary, } from './entities/appointment.response'; import { AppointmentSchedulingMethod, @@ -2041,57 +2042,78 @@ export class AppointmentsService { : productType === ProductType.BOAT ? 'boat_id' : 'aircraft_id'; - const appointment = await this.prisma.appointment.findFirst({ - where: { - client_id: clientId, - specialist_id: specialistId, - product_type: productType, - product_id: productId, - status: { - in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], - }, - process: { - is: { - client_id: clientId, - specialist_id: specialistId, - product_type: productType, - [productField]: productId, - status: { in: ACTIVE_PROCESS_STATUSES }, - removed_at: null, - }, + const scope = { + client_id: clientId, + specialist_id: specialistId, + product_type: productType, + [productField]: productId, + removed_at: null, + }; + const select = { + id: true, + client_id: true, + status: true, + appointment: { + select: { + id: true, + client_id: true, + status: true, + scheduling_method: true, + appointment_datetime: true, }, }, - select: { - id: true, - client_id: true, - status: true, - scheduling_method: true, - appointment_datetime: true, - process: { select: { id: true, client_id: true } }, - specialist: { select: { email: true } }, + specialist: { select: { email: true } }, + ProcessStatusHistory: { + select: { status: true, changed_at: true }, + orderBy: { changed_at: 'asc' as const }, }, - }); - - if ( - !appointment || - appointment.client_id !== clientId || - !appointment.process || - appointment.process.client_id !== clientId - ) { - return { exists: false }; + }; + // Ativo tem prioridade; sem ativo, mostra o encerrado mais recente. + const process = + (await this.prisma.process.findFirst({ + where: { ...scope, status: { in: ACTIVE_PROCESS_STATUSES } }, + select, + })) ?? + (await this.prisma.process.findFirst({ + where: { ...scope, status: { notIn: ACTIVE_PROCESS_STATUSES } }, + orderBy: { updated_at: 'desc' }, + select, + })); + + if (!process || process.client_id !== clientId) { + return { exists: false, process: null }; } - const specialistContactEmail = appointment.specialist?.email; + const isActive = ACTIVE_PROCESS_STATUSES.includes(process.status); + const summary: ProductProcessSummary = { + id: process.id, + status: process.status, + is_active: isActive, + status_history: process.ProcessStatusHistory.map((entry) => ({ + status: entry.status, + changed_at: entry.changed_at, + })), + }; + if (!isActive) return { exists: false, process: summary }; + + const appointment = + process.appointment?.client_id === clientId && + (process.appointment.status === StatusAgendamento.PENDING || + process.appointment.status === StatusAgendamento.SCHEDULED) + ? process.appointment + : null; + const specialistContactEmail = process.specialist?.email; 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, - ...(appointment.scheduling_method === AppointmentSchedulingMethod.EMAIL && - specialistContactEmail + appointment_id: appointment?.id ?? null, + process_id: process.id, + appointment_status: appointment?.status ?? null, + scheduling_method: appointment?.scheduling_method ?? null, + appointment_datetime: appointment?.appointment_datetime ?? null, + ...(appointment?.scheduling_method === + AppointmentSchedulingMethod.EMAIL && specialistContactEmail ? { specialist_contact_email: specialistContactEmail } : {}), + process: summary, }; } diff --git a/backend/src/features/appointments/entities/appointment.response.ts b/backend/src/features/appointments/entities/appointment.response.ts index 1157530..f06f7e1 100644 --- a/backend/src/features/appointments/entities/appointment.response.ts +++ b/backend/src/features/appointments/entities/appointment.response.ts @@ -1,21 +1,36 @@ import { AppointmentSchedulingMethod, ProductCurrency, + ProcessStatus, ProductType, StatusAgendamento, } from '@prisma/client'; import { Expose, Type } from 'class-transformer'; +/** Processo do cliente no produto; histórico expõe apenas status e data. */ +export interface ProductProcessSummary { + id: string; + status: ProcessStatus; + is_active: boolean; + status_history: { status: ProcessStatus; changed_at: Date }[]; +} + +/** + * exists indica processo ativo (trava anti-duplicidade); process traz o ativo + * ou, sem ativo, o encerrado mais recente. Campos de agendamento só para + * agendamento vigente (PENDING/SCHEDULED). + */ export type ExistingAppointmentCheck = - | { exists: false } + | { exists: false; process: ProductProcessSummary | null } | { exists: true; - appointment_id: string; + appointment_id: string | null; process_id: string; - appointment_status: StatusAgendamento; + appointment_status: StatusAgendamento | null; scheduling_method: AppointmentSchedulingMethod | null; appointment_datetime: Date | null; specialist_contact_email?: string; + process: ProductProcessSummary; }; export interface ActiveProcessSnapshot { diff --git a/backend/test/email-scheduling.e2e-spec.ts b/backend/test/email-scheduling.e2e-spec.ts index 17e59f2..0a6e8fa 100644 --- a/backend/test/email-scheduling.e2e-spec.ts +++ b/backend/test/email-scheduling.e2e-spec.ts @@ -25,6 +25,7 @@ const checkKeys = [ 'scheduling_method', 'appointment_datetime', 'specialist_contact_email', + 'process', ]; // A dedicated URL opts in to the real PostgreSQL gate. Ordinary e2e discovery @@ -503,7 +504,7 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { .auth(customerToken, { type: 'bearer' }) .query(checkQuery(fixture.cars[0].id)) .expect(200); - expect(own.body.data).toEqual({ exists: false }); + expect(own.body.data).toEqual({ exists: false, process: null }); assertNoContacts(own.body); await request(app!.getHttpServer()) .get('/api/appointments/check') @@ -637,6 +638,14 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { scheduling_method: 'EMAIL', appointment_datetime: proposedIso, specialist_contact_email: config.credentials.specialist.email, + process: { + id: response.body.data.process_id, + status: 'SCHEDULING', + is_active: true, + status_history: [ + { status: 'SCHEDULING', changed_at: expect.any(String) }, + ], + }, }); assertOwnerScopedSpecialistEmail(own.body); const duplicate = await request(app!.getHttpServer()) @@ -645,7 +654,8 @@ describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { .send(pendingBody(car.id)) .expect(409); expect(duplicate.body.error.code).toBe('ACTIVE_PROCESS_EXISTS'); - const { exists: _exists, ...snapshot } = own.body.data; + const { exists: _exists, process: _process, ...snapshot } = + own.body.data; expect(duplicate.body.error.details).toEqual({ existing_request: snapshot, }); From 4c165f3edb88c07cf928038af87cebb04c52ca37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius?= Date: Thu, 29 Oct 2026 19:46:02 -0300 Subject: [PATCH 02/11] feat(frontend): show the customer's process stage on the product page The product page now renders a timeline with the customer's own process stage, separate from the appointment state: neutral while active, green check when completed and red mark when rejected, with dates from the status history and no rejection reason. A completed process only links to "Meus Processos"; a rejected one offers "Fazer novo agendamento", which reveals the existing scheduling flow. The check refetches silently when the tab becomes visible again, keeping the last result meanwhile. Refs #253 --- .../processes/ProductProcessTimeline.test.tsx | 85 ++++++++++ .../processes/ProductProcessTimeline.tsx | 154 ++++++++++++++++++ .../src/hooks/useCheckAppointment.test.tsx | 51 ++++-- frontend/src/hooks/useCheckAppointment.ts | 34 +++- .../ProductPage.calendly.integration.test.tsx | 2 +- .../src/pages/catalog/ProductPage.test.tsx | 120 +++++++++++++- frontend/src/pages/catalog/ProductPage.tsx | 38 +++++ frontend/src/services/appointments.service.ts | 24 ++- 8 files changed, 484 insertions(+), 24 deletions(-) create mode 100644 frontend/src/components/processes/ProductProcessTimeline.test.tsx create mode 100644 frontend/src/components/processes/ProductProcessTimeline.tsx diff --git a/frontend/src/components/processes/ProductProcessTimeline.test.tsx b/frontend/src/components/processes/ProductProcessTimeline.test.tsx new file mode 100644 index 0000000..4363f2e --- /dev/null +++ b/frontend/src/components/processes/ProductProcessTimeline.test.tsx @@ -0,0 +1,85 @@ +// @vitest-environment jsdom +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; +import ProductProcessTimeline from "./ProductProcessTimeline"; +import type { ProductProcessSummary } from "../../services/appointments.service"; + +const base: ProductProcessSummary = { + id: "process-1", + status: "SCHEDULING", + is_active: true, + status_history: [ + { status: "SCHEDULING", changed_at: "2099-01-01T12:00:00.000Z" }, + ], +}; + +function steps() { + return screen.getAllByRole("listitem").map((item) => ({ + label: item.textContent, + current: item.getAttribute("aria-current") === "step", + })); +} + +afterEach(cleanup); + +describe("ProductProcessTimeline", () => { + it("highlights the current active stage with neutral styling", () => { + render(); + const region = screen.getByRole("region", { name: "Etapa do processo" }); + expect(region.className).toContain("border-border"); + expect(steps().find((step) => step.current)?.label).toContain("Documentação"); + expect(steps().at(-1)?.label).toContain("Concluído"); + }); + + it("keeps PROCESSING_CONTRACT inside the negotiation step", () => { + render(); + expect(steps().find((step) => step.current)?.label).toContain("Negociação"); + expect(screen.getByText("O contrato está sendo preparado.")).toBeTruthy(); + }); + + it("shows completion with the success tone and recorded dates", () => { + render( + , + ); + const region = screen.getByRole("region", { name: "Etapa do processo" }); + expect(region.className).toContain("bg-status-ok-wash"); + expect(steps().some((step) => step.current)).toBe(false); + expect(region.textContent).toContain( + new Date("2099-02-01T12:00:00.000Z").toLocaleDateString("pt-BR", { dateStyle: "short" }), + ); + }); + + it("shows rejection with the danger tone, only reached steps and no reason", () => { + render( + , + ); + const region = screen.getByRole("region", { name: "Etapa do processo" }); + expect(region.className).toContain("bg-status-bad-wash"); + expect(steps().at(-1)?.label).toContain("Rejeitado"); + // Documentação não foi alcançada: sem data e sem check. + const documentation = screen.getAllByRole("listitem")[2]; + expect(documentation.querySelector("svg")).toBeNull(); + expect(region.textContent).toContain("Este processo foi encerrado sem conclusão."); + }); +}); diff --git a/frontend/src/components/processes/ProductProcessTimeline.tsx b/frontend/src/components/processes/ProductProcessTimeline.tsx new file mode 100644 index 0000000..226c646 --- /dev/null +++ b/frontend/src/components/processes/ProductProcessTimeline.tsx @@ -0,0 +1,154 @@ +import { Check, CheckCircle, XCircle } from "lucide-react"; +import { cn } from "../../lib/utils"; +import { StatusBadge } from "../patterns/StatusBadge"; +import type { + ProductProcessStatus, + ProductProcessSummary, +} from "../../services/appointments.service"; + +// Mesmos passos do ProcessCard: PROCESSING_CONTRACT fica entre Negociação e Documentação. +const STEP_INDEX: Record = { + SCHEDULING: 0, + NEGOTIATION: 1, + PROCESSING_CONTRACT: 1.5, + DOCUMENTATION: 2, + COMPLETED: 3, + REJECTED: 3, +}; + +const STEPS: { label: string; statuses: ProductProcessStatus[] }[] = [ + { label: "Agendamento", statuses: ["SCHEDULING"] }, + { label: "Negociação", statuses: ["NEGOTIATION", "PROCESSING_CONTRACT"] }, + { label: "Documentação", statuses: ["DOCUMENTATION"] }, +]; + +const STAGE_DESCRIPTION: Record = { + SCHEDULING: "Sua reunião com o especialista está sendo agendada.", + NEGOTIATION: "Você está negociando os valores com o especialista.", + PROCESSING_CONTRACT: "O contrato está sendo preparado.", + DOCUMENTATION: "Os documentos da compra estão sendo reunidos.", + COMPLETED: "Este processo foi concluído.", + REJECTED: "Este processo foi encerrado sem conclusão.", +}; + +function formatDate(value: string | undefined): string | null { + if (!value) return null; + const date = new Date(value); + return Number.isNaN(date.getTime()) + ? null + : date.toLocaleDateString("pt-BR", { dateStyle: "short" }); +} + +/** Linha do tempo do processo do próprio cliente; sem motivo de rejeição. */ +export default function ProductProcessTimeline({ + process, +}: { + process: ProductProcessSummary; +}) { + const isCompleted = process.status === "COMPLETED"; + const isRejected = process.status === "REJECTED"; + // Rejeição pode ocorrer em qualquer etapa: só marca como feitas as que o histórico registra. + const reachedIndex = isRejected + ? Math.max( + -1, + ...process.status_history + .filter((entry) => entry.status !== "REJECTED") + .map((entry) => STEP_INDEX[entry.status]), + ) + : STEP_INDEX[process.status]; + const lastChange = (statuses: ProductProcessStatus[]) => + formatDate( + process.status_history.filter((entry) => statuses.includes(entry.status)) + .at(-1)?.changed_at, + ); + const steps = [ + ...STEPS, + { + label: isRejected ? "Rejeitado" : "Concluído", + statuses: [isRejected ? "REJECTED" : "COMPLETED"] as ProductProcessStatus[], + }, + ]; + + return ( +
+
+ {isCompleted && ( +
+

+ {STAGE_DESCRIPTION[process.status]} +

+
    + {steps.map((step, index) => { + const isFinal = index === steps.length - 1; + // Na rejeição, a etapa em que o processo parou também foi alcançada. + const done = isFinal + ? isCompleted || isRejected + : isRejected + ? index <= reachedIndex + : index < reachedIndex; + const current = + !isFinal && !isCompleted && !isRejected && index === Math.floor(reachedIndex); + const date = lastChange(step.statuses); + return ( +
  1. + + {isFinal && isRejected ? ( + + + + {step.label} + + {date && (done || current) && ( + {date} + )} + +
  2. + ); + })} +
+
+ ); +} diff --git a/frontend/src/hooks/useCheckAppointment.test.tsx b/frontend/src/hooks/useCheckAppointment.test.tsx index 14c5d1f..9d96b0f 100644 --- a/frontend/src/hooks/useCheckAppointment.test.tsx +++ b/frontend/src/hooks/useCheckAppointment.test.tsx @@ -14,6 +14,7 @@ vi.mock("../services/appointments.service", () => ({ checkExistingAppointment: v 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", + process: { id: "process-1", status: "SCHEDULING", is_active: true, status_history: [] }, }; function deferred() { @@ -29,7 +30,7 @@ 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 }); }); +beforeEach(() => { useAuth.setState({ user: customer }); vi.useFakeTimers(); vi.mocked(checkExistingAppointment).mockResolvedValue({ exists: false, process: null }); }); afterEach(() => { cleanup(); useAuth.setState({ user: null }); vi.useRealTimers(); vi.resetAllMocks(); }); describe("owned appointment check hook", () => { @@ -61,7 +62,7 @@ describe("owned appointment check hook", () => { it.each(scopeChanges.flatMap((change) => [ { ...change, previous: found, resultName: "snapshot" }, - { ...change, previous: { exists: false } as ExistingAppointmentCheck, resultName: "verified absence" }, + { ...change, previous: { exists: false, process: null } 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[] = []; @@ -105,7 +106,7 @@ describe("owned appointment check hook", () => { it.each([ { name: "snapshot", value: found }, - { name: "verified absence", value: { exists: false } as ExistingAppointmentCheck }, + { name: "verified absence", value: { exists: false, process: null } as ExistingAppointmentCheck }, { name: "rejection", value: null }, ])("discards a stale $name across an account switch in every commit", async ({ value }) => { const earlier = deferred(); @@ -167,10 +168,36 @@ describe("owned appointment check hook", () => { expect(result.current).toEqual({ existingAppointment: found, isLoading: false, error: null }); }); + it("refetches silently when the tab becomes visible, keeping the last result", async () => { + const advanced: ExistingAppointmentCheck = { + ...found, appointment_id: null, appointment_status: null, scheduling_method: null, appointment_datetime: null, + process: { id: "process-1", status: "NEGOTIATION", is_active: true, status_history: [] }, + }; + vi.mocked(checkExistingAppointment).mockResolvedValueOnce(found).mockResolvedValueOnce(advanced); + const { result } = renderHook(() => useCheckAppointment("specialist-1", "CAR", "car-1")); + await advance(); + expect(result.current.existingAppointment).toEqual(found); + act(() => { document.dispatchEvent(new Event("visibilitychange")); }); + expect(result.current).toEqual({ existingAppointment: found, isLoading: false, error: null }); + await advance(); + expect(checkExistingAppointment).toHaveBeenCalledTimes(2); + expect(result.current).toEqual({ existingAppointment: advanced, isLoading: false, error: null }); + }); + + it("keeps the last result when a focus refetch fails", async () => { + vi.mocked(checkExistingAppointment).mockResolvedValueOnce(found).mockRejectedValueOnce(new Error("offline")); + const { result } = renderHook(() => useCheckAppointment("specialist-1", "CAR", "car-1")); + await advance(); + act(() => { document.dispatchEvent(new Event("visibilitychange")); }); + await advance(); + expect(checkExistingAppointment).toHaveBeenCalledTimes(2); + 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.existingAppointment).toEqual({ exists: false, process: null }); expect(result.current.error).toBeNull(); }); @@ -201,7 +228,7 @@ describe("owned appointment check hook", () => { rerender({ productId: "car-2" }); expect(result.current).toEqual({ existingAppointment: null, isLoading: true, error: null }); await advance(); - expect(result.current.existingAppointment).toEqual({ exists: false }); + expect(result.current.existingAppointment).toEqual({ exists: false, process: null }); }); it("uses a readable fallback for a non-Error rejection", async () => { @@ -221,19 +248,19 @@ describe("owned appointment check hook", () => { 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 }); + await act(async () => { latest.resolve({ exists: false, process: null }); }); + expect(result.current).toEqual({ existingAppointment: { exists: false, process: null }, 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 }); + vi.mocked(checkExistingAppointment).mockReturnValueOnce(earlier.promise).mockResolvedValueOnce({ exists: false, process: null }); 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 }); + expect(result.current).toEqual({ existingAppointment: { exists: false, process: null }, isLoading: false, error: null }); }); it("invalidates an in-flight response when parameters become missing", async () => { @@ -269,12 +296,12 @@ describe("owned appointment check hook", () => { 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 }); + expect(result.current).toEqual({ existingAppointment: { exists: false, process: null }, 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 }); + vi.mocked(checkExistingAppointment).mockReturnValueOnce(earlier.promise).mockResolvedValueOnce({ exists: false, process: null }); const { result } = renderHook(() => useCheckAppointment("specialist-1", "CAR", "car-1")); await advance(); act(() => { useAuth.setState({ user: { ...customer, id: "customer-2" } }); }); @@ -283,7 +310,7 @@ describe("owned appointment check hook", () => { expect(result.current.existingAppointment).toBeNull(); await advance(); expect(checkExistingAppointment).toHaveBeenCalledTimes(2); - expect(result.current.existingAppointment).toEqual({ exists: false }); + expect(result.current.existingAppointment).toEqual({ exists: false, process: null }); }); it.each([null, { ...customer, role: "SPECIALIST" as const }])("does not check for a missing or non-customer identity", async (user) => { diff --git a/frontend/src/hooks/useCheckAppointment.ts b/frontend/src/hooks/useCheckAppointment.ts index 3f14a53..47cdb86 100644 --- a/frontend/src/hooks/useCheckAppointment.ts +++ b/frontend/src/hooks/useCheckAppointment.ts @@ -9,7 +9,10 @@ interface UseCheckAppointmentResult { error: string | null; } -/** Debounced own-request check; null means unchecked/failed, exists:false means a successful absence. */ +/** + * Debounced own-request check; null means unchecked/failed, exists:false means a successful absence. + * Refetches silently when the tab becomes visible again, keeping the last result meanwhile. + */ export function useCheckAppointment( specialistId: string | undefined, productType: "CAR" | "BOAT" | "AIRCRAFT" | undefined, @@ -23,6 +26,16 @@ export function useCheckAppointment( scopeKey, existingAppointment: null, isLoading: isEligible, error: null, })); const requestToken = useRef(0); + const [refreshTick, setRefreshTick] = useState(0); + + useEffect(() => { + if (!isEligible) return; + const onVisibilityChange = () => { + if (document.visibilityState === "visible") setRefreshTick((tick) => tick + 1); + }; + document.addEventListener("visibilitychange", onVisibilityChange); + return () => document.removeEventListener("visibilitychange", onVisibilityChange); + }, [isEligible]); useEffect(() => { const token = ++requestToken.current; @@ -30,7 +43,11 @@ export function useCheckAppointment( setState({ scopeKey, existingAppointment: null, isLoading: false, error: null }); return () => { requestToken.current = token + 1; }; } - setState({ scopeKey, existingAppointment: null, isLoading: true, error: null }); + // A focus refresh keeps the current result instead of flashing the loading state. + setState((previous) => + previous.scopeKey === scopeKey && previous.existingAppointment + ? previous + : { scopeKey, existingAppointment: null, isLoading: true, error: null }); const timer = setTimeout(async () => { try { const result = await checkExistingAppointment(specialistId, productType, productId); @@ -39,10 +56,13 @@ export function useCheckAppointment( } } catch (error) { if (token === requestToken.current) { - setState({ - scopeKey, existingAppointment: null, isLoading: false, - error: error instanceof Error ? error.message : "Erro ao verificar agendamentos", - }); + setState((previous) => + previous.scopeKey === scopeKey && previous.existingAppointment + ? previous + : { + scopeKey, existingAppointment: null, isLoading: false, + error: error instanceof Error ? error.message : "Erro ao verificar agendamentos", + }); } } }, 500); @@ -50,7 +70,7 @@ export function useCheckAppointment( requestToken.current = token + 1; clearTimeout(timer); }; - }, [userId, role, specialistId, productType, productId, scopeKey]); + }, [userId, role, specialistId, productType, productId, scopeKey, refreshTick]); // Scope changes must be safe during render, before passive effects reset state. if (!isEligible || state.scopeKey !== scopeKey) { diff --git a/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx b/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx index 8c3b8a7..0fa2dbb 100644 --- a/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx +++ b/frontend/src/pages/catalog/ProductPage.calendly.integration.test.tsx @@ -113,7 +113,7 @@ describe("delegated EMAIL flow with the real Radix dialog", () => { updated_at: "2026-01-01T00:00:00.000Z", }); vi.mocked(getPublicSpecialistById).mockResolvedValue(specialist); - vi.mocked(checkExistingAppointment).mockResolvedValue({ exists: false }); + vi.mocked(checkExistingAppointment).mockResolvedValue({ exists: false, process: null }); vi.mocked(getClients).mockResolvedValue([client]); vi.mocked(officeService.listClients).mockResolvedValue([ { diff --git a/frontend/src/pages/catalog/ProductPage.test.tsx b/frontend/src/pages/catalog/ProductPage.test.tsx index dedad5d..1019faa 100644 --- a/frontend/src/pages/catalog/ProductPage.test.tsx +++ b/frontend/src/pages/catalog/ProductPage.test.tsx @@ -124,6 +124,13 @@ const existingRequest: ActiveProcessSnapshot = { specialist_contact_email: "private-specialist@example.com", }; +const activeProcess = { + id: "process-1", + status: "SCHEDULING" as const, + is_active: true, + status_history: [], +}; + function ChangeProductButton() { const navigate = useNavigate(); return ( @@ -186,7 +193,7 @@ describe("ProductPage scheduling", () => { }; vi.mocked(getCarById).mockResolvedValue(product); vi.mocked(getPublicSpecialistById).mockResolvedValue(specialist); - vi.mocked(checkExistingAppointment).mockResolvedValue({ exists: false }); + vi.mocked(checkExistingAppointment).mockResolvedValue({ exists: false, process: null }); 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); @@ -605,6 +612,7 @@ describe("ProductPage scheduling", () => { vi.mocked(checkExistingAppointment).mockResolvedValue({ ...existingRequest, exists: true, + process: activeProcess, appointment_id: appointment.id, appointment_status: "PENDING", }); @@ -632,6 +640,7 @@ describe("ProductPage scheduling", () => { vi.mocked(checkExistingAppointment).mockResolvedValue({ ...existingRequest, exists: true, + process: activeProcess, appointment_id: "appointment-own-initial", appointment_status: "PENDING", }); @@ -654,6 +663,7 @@ describe("ProductPage scheduling", () => { it("does not compose email when an EMAIL snapshot lacks owner-scoped contact", async () => { vi.mocked(checkExistingAppointment).mockResolvedValue({ exists: true, + process: activeProcess, appointment_id: "appointment-no-contact", appointment_status: "PENDING", scheduling_method: "EMAIL", @@ -717,6 +727,7 @@ describe("ProductPage scheduling", () => { vi.mocked(checkExistingAppointment).mockResolvedValue({ ...existingRequest, exists: true, + process: activeProcess, appointment_id: "existing-other", appointment_status, scheduling_method, @@ -732,6 +743,113 @@ describe("ProductPage scheduling", () => { }, ); + it("shows an advanced active stage without appointment data and keeps scheduling blocked", async () => { + vi.mocked(checkExistingAppointment).mockResolvedValue({ + exists: true, + appointment_id: null, + process_id: "process-1", + appointment_status: null, + scheduling_method: null, + appointment_datetime: null, + process: { + ...activeProcess, + status: "NEGOTIATION", + status_history: [ + { status: "SCHEDULING", changed_at: "2099-01-01T10:00:00.000Z" }, + { status: "NEGOTIATION", changed_at: "2099-01-02T10:00:00.000Z" }, + ], + }, + }); + render(page()); + const stage = await screen.findByRole( + "region", + { name: "Etapa do processo" }, + { timeout: 2000 }, + ); + expect(stage.textContent).toContain("Negociação"); + expect( + stage.querySelector('[aria-current="step"]')?.textContent, + ).toContain("Negociação"); + expect( + screen.getByText("Você já possui um processo ativo para este produto"), + ).toBeTruthy(); + expect( + screen.queryByRole("button", { name: "Solicitar reunião" }), + ).toBeNull(); + }); + + it("shows a completed process without offering a new scheduling", async () => { + vi.mocked(checkExistingAppointment).mockResolvedValue({ + exists: false, + process: { ...activeProcess, status: "COMPLETED", is_active: false }, + }); + render(page()); + const stage = await screen.findByRole( + "region", + { name: "Etapa do processo" }, + { timeout: 2000 }, + ); + expect(stage.textContent).toContain("Este processo foi concluído."); + expect( + screen + .getByRole("link", { name: "Acompanhar processo" }) + .getAttribute("href"), + ).toBe("/customer/processes"); + expect( + screen.queryByRole("button", { name: "Fazer novo agendamento" }), + ).toBeNull(); + expect( + screen.queryByRole("button", { name: "Solicitar reunião" }), + ).toBeNull(); + }); + + it("offers a new scheduling only after a rejected process is acknowledged", async () => { + vi.mocked(checkExistingAppointment).mockResolvedValue({ + exists: false, + process: { + ...activeProcess, + status: "REJECTED", + is_active: false, + status_history: [ + { status: "SCHEDULING", changed_at: "2099-01-01T10:00:00.000Z" }, + { status: "REJECTED", changed_at: "2099-01-03T10:00:00.000Z" }, + ], + }, + }); + render(page()); + const stage = await screen.findByRole( + "region", + { name: "Etapa do processo" }, + { timeout: 2000 }, + ); + expect(stage.textContent).toContain("Rejeitado"); + expect( + screen.queryByRole("button", { name: "Solicitar reunião" }), + ).toBeNull(); + fireEvent.click( + screen.getByRole("button", { name: "Fazer novo agendamento" }), + ); + expect( + screen.getByRole("button", { name: "Solicitar reunião" }), + ).toBeTruthy(); + }); + + it("does not check or show process data for a visitor", async () => { + (authState as { user: unknown }).user = null; + render(page()); + expect( + await screen.findByRole( + "button", + { name: "Criar Conta para Agendar" }, + { timeout: 2000 }, + ), + ).toBeTruthy(); + expect(checkExistingAppointment).not.toHaveBeenCalled(); + expect( + screen.queryByRole("region", { name: "Etapa do processo" }), + ).toBeNull(); + }); + it("blocks creation when the own-request check fails", async () => { vi.mocked(checkExistingAppointment).mockRejectedValue( new Error("check unavailable"), diff --git a/frontend/src/pages/catalog/ProductPage.tsx b/frontend/src/pages/catalog/ProductPage.tsx index 9eed3a8..e0a6246 100644 --- a/frontend/src/pages/catalog/ProductPage.tsx +++ b/frontend/src/pages/catalog/ProductPage.tsx @@ -16,6 +16,7 @@ import { createPendingAppointment, getActiveProcessSnapshot, type ActiveProcessSnapshot, + type ProductProcessSummary, type ProductPendingAppointmentInput, type PendingAppointmentCreated, } from "../../services/appointments.service"; @@ -35,6 +36,7 @@ import StartProcessForClientModal from "../../components/processes/StartProcessF import AppointmentDateTimeModal from "../../components/appointments/AppointmentDateTimeModal"; import NoCalendlySchedulingActions from "../../components/appointments/NoCalendlySchedulingActions"; import EmailSchedulingSuccess from "../../components/appointments/EmailSchedulingSuccess"; +import ProductProcessTimeline from "../../components/processes/ProductProcessTimeline"; import { useAuth } from "../../store/authStateManager"; import { useCheckAppointment } from "../../hooks/useCheckAppointment"; import { useCalendlyScheduling } from "../../hooks/useCalendlyScheduling"; @@ -122,6 +124,7 @@ export default function ProductPage() { const [isDateTimeModalOpen, setIsDateTimeModalOpen] = useState(false); const [dateTimeError, setDateTimeError] = useState(null); const [creationNotice, setCreationNotice] = useState(null); + const [isNewSchedulingOpen, setIsNewSchedulingOpen] = useState(false); const scopeKey = JSON.stringify([ user?.id, user?.role, @@ -154,6 +157,7 @@ export default function ProductPage() { setIsDateTimeModalOpen(false); setDateTimeError(null); setCreationNotice(null); + setIsNewSchedulingOpen(false); }, [scopeKey]); const { @@ -199,6 +203,22 @@ export default function ProductPage() { const emailRequest = isPendingEmailRequest(currentRequest) ? currentRequest : null; + // Etapa do processo, separada do estado do agendamento. Um pedido recém-criado + // ainda não refletido pelo servidor começa em SCHEDULING. + const serverProcess = existingAppointment?.process ?? null; + const displayedProcess: ProductProcessSummary | null = + localRequest && !serverProcess?.is_active + ? { + id: localRequest.snapshot.process_id, + status: "SCHEDULING", + is_active: true, + status_history: [], + } + : serverProcess; + const closedProcess = + !currentRequest && serverProcess && !serverProcess.is_active + ? serverProcess + : null; const categoryMap: Record = { car: "cars", @@ -485,6 +505,9 @@ export default function ProductPage() { {creationNotice || calendlySyncMessage} )} + {user?.role === "CUSTOMER" && displayedProcess && ( + + )} {!user ? (
@@ -606,6 +629,21 @@ export default function ProductPage() { Acompanhar processo
+ ) : closedProcess?.status === "COMPLETED" ? ( + + Acompanhar processo + + ) : closedProcess && !isNewSchedulingOpen ? ( + ) : checkAppointmentError ? (

diff --git a/frontend/src/services/appointments.service.ts b/frontend/src/services/appointments.service.ts index 0904fb9..7a25772 100644 --- a/frontend/src/services/appointments.service.ts +++ b/frontend/src/services/appointments.service.ts @@ -57,16 +57,34 @@ export interface ApiResponse { data: T; } +export type ProductProcessStatus = + | "SCHEDULING" + | "NEGOTIATION" + | "PROCESSING_CONTRACT" + | "DOCUMENTATION" + | "COMPLETED" + | "REJECTED"; + +/** Processo do cliente no produto: o ativo ou, sem ativo, o encerrado mais recente. */ +export interface ProductProcessSummary { + id: string; + status: ProductProcessStatus; + is_active: boolean; + status_history: { status: ProductProcessStatus; changed_at: string }[]; +} + +/** exists indica processo ativo; campos de agendamento só para agendamento vigente. */ export type ExistingAppointmentCheck = - | { exists: false } + | { exists: false; process: ProductProcessSummary | null } | { exists: true; - appointment_id: string; + appointment_id: string | null; process_id: string; - appointment_status: Appointment["status"]; + appointment_status: Appointment["status"] | null; scheduling_method: AppointmentSchedulingMethod | null; appointment_datetime: string | null; specialist_contact_email?: string; + process: ProductProcessSummary; }; export interface ActiveProcessSnapshot { From 6d8839c98e2d47d5948194bbc285585161c6a4a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius?= Date: Thu, 29 Oct 2026 19:46:02 -0300 Subject: [PATCH 03/11] docs(architecture): document process stage in appointments check Refs #253 --- architecture.md | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/architecture.md b/architecture.md index ea79649..2144bc6 100644 --- a/architecture.md +++ b/architecture.md @@ -699,25 +699,35 @@ Controllers: ### Appointments - `GET /appointments/check` - - payload: -```json -{ - "client_id": "", - "specialist_id": "", - "product_type": "CAR", - "product_id": 0 -} -``` - - resposta: + - Apenas `CUSTOMER` (outros papéis: 403). O cliente vem do JWT; enviar `client_id` retorna 400. + - Query: `specialist_id`, `product_type` (`CAR` | `BOAT` | `AIRCRAFT`), `product_id` + - `exists`: há processo **ativo** (`SCHEDULING`…`DOCUMENTATION`) do cliente para o produto — é a trava anti-duplicidade do agendamento. + - `process`: o processo ativo ou, sem ativo, o `COMPLETED`/`REJECTED` mais recente (`null` se nunca houve). O histórico expõe só `status` + `changed_at`; o motivo de rejeição não é retornado. + - Campos de agendamento só para agendamento vigente (`PENDING`/`SCHEDULED`); senão `null`. `specialist_contact_email` só para pedido `EMAIL`. + - resposta (processo ativo): ```json { "success": true, "data": { - "id": "", - "status": "PENDING" + "exists": true, + "appointment_id": null, + "process_id": "uuid", + "appointment_status": null, + "scheduling_method": null, + "appointment_datetime": null, + "process": { + "id": "uuid", + "status": "NEGOTIATION", + "is_active": true, + "status_history": [ + { "status": "SCHEDULING", "changed_at": "2026-10-01T12:00:00.000Z" }, + { "status": "NEGOTIATION", "changed_at": "2026-10-03T12:00:00.000Z" } + ] + } } } ``` + - resposta (sem processo ativo): `{ "exists": false, "process": { "status": "REJECTED", "is_active": false, ... } | null }` - `GET /appointments` - Query: paginação - Resposta: lista de agendamentos do usuário From 220ff99f7001b84f482cac915108c1b9ac936acf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius?= Date: Thu, 29 Oct 2026 19:46:02 -0300 Subject: [PATCH 04/11] docs(appointments): note why updated_at dates the latest closed process Refs #253 --- backend/src/features/appointments/appointments.service.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 8e3051b..96a7a7e 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -2069,6 +2069,9 @@ export class AppointmentsService { }, }; // Ativo tem prioridade; sem ativo, mostra o encerrado mais recente. + // updated_at serve como data de encerramento porque processo COMPLETED/ + // REJECTED com produto não recebe mais escrita (transições não saem de + // estado terminal); se isso mudar, ordenar pelo ProcessStatusHistory. const process = (await this.prisma.process.findFirst({ where: { ...scope, status: { in: ACTIVE_PROCESS_STATUSES } }, From 4f4639ccfe375d42abf34580d7b4a72381b60a5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius?= Date: Thu, 29 Oct 2026 19:56:12 -0300 Subject: [PATCH 05/11] fix(frontend): simplify the process timeline header and contract step MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drop the status pill from the timeline header; the stage description and the steps already identify the stage. During PROCESSING_CONTRACT, "Negociação" was marked both done and current; show it only as the current step, with the description saying the contract is being prepared. Refs #253 --- .../components/processes/ProductProcessTimeline.test.tsx | 4 ++++ .../src/components/processes/ProductProcessTimeline.tsx | 8 ++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/frontend/src/components/processes/ProductProcessTimeline.test.tsx b/frontend/src/components/processes/ProductProcessTimeline.test.tsx index 4363f2e..cd4ba0e 100644 --- a/frontend/src/components/processes/ProductProcessTimeline.test.tsx +++ b/frontend/src/components/processes/ProductProcessTimeline.test.tsx @@ -34,6 +34,10 @@ describe("ProductProcessTimeline", () => { it("keeps PROCESSING_CONTRACT inside the negotiation step", () => { render(); expect(steps().find((step) => step.current)?.label).toContain("Negociação"); + const negotiation = screen.getAllByRole("listitem")[1]; + // Etapa atual mostra o número, não o check de concluída. + expect(negotiation.querySelector("svg")).toBeNull(); + expect(screen.getAllByRole("listitem")[0].querySelector("svg")).not.toBeNull(); expect(screen.getByText("O contrato está sendo preparado.")).toBeTruthy(); }); diff --git a/frontend/src/components/processes/ProductProcessTimeline.tsx b/frontend/src/components/processes/ProductProcessTimeline.tsx index 226c646..460b4f1 100644 --- a/frontend/src/components/processes/ProductProcessTimeline.tsx +++ b/frontend/src/components/processes/ProductProcessTimeline.tsx @@ -1,6 +1,5 @@ import { Check, CheckCircle, XCircle } from "lucide-react"; import { cn } from "../../lib/utils"; -import { StatusBadge } from "../patterns/StatusBadge"; import type { ProductProcessStatus, ProductProcessSummary, @@ -88,8 +87,7 @@ export default function ProductProcessTimeline({ {isRejected && (

Etapa do processo:

- +

Etapa do processo

{STAGE_DESCRIPTION[process.status]} @@ -98,11 +96,13 @@ export default function ProductProcessTimeline({ {steps.map((step, index) => { const isFinal = index === steps.length - 1; // Na rejeição, a etapa em que o processo parou também foi alcançada. + // Em PROCESSING_CONTRACT (1.5), Negociação segue como etapa atual, sem check; + // a descrição informa que o contrato está sendo preparado. const done = isFinal ? isCompleted || isRejected : isRejected ? index <= reachedIndex - : index < reachedIndex; + : index < Math.floor(reachedIndex); const current = !isFinal && !isCompleted && !isRejected && index === Math.floor(reachedIndex); const date = lastChange(step.statuses); From 3ce25eac31af6bf601f6850b3db7f4dc12b66864 Mon Sep 17 00:00:00 2001 From: "luiz.cazelatto" Date: Fri, 30 Oct 2026 11:42:59 -0300 Subject: [PATCH 06/11] feat(products): admin transfere produto para outro especialista PATCH /cars|boats|aircrafts/:id/specialist (somente ADMIN) valida o especialista de destino (ativo, mesma especialidade), bloqueia com 409 PRODUCT_HAS_OPEN_PROCESSES se houver processo ou agendamento em andamento e audita como PRODUCT_TRANSFER. A jornada admin ganha a acao Transferir no catalogo do especialista. Closes #250 --- architecture.md | 14 ++ .../aircrafts/aircrafts.controller.ts | 22 +++ .../src/features/boats/boats.controller.ts | 22 +++ backend/src/features/cars/cars.controller.ts | 22 +++ .../products/dto/transfer-product.dto.ts | 6 + .../products/product-monetary-lock.ts | 4 +- .../products/product-transfer.spec.ts | 154 ++++++++++++++++++ .../src/features/products/product-transfer.ts | 125 ++++++++++++++ .../admin/SpecialistJourneyProductsPage.tsx | 72 +++++++- .../admin-specialist-journey.service.ts | 13 ++ 10 files changed, 449 insertions(+), 5 deletions(-) create mode 100644 backend/src/features/products/dto/transfer-product.dto.ts create mode 100644 backend/src/features/products/product-transfer.spec.ts create mode 100644 backend/src/features/products/product-transfer.ts diff --git a/architecture.md b/architecture.md index 2144bc6..f049ca0 100644 --- a/architecture.md +++ b/architecture.md @@ -362,6 +362,20 @@ Cada domínio expõe: "updated": true } ``` +- `PATCH /cars|boats|aircrafts/:id/specialist` (somente ADMIN) — transfere o produto para outro especialista ativo da mesma especialidade. `409 PRODUCT_HAS_OPEN_PROCESSES` se houver processo não concluído/rejeitado ou agendamento pendente/agendado; processos antigos mantêm o especialista original. Auditado como `PRODUCT_TRANSFER`. + - payload: +```json +{ + "specialist_id": "uuid" +} +``` + - resposta: +```json +{ + "fromSpecialistId": "uuid", + "toSpecialistId": "uuid" +} +``` - `DELETE /cars|boats|aircrafts/:id` - payload: ```json diff --git a/backend/src/features/aircrafts/aircrafts.controller.ts b/backend/src/features/aircrafts/aircrafts.controller.ts index 446bd77..fa2c008 100644 --- a/backend/src/features/aircrafts/aircrafts.controller.ts +++ b/backend/src/features/aircrafts/aircrafts.controller.ts @@ -37,6 +37,8 @@ import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated- import { ProductCsvImportDto } from '../product-import-jobs/dto/product-csv-import.dto'; import { PrismaService } from 'src/prisma/prisma.service'; import { randomUUID } from 'node:crypto'; +import { TransferProductDto } from '../products/dto/transfer-product.dto'; +import { transferProductAsAdmin } from '../products/product-transfer'; @Controller('aircrafts') export class AircraftsController { @@ -259,6 +261,26 @@ export class AircraftsController { return this.aircraftsService.findOne(id); } + @Patch(':id/specialist') + @Roles(UserRole.ADMIN) + transferSpecialist( + @Param('id') id: string, + @Body() body: TransferProductDto, + @CurrentUser() user: UserEntity, + ) { + return transferProductAsAdmin( + { + prisma: this.prisma, + actorContextService: this.actorContextService, + delegatedAudit: this.delegatedAudit, + }, + user, + ProductType.AIRCRAFT, + id, + body.specialist_id, + ); + } + @Patch(':id') @Roles(UserRole.ADMIN, UserRole.SPECIALIST) async update( diff --git a/backend/src/features/boats/boats.controller.ts b/backend/src/features/boats/boats.controller.ts index 55cad87..c1c6e55 100644 --- a/backend/src/features/boats/boats.controller.ts +++ b/backend/src/features/boats/boats.controller.ts @@ -37,6 +37,8 @@ import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated- import { ProductCsvImportDto } from '../product-import-jobs/dto/product-csv-import.dto'; import { PrismaService } from 'src/prisma/prisma.service'; import { randomUUID } from 'node:crypto'; +import { TransferProductDto } from '../products/dto/transfer-product.dto'; +import { transferProductAsAdmin } from '../products/product-transfer'; @Controller('boats') export class BoatsController { @@ -257,6 +259,26 @@ export class BoatsController { return this.boatsService.findOne(id); } + @Patch(':id/specialist') + @Roles(UserRole.ADMIN) + transferSpecialist( + @Param('id') id: string, + @Body() body: TransferProductDto, + @CurrentUser() user: UserEntity, + ) { + return transferProductAsAdmin( + { + prisma: this.prisma, + actorContextService: this.actorContextService, + delegatedAudit: this.delegatedAudit, + }, + user, + ProductType.BOAT, + id, + body.specialist_id, + ); + } + @Patch(':id') @Roles(UserRole.ADMIN, UserRole.SPECIALIST) async update( diff --git a/backend/src/features/cars/cars.controller.ts b/backend/src/features/cars/cars.controller.ts index 4e7fe34..4574347 100644 --- a/backend/src/features/cars/cars.controller.ts +++ b/backend/src/features/cars/cars.controller.ts @@ -34,6 +34,8 @@ import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated- import { ProductCsvImportDto } from '../product-import-jobs/dto/product-csv-import.dto'; import { PrismaService } from 'src/prisma/prisma.service'; import { randomUUID } from 'node:crypto'; +import { TransferProductDto } from '../products/dto/transfer-product.dto'; +import { transferProductAsAdmin } from '../products/product-transfer'; @Controller('cars') export class CarsController { @@ -254,6 +256,26 @@ export class CarsController { return this.carsService.findOne(id); } + @Patch(':id/specialist') + @Roles(UserRole.ADMIN) + transferSpecialist( + @Param('id') id: string, + @Body() body: TransferProductDto, + @CurrentUser() user: UserEntity, + ) { + return transferProductAsAdmin( + { + prisma: this.prisma, + actorContextService: this.actorContextService, + delegatedAudit: this.delegatedAudit, + }, + user, + ProductType.CAR, + id, + body.specialist_id, + ); + } + @Patch(':id') @Roles(UserRole.ADMIN, UserRole.SPECIALIST) async update( diff --git a/backend/src/features/products/dto/transfer-product.dto.ts b/backend/src/features/products/dto/transfer-product.dto.ts new file mode 100644 index 0000000..563cc49 --- /dev/null +++ b/backend/src/features/products/dto/transfer-product.dto.ts @@ -0,0 +1,6 @@ +import { IsUUID } from 'class-validator'; + +export class TransferProductDto { + @IsUUID() + specialist_id: string; +} diff --git a/backend/src/features/products/product-monetary-lock.ts b/backend/src/features/products/product-monetary-lock.ts index 2a9917d..90383a4 100644 --- a/backend/src/features/products/product-monetary-lock.ts +++ b/backend/src/features/products/product-monetary-lock.ts @@ -48,13 +48,13 @@ type TransactionLockClient = { ): Promise; }; -const PRODUCT_DELEGATE_BY_TYPE = { +export const PRODUCT_DELEGATE_BY_TYPE = { [ProductType.CAR]: 'car', [ProductType.BOAT]: 'boat', [ProductType.AIRCRAFT]: 'aircraft', } as const; -const PROCESS_FOREIGN_KEY_BY_TYPE = { +export const PROCESS_FOREIGN_KEY_BY_TYPE = { [ProductType.CAR]: 'car_id', [ProductType.BOAT]: 'boat_id', [ProductType.AIRCRAFT]: 'aircraft_id', diff --git a/backend/src/features/products/product-transfer.spec.ts b/backend/src/features/products/product-transfer.spec.ts new file mode 100644 index 0000000..495cae1 --- /dev/null +++ b/backend/src/features/products/product-transfer.spec.ts @@ -0,0 +1,154 @@ +import { + BadRequestException, + ConflictException, + ForbiddenException, + NotFoundException, +} from '@nestjs/common'; +import { ProductType, UserRole } from '@prisma/client'; +import { + transferProductAsAdmin, + transferProductSpecialist, +} from './product-transfer'; + +function db(overrides: Record = {}) { + return { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + car: { + findUnique: jest + .fn() + .mockResolvedValue({ id: 'car-1', specialist_id: 'old' }), + update: jest.fn().mockResolvedValue({}), + }, + process: { findFirst: jest.fn().mockResolvedValue(null) }, + appointment: { findFirst: jest.fn().mockResolvedValue(null) }, + ...overrides, + } as any; +} + +const input = { + productType: ProductType.CAR, + productId: 'car-1', + toSpecialistId: 'new', +}; + +describe('transferProductSpecialist', () => { + it('locks the product, then moves it to the new specialist', async () => { + const tx = db(); + + await expect(transferProductSpecialist(tx, input)).resolves.toEqual({ + fromSpecialistId: 'old', + toSpecialistId: 'new', + }); + + expect(tx.$queryRaw).toHaveBeenCalledWith( + expect.anything(), + 'product-money:CAR:car-1', + ); + expect(tx.car.update).toHaveBeenCalledWith({ + where: { id: 'car-1' }, + data: { specialist_id: 'new' }, + }); + }); + + it('only counts non-terminal, non-removed processes as open', async () => { + const tx = db(); + + await transferProductSpecialist(tx, input); + + expect(tx.process.findFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: { + car_id: 'car-1', + status: { notIn: ['COMPLETED', 'REJECTED'] }, + removed_at: null, + }, + }), + ); + }); + + it('blocks when a process is in progress', async () => { + const tx = db({ + process: { findFirst: jest.fn().mockResolvedValue({ id: 'p-1' }) }, + }); + + await expect(transferProductSpecialist(tx, input)).rejects.toBeInstanceOf( + ConflictException, + ); + expect(tx.car.update).not.toHaveBeenCalled(); + }); + + it('blocks when an appointment is pending or scheduled', async () => { + const tx = db({ + appointment: { findFirst: jest.fn().mockResolvedValue({ id: 'a-1' }) }, + }); + + await expect(transferProductSpecialist(tx, input)).rejects.toBeInstanceOf( + ConflictException, + ); + expect(tx.car.update).not.toHaveBeenCalled(); + }); + + it('rejects missing products and no-op transfers', async () => { + const missing = db({ + car: { findUnique: jest.fn().mockResolvedValue(null), update: jest.fn() }, + }); + await expect( + transferProductSpecialist(missing, input), + ).rejects.toBeInstanceOf(NotFoundException); + + await expect( + transferProductSpecialist(db(), { ...input, toSpecialistId: 'old' }), + ).rejects.toBeInstanceOf(BadRequestException); + }); +}); + +describe('transferProductAsAdmin', () => { + it('validates the target before touching the product and audits the change', async () => { + const tx = db(); + const context = { specialistId: 'new' }; + const deps = { + prisma: { $transaction: jest.fn((fn) => fn(tx)) }, + actorContextService: { resolve: jest.fn().mockResolvedValue(context) }, + delegatedAudit: { record: jest.fn() }, + } as any; + const admin = { id: 'admin', role: UserRole.ADMIN } as any; + + await transferProductAsAdmin(deps, admin, ProductType.CAR, 'car-1', 'new'); + + expect(deps.actorContextService.resolve).toHaveBeenCalledWith( + admin, + 'new', + ProductType.CAR, + ); + expect(deps.delegatedAudit.record).toHaveBeenCalledWith( + expect.objectContaining({ + context, + action: 'PRODUCT_TRANSFER', + resourceId: 'car-1', + metadata: { fromSpecialistId: 'old', toSpecialistId: 'new' }, + }), + tx, + ); + }); + + it('does not open a transaction when the target is rejected', async () => { + const deps = { + prisma: { $transaction: jest.fn() }, + actorContextService: { + resolve: jest.fn().mockRejectedValue(new ForbiddenException()), + }, + delegatedAudit: { record: jest.fn() }, + } as any; + + await expect( + transferProductAsAdmin( + deps, + { id: 's', role: UserRole.SPECIALIST } as any, + ProductType.CAR, + 'car-1', + 'other', + ), + ).rejects.toBeInstanceOf(ForbiddenException); + expect(deps.prisma.$transaction).not.toHaveBeenCalled(); + }); +}); diff --git a/backend/src/features/products/product-transfer.ts b/backend/src/features/products/product-transfer.ts new file mode 100644 index 0000000..b444dc7 --- /dev/null +++ b/backend/src/features/products/product-transfer.ts @@ -0,0 +1,125 @@ +import { + BadRequestException, + ConflictException, + NotFoundException, +} from '@nestjs/common'; +import { + Prisma, + ProcessStatus, + ProductType, + StatusAgendamento, +} from '@prisma/client'; +import { UserEntity } from 'src/auth/entities/user.entity'; +import { PrismaService } from 'src/prisma/prisma.service'; +import { ActorContextService } from 'src/shared/actor-context/actor-context.service'; +import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service'; +import { + acquireProductMonetaryLock, + PROCESS_FOREIGN_KEY_BY_TYPE, + PRODUCT_DELEGATE_BY_TYPE, +} from './product-monetary-lock'; + +/** + * Troca o especialista responsável por um produto. + * Bloqueia se houver processo ou agendamento em andamento: esses registros + * ficam com o especialista antigo e nunca são transferidos silenciosamente. + * Processos concluídos/rejeitados mantêm o especialista original (histórico). + */ +export async function transferProductSpecialist( + tx: Prisma.TransactionClient, + input: { + productType: ProductType; + productId: string; + toSpecialistId: string; + }, +): Promise<{ fromSpecialistId: string | null; toSpecialistId: string }> { + // Mesmo lock usado ao vincular produto a processo/agendamento. + await acquireProductMonetaryLock(tx, input); + + const delegate = (tx as any)[PRODUCT_DELEGATE_BY_TYPE[input.productType]]; + const product = await delegate.findUnique({ + where: { id: input.productId }, + select: { id: true, specialist_id: true }, + }); + if (!product) throw new NotFoundException('Produto não encontrado'); + if (product.specialist_id === input.toSpecialistId) { + throw new BadRequestException( + 'O produto já pertence a este especialista.', + ); + } + + const [openProcess, openAppointment] = await Promise.all([ + tx.process.findFirst({ + where: { + [PROCESS_FOREIGN_KEY_BY_TYPE[input.productType]]: input.productId, + status: { notIn: [ProcessStatus.COMPLETED, ProcessStatus.REJECTED] }, + removed_at: null, + }, + select: { id: true }, + }), + tx.appointment.findFirst({ + where: { + product_type: input.productType, + product_id: input.productId, + status: { + in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], + }, + }, + select: { id: true }, + }), + ]); + if (openProcess || openAppointment) { + throw new ConflictException({ + code: 'PRODUCT_HAS_OPEN_PROCESSES', + message: + 'Este produto tem processos ou agendamentos em andamento. Conclua ou rejeite-os antes de transferir.', + }); + } + + await delegate.update({ + where: { id: input.productId }, + data: { specialist_id: input.toSpecialistId }, + }); + return { + fromSpecialistId: product.specialist_id, + toSpecialistId: input.toSpecialistId, + }; +} + +/** Fluxo completo do endpoint PATCH /:resource/:id/specialist (somente ADMIN). */ +export async function transferProductAsAdmin( + deps: { + prisma: PrismaService; + actorContextService: ActorContextService; + delegatedAudit: DelegatedActionAuditService; + }, + user: UserEntity, + productType: ProductType, + productId: string, + toSpecialistId: string, +) { + // Valida destino: especialista existente, ativo e da especialidade certa. + const context = await deps.actorContextService.resolve( + user, + toSpecialistId, + productType, + ); + return deps.prisma.$transaction(async (tx) => { + const result = await transferProductSpecialist(tx, { + productType, + productId, + toSpecialistId: context.specialistId, + }); + await deps.delegatedAudit.record( + { + context, + action: 'PRODUCT_TRANSFER', + resourceType: productType, + resourceId: productId, + metadata: result, + }, + tx, + ); + return result; + }); +} diff --git a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx index a7d1134..5ce46a0 100644 --- a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx +++ b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx @@ -6,6 +6,7 @@ import { getAdminSpecialistProducts, importAdminCatalogCsv, previewAdminCatalogCsv, + transferAdminProduct, type AdminCatalogProduct, type CsvImportPreview, type ProductImportMode, @@ -13,6 +14,10 @@ import { import { deleteCar } from "../../services/cars.service"; import { deleteBoat } from "../../services/boats.service"; import { deleteAircraft } from "../../services/aircrafts.service"; +import { + getSpecialists, + type Specialist, +} from "../../services/specialists.service"; import { formatCurrency } from "../../lib/currency"; import Button from "../../components/ui/button"; import { Alert } from "../../components/ui/alert"; @@ -30,6 +35,15 @@ export default function SpecialistJourneyProductsPage() { const [preview, setPreview] = useState(null); const [syncConfirmed, setSyncConfirmed] = useState(false); const [importing, setImporting] = useState(false); + const [specialists, setSpecialists] = useState([]); + const [transferringId, setTransferringId] = useState(null); + const [transferTo, setTransferTo] = useState(""); + + useEffect(() => { + void getSpecialists() + .then(setSpecialists) + .catch(() => setSpecialists([])); + }, []); if (!context) return null; const productType = context.specialist.speciality; @@ -64,6 +78,37 @@ export default function SpecialistJourneyProductsPage() { await load(); }; + const transferTargets = specialists.filter( + (item) => + item.is_active !== false && + item.speciality === productType && + item.id !== context.targetSpecialistId, + ); + + const transfer = async (id: string) => { + const target = transferTargets.find((item) => item.id === transferTo); + if (!target) return; + if ( + !window.confirm( + `Transferir este produto para ${target.name} ${target.surname}?`, + ) + ) { + return; + } + setError(null); + try { + await transferAdminProduct(productType, id, target.id); + setTransferringId(null); + setTransferTo(""); + await load(); + } catch (caught) { + setError( + (caught as { friendlyMessage?: string })?.friendlyMessage ?? + "Não foi possível transferir o produto.", + ); + } + }; + const runPreview = async () => { if (!file) return; setError(null); @@ -126,7 +171,7 @@ export default function SpecialistJourneyProductsPage() {

Catálogo administrativo

- Itens ativos e inativos de {context.specialist.name} {context.specialist.surname}; dono imutável após a criação. + Itens ativos e inativos de {context.specialist.name} {context.specialist.surname}; transferência bloqueada enquanto houver processos em andamento.

- {product.is_active && } + {transferringId === product.id ? ( + + + + + + ) : ( + <> + + + {product.is_active && } + + )} ))} diff --git a/frontend/src/services/admin-specialist-journey.service.ts b/frontend/src/services/admin-specialist-journey.service.ts index d97abbd..e455568 100644 --- a/frontend/src/services/admin-specialist-journey.service.ts +++ b/frontend/src/services/admin-specialist-journey.service.ts @@ -54,6 +54,19 @@ export async function getAdminSpecialistProducts( return { products, pagination: response.data.meta.pagination }; } +// Transfere o produto para outro especialista. O backend bloqueia (409) +// enquanto houver processo ou agendamento em andamento. +export async function transferAdminProduct( + productType: JourneyProductType, + productId: string, + specialistId: string, +): Promise { + const resource = resourceByType[productType]; + await api.patch(`/${resource}/${productId}/specialist`, { + specialist_id: specialistId, + }); +} + export type CsvImportPreview = { productType: JourneyProductType; targetSpecialistId: string; From bee008f43d118a496f1bab769c2688ce43de16c1 Mon Sep 17 00:00:00 2001 From: "luiz.cazelatto" Date: Fri, 30 Oct 2026 21:15:03 -0300 Subject: [PATCH 07/11] =?UTF-8?q?feat(import):=20s=C3=B3=20valor=20e=20moe?= =?UTF-8?q?da=20obrigat=C3=B3rios=20e=20planilha=20com=20instru=C3=A7?= =?UTF-8?q?=C3=B5es?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Template de importação vira .xlsx com aba "Instruções" (coluna, obrigatório, formato, exemplo, como preencher), gerado da fonte única product-columns.ts; import aceita .xlsx ou .csv. - Obrigatórios: valor e currency (BRL/USD). Sem identificador, o import gera auto- dos campos descritivos, então reimportar a mesma linha atualiza em vez de duplicar. - Na criação, campos vazios recebem padrão (marca = tipo, modelo = identificador, estado = "não informado"); no update não sobrescrevem. - ano passa a ser opcional (Car, Boat, Aircraft) com migration aditiva. - parseWorkbook lê cell.text (links do Excel viravam [object Object]). Closes #254 --- architecture.md | 11 +- .../migration.sql | 4 + backend/prisma/schema.prisma | 6 +- .../aircrafts/aircrafts.controller.ts | 33 +-- .../features/aircrafts/aircrafts.service.ts | 24 -- .../aircrafts/dto/create-aircraft.dto.ts | 3 +- .../aircrafts/entity/aircraft.entity.ts | 2 +- .../src/features/boats/boats.controller.ts | 33 +-- backend/src/features/boats/boats.service.ts | 29 --- .../src/features/boats/dto/create-boat.dto.ts | 3 +- .../src/features/boats/entity/boat.entity.ts | 2 +- backend/src/features/cars/cars.controller.ts | 33 +-- backend/src/features/cars/cars.service.ts | 26 -- .../src/features/cars/dto/create-car.dto.ts | 3 +- .../src/features/cars/entity/car.entity.ts | 2 +- ...roduct-identificador-normalization.spec.ts | 1 + .../product-import-jobs.service.spec.ts | 123 +++++++++- .../product-import-jobs.service.ts | 232 ++++++++++++------ .../features/product-template-columns.spec.ts | 127 ++++++---- .../src/shared/constants/product-columns.ts | 153 ++++++++---- .../shared/services/xlsx-import.service.ts | 127 ++++------ .../src/components/shared/XlsxImporter.tsx | 54 ++-- .../admin/SpecialistJourneyProductsPage.tsx | 8 +- frontend/src/services/aircrafts.service.ts | 6 +- frontend/src/services/boats.service.ts | 6 +- frontend/src/services/cars.service.ts | 6 +- 26 files changed, 626 insertions(+), 431 deletions(-) create mode 100644 backend/prisma/migrations/20261030120000_optional_product_year/migration.sql diff --git a/architecture.md b/architecture.md index 2144bc6..a2b8abc 100644 --- a/architecture.md +++ b/architecture.md @@ -285,7 +285,7 @@ Cada domínio expõe: "images": [] } ``` -- `POST /cars|boats|aircrafts/import-csv` +- `POST /cars|boats|aircrafts/import-csv` — aceita `.xlsx` (template) ou `.csv`. Só `valor` e `currency` (`BRL`/`USD`) são obrigatórios. Sem `identificador`, o import gera `auto-` a partir dos campos descritivos da linha (sem valor/moeda/folder_url), então reimportar a mesma linha atualiza em vez de duplicar. Na criação, campos vazios viram padrão: `marca` = tipo (Carro/Lancha/Aeronave), `modelo` = identificador, `estado` = "não informado", `ano` = null; no update, campos vazios não sobrescrevem o que existe. - payload: ```json { @@ -299,17 +299,12 @@ Cada domínio expõe: "status": "PENDING" } ``` -- `GET /cars|boats|aircrafts/csv-template` +- `GET /cars|boats|aircrafts/import-template` - payload: ```json {} ``` - - resposta: -```json -{ - "file": "template.csv" -} -``` + - resposta: arquivo `template_.xlsx` com a aba "Produtos" (só cabeçalho) e a aba "Instruções" (coluna, obrigatório, formato, exemplo, como preencher), geradas de `backend/src/shared/constants/product-columns.ts`. - `GET /cars|boats|aircrafts` - payload: ```json diff --git a/backend/prisma/migrations/20261030120000_optional_product_year/migration.sql b/backend/prisma/migrations/20261030120000_optional_product_year/migration.sql new file mode 100644 index 0000000..f1dec6d --- /dev/null +++ b/backend/prisma/migrations/20261030120000_optional_product_year/migration.sql @@ -0,0 +1,4 @@ +-- Importação mínima (issue #254): produto pode ser cadastrado sem ano. +ALTER TABLE "Car" ALTER COLUMN "ano" DROP NOT NULL; +ALTER TABLE "Boat" ALTER COLUMN "ano" DROP NOT NULL; +ALTER TABLE "Aircraft" ALTER COLUMN "ano" DROP NOT NULL; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 09f9164..bcc2088 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -699,7 +699,7 @@ model Car { valor Decimal currency ProductCurrency @default(BRL) estado String - ano Int + ano Int? descricao String? cor String? km Int? @@ -744,7 +744,7 @@ model Boat { identificador String valor Decimal currency ProductCurrency @default(BRL) - ano Int + ano Int? fabricante String? tamanho String? estilo String? @@ -789,7 +789,7 @@ model Aircraft { deactivated_at DateTime? deactivated_by_sync_job_id String? @db.Uuid categoria String? - ano Int + ano Int? marca String modelo String identificador String diff --git a/backend/src/features/aircrafts/aircrafts.controller.ts b/backend/src/features/aircrafts/aircrafts.controller.ts index 446bd77..6db077a 100644 --- a/backend/src/features/aircrafts/aircrafts.controller.ts +++ b/backend/src/features/aircrafts/aircrafts.controller.ts @@ -31,7 +31,10 @@ import { 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 { + isImportSpreadsheet, + 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'; @@ -104,8 +107,8 @@ export class AircraftsController { options.specialist_id, ProductType.AIRCRAFT, ); - if (!file?.originalname?.toLowerCase().endsWith('.csv')) { - throw new BadRequestException('Arquivo CSV é obrigatório.'); + if (!isImportSpreadsheet(file?.originalname)) { + throw new BadRequestException('Envie a planilha modelo (.xlsx) ou um .csv.'); } return this.productImportJobsService.previewCsvImport( file.buffer, @@ -132,16 +135,11 @@ export class AircraftsController { ); if (!file) { - throw new BadRequestException('Arquivo CSV é obrigatório.'); + throw new BadRequestException('A planilha é obrigatória.'); } - const isCsvFile = - file.mimetype === 'text/csv' || - file.mimetype === 'application/vnd.ms-excel' || - file.originalname?.toLowerCase().endsWith('.csv'); - - if (!isCsvFile) { - throw new BadRequestException('Apenas arquivos .csv são aceitos.'); + if (!isImportSpreadsheet(file.originalname)) { + throw new BadRequestException('Apenas arquivos .xlsx ou .csv são aceitos.'); } return this.productImportJobsService.createJobFromCsv( @@ -157,12 +155,15 @@ export class AircraftsController { ); } - @Get('csv-template') - async getCsvTemplate(@Res({ passthrough: true }) res: any) { - const buffer = await this.aircraftsService.getCsvTemplate(); + @Get('import-template') + async getImportTemplate(@Res({ passthrough: true }) res: any) { + const buffer = await this.productImportJobsService.getImportTemplate( + ProductType.AIRCRAFT, + ); res.set({ - 'Content-Type': 'text/csv; charset=utf-8', - 'Content-Disposition': 'attachment; filename=template_aeronaves.csv', + 'Content-Type': + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': 'attachment; filename=template_aeronaves.xlsx', }); return new StreamableFile(buffer); } diff --git a/backend/src/features/aircrafts/aircrafts.service.ts b/backend/src/features/aircrafts/aircrafts.service.ts index a520a3a..87d91a7 100644 --- a/backend/src/features/aircrafts/aircrafts.service.ts +++ b/backend/src/features/aircrafts/aircrafts.service.ts @@ -16,7 +16,6 @@ import { RangeAircraftFilters, } from 'src/shared/dto/filters.dto'; 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'; @@ -31,8 +30,6 @@ import { export class AircraftsService { private readonly logger = new Logger(AircraftsService.name); - // Colunas da planilha de aeronaves — fonte única em shared/constants/product-columns.ts - private readonly xlsxColumns = AIRCRAFT_COLUMNS; constructor( private prismaService: PrismaService, @@ -412,25 +409,4 @@ export class AircraftsService { } } - async getCsvTemplate(): Promise { - const headers = this.xlsxColumns.map((column) => column.name).join(';'); - const exampleValues = [ - 'Embraer-Phenom 300-1', - 'Embraer', - 'Phenom 300', - '15000000', - 'BRL', - 'São Paulo', - '2021', - 'Light Jet', - '8', - 'Jato Executivo', - 'Aeronave com baixas horas de voo e interior renovado', - 'https://drive.google.com/drive/folders/SEU_FOLDER_ID', - ].join(';'); - - const BOM = Buffer.from([0xef, 0xbb, 0xbf]); - const content = Buffer.from(`${headers}\n${exampleValues}\n`, 'utf-8'); - return Buffer.concat([BOM, content]); - } } diff --git a/backend/src/features/aircrafts/dto/create-aircraft.dto.ts b/backend/src/features/aircrafts/dto/create-aircraft.dto.ts index 15aa25c..adbbc7a 100644 --- a/backend/src/features/aircrafts/dto/create-aircraft.dto.ts +++ b/backend/src/features/aircrafts/dto/create-aircraft.dto.ts @@ -39,8 +39,9 @@ export class CreateAircraftDto { @IsString() estado: string; + @IsOptional() @IsNumber() - ano: number; + ano?: number; @IsOptional() @IsString() diff --git a/backend/src/features/aircrafts/entity/aircraft.entity.ts b/backend/src/features/aircrafts/entity/aircraft.entity.ts index 718b301..05d9f49 100644 --- a/backend/src/features/aircrafts/entity/aircraft.entity.ts +++ b/backend/src/features/aircrafts/entity/aircraft.entity.ts @@ -9,7 +9,7 @@ export class Aircraft { deactivated_by_sync_job_id: string | null; categoria: string | null; specialist_id: string | null; - ano: number; + ano: number | null; marca: string; modelo: string; assentos: number | null; diff --git a/backend/src/features/boats/boats.controller.ts b/backend/src/features/boats/boats.controller.ts index 55cad87..9e89687 100644 --- a/backend/src/features/boats/boats.controller.ts +++ b/backend/src/features/boats/boats.controller.ts @@ -31,7 +31,10 @@ import { 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 { + isImportSpreadsheet, + 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'; @@ -103,8 +106,8 @@ export class BoatsController { options.specialist_id, ProductType.BOAT, ); - if (!file?.originalname?.toLowerCase().endsWith('.csv')) { - throw new BadRequestException('Arquivo CSV é obrigatório.'); + if (!isImportSpreadsheet(file?.originalname)) { + throw new BadRequestException('Envie a planilha modelo (.xlsx) ou um .csv.'); } return this.productImportJobsService.previewCsvImport( file.buffer, @@ -131,16 +134,11 @@ export class BoatsController { ); if (!file) { - throw new BadRequestException('Arquivo CSV é obrigatório.'); + throw new BadRequestException('A planilha é obrigatória.'); } - const isCsvFile = - file.mimetype === 'text/csv' || - file.mimetype === 'application/vnd.ms-excel' || - file.originalname?.toLowerCase().endsWith('.csv'); - - if (!isCsvFile) { - throw new BadRequestException('Apenas arquivos .csv são aceitos.'); + if (!isImportSpreadsheet(file.originalname)) { + throw new BadRequestException('Apenas arquivos .xlsx ou .csv são aceitos.'); } return this.productImportJobsService.createJobFromCsv( @@ -156,12 +154,15 @@ export class BoatsController { ); } - @Get('csv-template') - async getCsvTemplate(@Res({ passthrough: true }) res: any) { - const buffer = await this.boatsService.getCsvTemplate(); + @Get('import-template') + async getImportTemplate(@Res({ passthrough: true }) res: any) { + const buffer = await this.productImportJobsService.getImportTemplate( + ProductType.BOAT, + ); res.set({ - 'Content-Type': 'text/csv; charset=utf-8', - 'Content-Disposition': 'attachment; filename=template_lanchas.csv', + 'Content-Type': + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': 'attachment; filename=template_lanchas.xlsx', }); return new StreamableFile(buffer); } diff --git a/backend/src/features/boats/boats.service.ts b/backend/src/features/boats/boats.service.ts index 688ca63..13957af 100644 --- a/backend/src/features/boats/boats.service.ts +++ b/backend/src/features/boats/boats.service.ts @@ -16,7 +16,6 @@ import { FiltersBoatMeta, RangeBoatFilters, } from 'src/shared/dto/filters.dto'; -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'; @@ -31,8 +30,6 @@ import { export class BoatsService { private readonly logger = new Logger(BoatsService.name); - // Colunas da planilha de barcos — fonte única em shared/constants/product-columns.ts - private readonly xlsxColumns = BOAT_COLUMNS; constructor( private prismaService: PrismaService, @@ -343,30 +340,4 @@ export class BoatsService { } } - async getCsvTemplate(): Promise { - const headers = this.xlsxColumns.map((column) => column.name).join(';'); - const exampleValues = [ - 'Azimut-55 Fly-1', - 'Azimut', - '55 Fly', - '3500000', - 'BRL', - 'São Paulo', - '2022', - 'Azimut', - '55 pés', - 'Flybridge', - 'Diesel', - 'Volvo Penta D6', - '2022', - 'Lancha', - 'Embarcação em excelente estado com todos os opcionais', - 'GPS Garmin - Ar condicionado - Gerador', - 'https://drive.google.com/drive/folders/SEU_FOLDER_ID', - ].join(';'); - - const BOM = Buffer.from([0xef, 0xbb, 0xbf]); - const content = Buffer.from(`${headers}\n${exampleValues}\n`, 'utf-8'); - return Buffer.concat([BOM, content]); - } } diff --git a/backend/src/features/boats/dto/create-boat.dto.ts b/backend/src/features/boats/dto/create-boat.dto.ts index 963d33a..2ae6f6f 100644 --- a/backend/src/features/boats/dto/create-boat.dto.ts +++ b/backend/src/features/boats/dto/create-boat.dto.ts @@ -39,8 +39,9 @@ export class CreateBoatDto { @IsString() estado: string; + @IsOptional() @IsNumber() - ano: number; + ano?: number; @IsOptional() @IsString() diff --git a/backend/src/features/boats/entity/boat.entity.ts b/backend/src/features/boats/entity/boat.entity.ts index 0576126..b9a7bc0 100644 --- a/backend/src/features/boats/entity/boat.entity.ts +++ b/backend/src/features/boats/entity/boat.entity.ts @@ -12,7 +12,7 @@ export class Boat { valor: number; currency: ProductCurrency; estado: string; - ano: number; + ano: number | null; fabricante: string | null; tamanho: string | null; estilo: string | null; diff --git a/backend/src/features/cars/cars.controller.ts b/backend/src/features/cars/cars.controller.ts index 4e7fe34..b579a86 100644 --- a/backend/src/features/cars/cars.controller.ts +++ b/backend/src/features/cars/cars.controller.ts @@ -28,7 +28,10 @@ import { 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 { + isImportSpreadsheet, + 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'; @@ -100,8 +103,8 @@ export class CarsController { options.specialist_id, ProductType.CAR, ); - if (!file?.originalname?.toLowerCase().endsWith('.csv')) { - throw new BadRequestException('Arquivo CSV é obrigatório.'); + if (!isImportSpreadsheet(file?.originalname)) { + throw new BadRequestException('Envie a planilha modelo (.xlsx) ou um .csv.'); } return this.productImportJobsService.previewCsvImport( file.buffer, @@ -128,16 +131,11 @@ export class CarsController { ); if (!file) { - throw new BadRequestException('Arquivo CSV é obrigatório.'); + throw new BadRequestException('A planilha é obrigatória.'); } - const isCsvFile = - file.mimetype === 'text/csv' || - file.mimetype === 'application/vnd.ms-excel' || - file.originalname?.toLowerCase().endsWith('.csv'); - - if (!isCsvFile) { - throw new BadRequestException('Apenas arquivos .csv são aceitos.'); + if (!isImportSpreadsheet(file.originalname)) { + throw new BadRequestException('Apenas arquivos .xlsx ou .csv são aceitos.'); } return this.productImportJobsService.createJobFromCsv( @@ -153,12 +151,15 @@ export class CarsController { ); } - @Get('csv-template') - async getCsvTemplate(@Res({ passthrough: true }) res: any) { - const buffer = await this.carsService.getCsvTemplate(); + @Get('import-template') + async getImportTemplate(@Res({ passthrough: true }) res: any) { + const buffer = await this.productImportJobsService.getImportTemplate( + ProductType.CAR, + ); res.set({ - 'Content-Type': 'text/csv; charset=utf-8', - 'Content-Disposition': 'attachment; filename=template_carros.csv', + 'Content-Type': + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': 'attachment; filename=template_carros.xlsx', }); return new StreamableFile(buffer); } diff --git a/backend/src/features/cars/cars.service.ts b/backend/src/features/cars/cars.service.ts index bfba8e3..c7df451 100644 --- a/backend/src/features/cars/cars.service.ts +++ b/backend/src/features/cars/cars.service.ts @@ -16,7 +16,6 @@ import { FiltersCarMeta, RangeCarFilters, } from 'src/shared/dto/filters.dto'; -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'; @@ -31,8 +30,6 @@ import { export class CarsService { private readonly logger = new Logger(CarsService.name); - // Colunas da planilha de carros — fonte única em shared/constants/product-columns.ts - private readonly xlsxColumns = CAR_COLUMNS; constructor( private prismaService: PrismaService, @@ -324,27 +321,4 @@ export class CarsService { } } - async getCsvTemplate(): Promise { - const headers = this.xlsxColumns.map((column) => column.name).join(';'); - const exampleValues = [ - 'BMW-X5-1', - 'BMW', - 'X5', - '450000', - 'BRL', - 'São Paulo', - '2023', - 'Preto', - '15000', - 'Automático', - 'Gasolina', - 'SUV', - 'Carro em excelente estado', - 'https://drive.google.com/drive/folders/SEU_FOLDER_ID', - ].join(';'); - - const BOM = Buffer.from([0xef, 0xbb, 0xbf]); - const content = Buffer.from(`${headers}\n${exampleValues}\n`, 'utf-8'); - return Buffer.concat([BOM, content]); - } } diff --git a/backend/src/features/cars/dto/create-car.dto.ts b/backend/src/features/cars/dto/create-car.dto.ts index 2a577f4..7e54823 100644 --- a/backend/src/features/cars/dto/create-car.dto.ts +++ b/backend/src/features/cars/dto/create-car.dto.ts @@ -39,8 +39,9 @@ export class CreateCarDto { @IsString() estado: string; + @IsOptional() @IsNumber() - ano: number; + ano?: number; @IsOptional() @IsString() diff --git a/backend/src/features/cars/entity/car.entity.ts b/backend/src/features/cars/entity/car.entity.ts index 1b653b5..a701a51 100644 --- a/backend/src/features/cars/entity/car.entity.ts +++ b/backend/src/features/cars/entity/car.entity.ts @@ -12,7 +12,7 @@ export class Car { valor: number; currency: ProductCurrency; estado: string; - ano: number; + ano: number | null; cor: string | null; km: number | null; cambio: string | null; diff --git a/backend/src/features/product-identificador-normalization.spec.ts b/backend/src/features/product-identificador-normalization.spec.ts index 6c9cef6..5342c1f 100644 --- a/backend/src/features/product-identificador-normalization.spec.ts +++ b/backend/src/features/product-identificador-normalization.spec.ts @@ -7,6 +7,7 @@ const baseRow = { marca: 'Marca', modelo: 'Modelo', valor: '100', + currency: 'BRL', estado: 'SP', ano: '2020', }; 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 b4eae2d..c424fdf 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 @@ -1,5 +1,6 @@ import { ProductImportJobsService } from './product-import-jobs.service'; import { Prisma, ProductCurrency, ProductType } from '@prisma/client'; +import { XlsxImportService } from 'src/shared/services/xlsx-import.service'; describe('ProductImportJobsService', () => { beforeEach(() => { @@ -50,6 +51,7 @@ describe('ProductImportJobsService', () => { modelo: 'Roma', identificador: 'FERRARI-ROMA-1', valor: '1000000', + currency: 'BRL', estado: 'SP', ano: '2024', }; @@ -74,12 +76,10 @@ describe('ProductImportJobsService', () => { }); 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'], + ['identificador', '-', 'Identificador faltando'], + ['valor', ' ', 'Valor do produto faltando'], + ['currency', ' - ', 'Moeda (use BRL ou USD) faltando'], + ['currency', 'EUR', 'Moeda inválida "EUR": use BRL ou USD.'], ])( 'trata %s com marcador de ausência como erro natural da linha', async (field, emptyValue, expectedMessage) => { @@ -115,7 +115,6 @@ describe('ProductImportJobsService', () => { ProductType.CAR, { ...validCarRow, - currency: '-', cor: ' - ', km: '-', cambio: ' ', @@ -126,7 +125,7 @@ describe('ProductImportJobsService', () => { expect(create).toHaveBeenCalledWith({ data: expect.objectContaining({ - currency: undefined, + currency: ProductCurrency.BRL, cor: undefined, km: undefined, cambio: undefined, @@ -153,7 +152,7 @@ describe('ProductImportJobsService', () => { { id: 'item-2', status: 'PENDING', - payload: { ...validCarRow, modelo: '-' }, + payload: { ...validCarRow, valor: '-' }, folder_url: null, }, ], @@ -196,7 +195,7 @@ describe('ProductImportJobsService', () => { where: { id: 'item-2' }, data: expect.objectContaining({ status: 'FAILED', - error_message: 'Nome do veículo faltando', + error_message: 'Valor do produto faltando', }), }); }); @@ -777,6 +776,108 @@ describe('ProductImportJobsService', () => { }); }); + it('produto só com valor e moeda é criado com valores padrão', 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 (service as any).upsertProductFromRow( + ProductType.CAR, + { identificador: 'auto-abc', valor: '450000', currency: 'usd' }, + '00000000-0000-4000-8000-000000000001', + ); + + expect(create).toHaveBeenCalledWith({ + data: expect.objectContaining({ + identificador: 'auto-abc', + marca: 'Carro', + modelo: 'auto-abc', + estado: 'não informado', + ano: undefined, + valor: 450000, + currency: ProductCurrency.USD, + }), + }); + }); + + it('reimport não sobrescreve com valores padrão o que foi editado à mão', async () => { + const existing = { id: 'product-1', is_active: true }; + const update = jest.fn().mockResolvedValue({ updated_at: new Date() }); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([]), + car: { + findFirst: jest.fn().mockResolvedValue(existing), + findUnique: jest.fn().mockResolvedValue({ + id: 'product-1', + valor: new Prisma.Decimal(450000), + currency: ProductCurrency.BRL, + }), + update, + create: jest.fn(), + }, + process: { findFirst: jest.fn().mockResolvedValue(null) }, + } as any; + const service = new ProductImportJobsService(tx, {} as any, {} as any); + + await (service as any).upsertProductFromRow( + ProductType.CAR, + { identificador: 'auto-abc', valor: '450000', currency: 'BRL' }, + '00000000-0000-4000-8000-000000000001', + tx, + ); + + const data = update.mock.calls[0][0].data; + expect(data).toMatchObject({ identificador: 'auto-abc', valor: 450000 }); + expect(data.marca).toBeUndefined(); + expect(data.modelo).toBeUndefined(); + expect(data.estado).toBeUndefined(); + expect(tx.car.create).not.toHaveBeenCalled(); + }); + + describe('identificador automático', () => { + const parse = async (lines: string[]) => { + const service = new ProductImportJobsService( + {} as any, + new XlsxImportService(), + {} as any, + ); + return (service as any).parseImportRows( + Buffer.from(lines.join('\n'), 'utf-8'), + ProductType.CAR, + ); + }; + + it('a mesma linha gera o mesmo identificador, mesmo com outro preço', async () => { + const [first] = await parse(['marca;modelo;valor;currency', 'BMW;X5;450000;BRL']); + const [repriced] = await parse(['marca;modelo;valor;currency', 'bmw;X5;399000;USD']); + const [other] = await parse(['marca;modelo;valor;currency', 'BMW;X6;450000;BRL']); + + expect(first.identificador).toMatch(/^auto-[0-9a-f]{12}$/); + expect(repriced.identificador).toBe(first.identificador); + expect(other.identificador).not.toBe(first.identificador); + }); + + it('linhas só com valor e moeda se distinguem pelo preço', async () => { + const rows = await parse(['valor;currency', '100;BRL', '200;BRL']); + + expect(rows[0].identificador).not.toBe(rows[1].identificador); + }); + + it('identificador informado é mantido', async () => { + const [row] = await parse(['identificador;valor;currency', 'BMW-1;100;BRL']); + + expect(row.identificador).toBe('BMW-1'); + }); + + it('rejeita linhas sem identificador com os mesmos dados', async () => { + await expect( + parse(['marca;valor;currency', 'BMW;100;BRL', 'BMW;200;BRL']), + ).rejects.toThrow(/sem identificador com os mesmos dados/); + }); + }); + 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); @@ -789,6 +890,7 @@ describe('ProductImportJobsService', () => { modelo: 'X', identificador: ' ', valor: '100', + currency: 'BRL', estado: 'SP', ano: '2020', }, @@ -811,6 +913,7 @@ describe('ProductImportJobsService', () => { modelo: 'X', identificador: 'FERRARI-X-2', valor: '100', + currency: 'BRL', estado: 'SP', ano: '2020', }, 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 9c78f0f..5c20b03 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 @@ -127,15 +127,38 @@ class ProductImportJobLeaseLostError extends Error { } } +// identificador nunca chega vazio de parseImportRows (é gerado quando falta); +// a checagem protege payloads montados por outro caminho. 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' }, + { key: 'identificador', label: 'Identificador' }, + { key: 'valor', label: 'Valor do produto' }, + { key: 'currency', label: 'Moeda (use BRL ou USD)' }, ] as const; +// Produto importado só com valor e moeda: o que aparece no catálogo até alguém +// completar o cadastro. Aplicado só na criação, para um reimport não apagar o +// que foi editado à mão. +const DEFAULT_MARCA: Record = { + [ProductType.CAR]: 'Carro', + [ProductType.BOAT]: 'Lancha', + [ProductType.AIRCRAFT]: 'Aeronave', +}; +const DEFAULT_ESTADO = 'não informado'; + +// Colunas que não descrevem o produto: ficam fora do identificador automático +// para que reimportar com outro preço ou outras fotos atualize o mesmo produto. +const NON_DESCRIPTIVE_COLUMNS = new Set([ + 'identificador', + 'valor', + 'currency', + 'folder_url', +]); +export const AUTO_IDENTIFIER_PREFIX = 'auto-'; + +export function isImportSpreadsheet(fileName?: string): boolean { + return /\.(xlsx|csv)$/i.test(fileName ?? ''); +} + @Injectable() export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(ProductImportJobsService.name); @@ -232,24 +255,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }); } - 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)); - this.validateUniqueIdentifiers(normalizedRows); + const normalizedRows = await this.parseImportRows(fileBuffer, productType); const specialistId = options.context?.specialistId ?? user.id; let creationResult; try { @@ -370,21 +376,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { '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)); - this.validateUniqueIdentifiers(normalizedRows); + const normalizedRows = await this.parseImportRows(fileBuffer, productType); const catalogSnapshot = await this.getSynchronizationCatalogSnapshot( productType, specialistId, @@ -1981,15 +1973,13 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { if (productType === ProductType.CAR) { const data = { - marca: row.marca, - modelo: row.modelo, + marca: row.marca || undefined, + modelo: row.modelo || undefined, identificador, valor: Number(row.valor), - currency: row.currency - ? (row.currency.toUpperCase() as ProductCurrency) - : undefined, - estado: row.estado, - ano: Number(row.ano), + currency: row.currency.toUpperCase() as ProductCurrency, + estado: row.estado || undefined, + ano: row.ano ? Number(row.ano) : undefined, cor: row.cor || undefined, km: row.km ? Number(row.km) : undefined, cambio: row.cambio || undefined, @@ -1999,7 +1989,8 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { specialist_id: specialistId, }; - await this.validatePayload(data, CreateCarDto); + const createData = this.withCreationDefaults(ProductType.CAR, data); + await this.validatePayload(createData, CreateCarDto); const existing = await (client as PrismaService).car.findFirst({ where: { @@ -2032,7 +2023,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }; } - const created = await (client as PrismaService).car.create({ data }); + const created = await (client as PrismaService).car.create({ data: createData }); return { productId: created.id, action: 'CREATED', @@ -2042,15 +2033,13 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { if (productType === ProductType.BOAT) { const data = { - marca: row.marca, - modelo: row.modelo, + marca: row.marca || undefined, + modelo: row.modelo || undefined, identificador, valor: Number(row.valor), - currency: row.currency - ? (row.currency.toUpperCase() as ProductCurrency) - : undefined, - estado: row.estado, - ano: Number(row.ano), + currency: row.currency.toUpperCase() as ProductCurrency, + estado: row.estado || undefined, + ano: row.ano ? Number(row.ano) : undefined, fabricante: row.fabricante || undefined, tamanho: row.tamanho || undefined, estilo: row.estilo || undefined, @@ -2063,7 +2052,8 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { specialist_id: specialistId, }; - await this.validatePayload(data, CreateBoatDto); + const createData = this.withCreationDefaults(ProductType.BOAT, data); + await this.validatePayload(createData, CreateBoatDto); const existing = await (client as PrismaService).boat.findFirst({ where: { @@ -2096,7 +2086,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }; } - const created = await (client as PrismaService).boat.create({ data }); + const created = await (client as PrismaService).boat.create({ data: createData }); return { productId: created.id, action: 'CREATED', @@ -2105,15 +2095,13 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { } const data = { - marca: row.marca, - modelo: row.modelo, + marca: row.marca || undefined, + modelo: row.modelo || undefined, identificador, valor: Number(row.valor), - currency: row.currency - ? (row.currency.toUpperCase() as ProductCurrency) - : undefined, - estado: row.estado, - ano: Number(row.ano), + currency: row.currency.toUpperCase() as ProductCurrency, + estado: row.estado || undefined, + ano: row.ano ? Number(row.ano) : undefined, categoria: row.categoria || undefined, assentos: row.assentos ? Number(row.assentos) : undefined, tipo_aeronave: row.tipo_aeronave || undefined, @@ -2121,7 +2109,8 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { specialist_id: specialistId, }; - await this.validatePayload(data, CreateAircraftDto); + const createData = this.withCreationDefaults(ProductType.AIRCRAFT, data); + await this.validatePayload(createData, CreateAircraftDto); const existing = await (client as PrismaService).aircraft.findFirst({ where: { @@ -2154,7 +2143,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }; } - const created = await (client as PrismaService).aircraft.create({ data }); + const created = await (client as PrismaService).aircraft.create({ data: createData }); return { productId: created.id, action: 'CREATED', @@ -2171,6 +2160,93 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { ); } + /** + * Lê .xlsx (o modelo baixado) ou .csv, valida o cabeçalho e devolve as + * linhas normalizadas, já com identificador. Todo o resto do import (prévia, + * sincronização, payload dos itens) usa estas linhas. + */ + getImportTemplate(productType: ProductType): Promise { + return this.xlsxImportService.generateTemplate( + this.getColumnsForType(productType), + ); + } + + private async parseImportRows( + fileBuffer: Buffer, + productType: ProductType, + ): Promise { + // .xlsx é um zip: começa com "PK". + const isXlsx = fileBuffer[0] === 0x50 && fileBuffer[1] === 0x4b; + const { rows } = isXlsx + ? await this.xlsxImportService.parseWorkbook(fileBuffer) + : this.xlsxImportService.parseCsv(fileBuffer); + const columns = this.getColumnsForType(productType); + const structureValidation = this.xlsxImportService.validateStructure( + rows, + columns, + ); + if (!structureValidation.valid) { + throw new BadRequestException({ + message: 'Estrutura da planilha inválida', + errors: structureValidation.errors, + missingRequired: structureValidation.missingRequired, + unknownColumns: structureValidation.unknownColumns, + }); + } + const normalizedRows = rows.map((row) => + this.withIdentifier(productType, this.normalizeProductRow(row), columns), + ); + this.validateUniqueIdentifiers(normalizedRows); + return normalizedRows; + } + + /** + * Linha sem identificador ganha um derivado dos dados descritivos, para que + * reimportar a mesma linha atualize o produto em vez de duplicar. + * ponytail: mudar um dado descritivo (marca, km...) numa linha sem + * identificador gera outro id e cria um produto novo; a aba Instruções + * orienta a preencher o identificador quando a linha for editada depois. + */ + private withIdentifier( + productType: ProductType, + row: ImportParsedRow, + columns: XlsxColumnDefinition[], + ): ImportParsedRow { + if (row.identificador) return row; + const descriptive = columns + .map((column) => column.name) + .filter((name) => !NON_DESCRIPTIVE_COLUMNS.has(name) && row[name]) + .map((name) => [name, row[name].toLowerCase()]); + // Sem nenhum dado descritivo, só o preço distingue uma linha da outra. + const basis = descriptive.length + ? descriptive + : [ + ['valor', row.valor], + ['currency', row.currency?.toUpperCase()], + ]; + const hash = this.sha256(JSON.stringify([productType, basis])).slice(0, 12); + return { ...row, identificador: `${AUTO_IDENTIFIER_PREFIX}${hash}` }; + } + + private withCreationDefaults< + T extends { + identificador: string; + marca?: string; + modelo?: string; + estado?: string; + }, + >( + productType: ProductType, + data: T, + ): T & { marca: string; modelo: string; estado: string } { + return { + ...data, + marca: data.marca ?? DEFAULT_MARCA[productType], + modelo: data.modelo ?? data.identificador, + estado: data.estado ?? DEFAULT_ESTADO, + }; + } + private validateUniqueIdentifiers(rows: ImportParsedRow[]): void { const seen = new Set(); const duplicates = new Set(); @@ -2180,11 +2256,15 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { 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(', ')}.`, - ); - } + if (duplicates.size === 0) return; + const manual = [...duplicates].filter( + (id) => !id.startsWith(AUTO_IDENTIFIER_PREFIX), + ); + throw new BadRequestException( + manual.length > 0 + ? `A planilha contém identificadores duplicados: ${manual.join(', ')}.` + : 'A planilha contém linhas sem identificador com os mesmos dados. Preencha o identificador para diferenciá-las.', + ); } private validateRequiredProductFields(row: ImportParsedRow): void { @@ -2193,6 +2273,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { ); if (missingFields.length === 0) { + this.validateCurrency(row); return; } @@ -2201,6 +2282,15 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { ); } + private validateCurrency(row: ImportParsedRow): void { + const currency = row.currency.toUpperCase(); + if (currency !== ProductCurrency.BRL && currency !== ProductCurrency.USD) { + throw new BadRequestException( + `Moeda inválida "${row.currency}": use BRL ou USD.`, + ); + } + } + private async validatePayload( payload: Record, dtoClass: new () => T, diff --git a/backend/src/features/product-template-columns.spec.ts b/backend/src/features/product-template-columns.spec.ts index 1cd3a43..bec6892 100644 --- a/backend/src/features/product-template-columns.spec.ts +++ b/backend/src/features/product-template-columns.spec.ts @@ -1,6 +1,4 @@ -import { CarsService } from './cars/cars.service'; -import { BoatsService } from './boats/boats.service'; -import { AircraftsService } from './aircrafts/aircrafts.service'; +import * as ExcelJS from 'exceljs'; import { AIRCRAFT_COLUMNS, BOAT_COLUMNS, @@ -8,63 +6,76 @@ import { } from 'src/shared/constants/product-columns'; import { XlsxImportService } from 'src/shared/services/xlsx-import.service'; -// getCsvTemplate só lê `xlsxColumns`, então as deps podem ser nulas aqui. const cases = [ - [ - 'carros', - new CarsService(null as any, null as any, null as any), - CAR_COLUMNS, - ], - [ - 'barcos', - new BoatsService(null as any, null as any, null as any), - BOAT_COLUMNS, - ], - [ - 'aeronaves', - new AircraftsService(null as any, null as any, null as any), - AIRCRAFT_COLUMNS, - ], + ['carros', CAR_COLUMNS], + ['barcos', BOAT_COLUMNS], + ['aeronaves', AIRCRAFT_COLUMNS], ] as const; +async function loadTemplate(xlsx: XlsxImportService, columns: typeof CAR_COLUMNS) { + const workbook = new ExcelJS.Workbook(); + await workbook.xlsx.load((await xlsx.generateTemplate(columns)) as any); + return workbook; +} + +function rowValues(sheet: ExcelJS.Worksheet, rowNumber: number): string[] { + const values: string[] = []; + sheet.getRow(rowNumber).eachCell((cell) => values.push(cell.text)); + return values; +} + describe('template de importação de produtos', () => { const xlsx = new XlsxImportService(); it.each(cases)( 'template de %s casa com a fonte única de colunas', - async (_label, service, columns) => { - const csv = (await service.getCsvTemplate()).toString('utf-8'); - const [headerLine, exampleLine] = csv - .replace(/^\uFEFF/, '') - .trim() - .split('\n'); - const headers = headerLine.split(';'); + async (_label, columns) => { + const workbook = await loadTemplate(xlsx, columns); + const data = workbook.worksheets[0]; // o header vem da mesma lista que o import valida — se divergir, o // usuário baixa um template que o próprio import rejeita - expect(headers).toEqual(columns.map((column) => column.name)); - expect(headers[0]).toBe('identificador'); - - // a linha de exemplo é posicional: casa cada valor com sua coluna para - // pegar desalinhamento, não só o primeiro campo - const values = exampleLine.split(';'); - expect(values).toHaveLength(headers.length); - const example = Object.fromEntries( - headers.map((header, index) => [header, values[index]]), + expect(rowValues(data, 1)).toEqual(columns.map((column) => column.name)); + // sem linha de exemplo na aba de dados: ela seria importada por engano + expect(data.rowCount).toBe(1); + }, + ); + + it.each(cases)( + 'aba Instruções de %s explica cada coluna e só exige valor e moeda', + async (_label, columns) => { + const instructions = (await loadTemplate(xlsx, columns)).getWorksheet( + 'Instruções', + )!; + + const documented = columns.map((_, index) => rowValues(instructions, index + 2)); + expect(documented.map(([name]) => name)).toEqual( + columns.map((column) => column.name), ); - expect(example.identificador).toMatch(/-1$/); - for (const column of columns.filter((c) => c.type === 'number')) { - expect(example[column.name]).toMatch(/^\d+$/); + for (const [, , , example, description] of documented) { + expect(example).toBeTruthy(); + expect(description).toBeTruthy(); } + expect( + documented.filter(([, required]) => required === 'Sim').map(([name]) => name), + ).toEqual(['valor', 'currency']); }, ); it.each(cases)( - 'o template de %s é aceito pelo próprio parser de import', - async (_label, service, columns) => { - const buffer = await service.getCsvTemplate(); - const { rows } = xlsx.parseCsv(buffer); + 'o template de %s preenchido só com valor e moeda é aceito pelo parser', + async (_label, columns) => { + const workbook = await loadTemplate(xlsx, columns); + const data = workbook.worksheets[0]; + const row = data.getRow(2); + row.getCell(columns.findIndex((c) => c.name === 'valor') + 1).value = 450000; + row.getCell(columns.findIndex((c) => c.name === 'currency') + 1).value = 'USD'; + const filled = Buffer.from(await workbook.xlsx.writeBuffer()); + + const { rows } = await xlsx.parseWorkbook(filled); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ valor: '450000', currency: 'USD' }); expect(xlsx.validateStructure(rows, columns as any)).toMatchObject({ valid: true, missingRequired: [], @@ -73,16 +84,38 @@ describe('template de importação de produtos', () => { }, ); - it('planilha na ordem antiga (identificador em 3º) continua válida', () => { - const legacy = [ - 'marca;modelo;identificador;valor;estado;ano', - 'BMW;X5;BMW-X5-1;450000;São Paulo;2023', + it('link do Drive vindo como hyperlink do Excel é lido como texto', async () => { + const workbook = await loadTemplate(xlsx, CAR_COLUMNS); + const data = workbook.worksheets[0]; + const url = 'https://drive.google.com/drive/folders/abc'; + data.getRow(2).getCell(CAR_COLUMNS.length).value = { text: url, hyperlink: url }; + data.getRow(2).getCell(4).value = 1; + + const { rows } = await xlsx.parseWorkbook( + Buffer.from(await workbook.xlsx.writeBuffer()), + ); + + expect(rows[0].folder_url).toBe(url); + }); + + it('CSV em outra ordem de colunas continua válido', () => { + const csv = [ + 'marca;modelo;identificador;valor;currency;estado;ano', + 'BMW;X5;BMW-X5-1;450000;BRL;São Paulo;2023', ].join('\n'); - const { rows } = xlsx.parseCsv(Buffer.from(legacy, 'utf-8')); + const { rows } = xlsx.parseCsv(Buffer.from(csv, 'utf-8')); expect(rows[0]).toMatchObject({ marca: 'BMW', identificador: 'BMW-X5-1' }); expect(xlsx.validateStructure(rows, CAR_COLUMNS).missingRequired).toEqual( [], ); }); + + it('CSV sem a coluna de moeda é rejeitado', () => { + const { rows } = xlsx.parseCsv(Buffer.from('valor\n450000', 'utf-8')); + + expect(xlsx.validateStructure(rows, CAR_COLUMNS).missingRequired).toEqual([ + 'currency', + ]); + }); }); diff --git a/backend/src/shared/constants/product-columns.ts b/backend/src/shared/constants/product-columns.ts index 3768666..82ce391 100644 --- a/backend/src/shared/constants/product-columns.ts +++ b/backend/src/shared/constants/product-columns.ts @@ -3,9 +3,13 @@ import { XlsxColumnDefinition } from 'src/shared/services/xlsx-import.service'; /** * Fonte única das colunas de importação de produto. * - * A ordem aqui define o header do CSV/XLSX baixado pelo usuário e a ordem da - * aba "Instruções" — `identificador` vem primeiro por ser a chave do upsert. - * O parser casa por nome, então planilhas em outra ordem continuam válidas. + * A ordem aqui define o header da planilha baixada pelo usuário e a ordem da + * aba "Instruções". O parser casa por nome, então planilhas em outra ordem + * continuam válidas. `description`/`example` alimentam a aba "Instruções". + * + * Só valor e moeda são obrigatórios: sem identificador, o import gera um a + * partir dos dados da linha; sem marca/modelo/estado, o produto recebe + * valores padrão (ver product-import-jobs.service.ts). * * Antes existiam três cópias destas listas (um par por tipo de produto, em * `{cars,boats,aircrafts}.service.ts` e em `product-import-jobs.service.ts`). @@ -13,54 +17,111 @@ import { XlsxColumnDefinition } from 'src/shared/services/xlsx-import.service'; * adicionar uma coluna só na primeira fazia o import rejeitar o próprio * template com "Colunas não reconhecidas". */ +const VALOR: XlsxColumnDefinition = { + name: 'valor', + required: true, + type: 'number', + description: 'Preço do produto, só números, sem pontos nem símbolo.', + example: '450000', +}; + +const CURRENCY: XlsxColumnDefinition = { + name: 'currency', + required: true, + type: 'string', + description: 'Moeda do valor: BRL (real) ou USD (dólar).', + example: 'BRL', +}; + +const IDENTIFICADOR: XlsxColumnDefinition = { + name: 'identificador', + required: false, + type: 'string', + description: + 'Código único do produto no seu catálogo. Reimportar o mesmo código atualiza o produto em vez de duplicar. Se ficar vazio, é gerado a partir dos dados da linha — nesse caso, mudar marca, modelo ou outro dado descritivo cria um produto novo. Preencha se for editar a linha depois.', + example: 'BMW-X5-2023-01', +}; + +const FOLDER_URL: XlsxColumnDefinition = { + name: 'folder_url', + required: false, + type: 'string', + description: + 'Link de uma pasta pública do Google Drive com as fotos do produto.', + example: 'https://drive.google.com/drive/folders/SEU_FOLDER_ID', +}; + +function common( + productLabel: string, + examples: { marca: string; modelo: string }, +): XlsxColumnDefinition[] { + return [ + IDENTIFICADOR, + { + name: 'marca', + required: false, + type: 'string', + description: `Marca/fabricante. Se vazio, aparece como "${productLabel}".`, + example: examples.marca, + }, + { + name: 'modelo', + required: false, + type: 'string', + description: + 'Nome do modelo. Se vazio, aparece o identificador no lugar.', + example: examples.modelo, + }, + VALOR, + CURRENCY, + { + name: 'estado', + required: false, + type: 'string', + description: + 'Estado de conservação (ex.: novo, seminovo, usado). Se vazio, "não informado".', + example: 'seminovo', + }, + { + name: 'ano', + required: false, + type: 'number', + description: 'Ano de fabricação, 4 dígitos.', + example: '2023', + }, + ]; +} + export const CAR_COLUMNS: XlsxColumnDefinition[] = [ - { name: 'identificador', required: true, type: 'string' }, - { name: 'marca', required: true, type: 'string' }, - { name: 'modelo', required: true, type: 'string' }, - { name: 'valor', required: true, type: 'number' }, - { name: 'currency', required: false, type: 'string' }, - { name: 'estado', required: true, type: 'string' }, - { name: 'ano', required: true, type: 'number' }, - { name: 'cor', required: false, type: 'string' }, - { name: 'km', required: false, type: 'number' }, - { name: 'cambio', required: false, type: 'string' }, - { name: 'combustivel', required: false, type: 'string' }, - { name: 'tipo_categoria', required: false, type: 'string' }, - { name: 'descricao', required: false, type: 'string' }, - { name: 'folder_url', required: false, type: 'string' }, + ...common('Carro', { marca: 'BMW', modelo: 'X5' }), + { name: 'cor', required: false, type: 'string', description: 'Cor externa.', example: 'Preto' }, + { name: 'km', required: false, type: 'number', description: 'Quilometragem, só números.', example: '15000' }, + { name: 'cambio', required: false, type: 'string', description: 'Tipo de câmbio.', example: 'Automático' }, + { name: 'combustivel', required: false, type: 'string', description: 'Combustível.', example: 'Gasolina' }, + { name: 'tipo_categoria', required: false, type: 'string', description: 'Categoria do carro.', example: 'SUV' }, + { name: 'descricao', required: false, type: 'string', description: 'Texto livre exibido na página do produto.', example: 'Carro em excelente estado' }, + FOLDER_URL, ]; export const BOAT_COLUMNS: XlsxColumnDefinition[] = [ - { name: 'identificador', required: true, type: 'string' }, - { name: 'marca', required: true, type: 'string' }, - { name: 'modelo', required: true, type: 'string' }, - { name: 'valor', required: true, type: 'number' }, - { name: 'currency', required: false, type: 'string' }, - { name: 'estado', required: true, type: 'string' }, - { name: 'ano', required: true, type: 'number' }, - { name: 'fabricante', required: false, type: 'string' }, - { name: 'tamanho', required: false, type: 'string' }, - { name: 'estilo', required: false, type: 'string' }, - { name: 'combustivel', required: false, type: 'string' }, - { name: 'motor', required: false, type: 'string' }, - { name: 'ano_motor', required: false, type: 'number' }, - { name: 'tipo_embarcacao', required: false, type: 'string' }, - { name: 'descricao_completa', required: false, type: 'string' }, - { name: 'acessorios', required: false, type: 'string' }, - { name: 'folder_url', required: false, type: 'string' }, + ...common('Lancha', { marca: 'Azimut', modelo: 'Atlantis 51' }), + { name: 'fabricante', required: false, type: 'string', description: 'Estaleiro/fabricante.', example: 'Azimut Yachts' }, + { name: 'tamanho', required: false, type: 'string', description: 'Comprimento da embarcação.', example: '51 pés' }, + { name: 'estilo', required: false, type: 'string', description: 'Estilo da embarcação.', example: 'Cabinada' }, + { name: 'combustivel', required: false, type: 'string', description: 'Combustível.', example: 'Diesel' }, + { name: 'motor', required: false, type: 'string', description: 'Motorização.', example: '2x Volvo IPS 600' }, + { name: 'ano_motor', required: false, type: 'number', description: 'Ano do motor, 4 dígitos.', example: '2022' }, + { name: 'tipo_embarcacao', required: false, type: 'string', description: 'Tipo de embarcação.', example: 'Lancha' }, + { name: 'descricao_completa', required: false, type: 'string', description: 'Texto livre exibido na página do produto.', example: 'Embarcação revisada' }, + { name: 'acessorios', required: false, type: 'string', description: 'Acessórios incluídos.', example: 'GPS, ar-condicionado' }, + FOLDER_URL, ]; export const AIRCRAFT_COLUMNS: XlsxColumnDefinition[] = [ - { name: 'identificador', required: true, type: 'string' }, - { name: 'marca', required: true, type: 'string' }, - { name: 'modelo', required: true, type: 'string' }, - { name: 'valor', required: true, type: 'number' }, - { name: 'currency', required: false, type: 'string' }, - { name: 'estado', required: true, type: 'string' }, - { name: 'ano', required: true, type: 'number' }, - { name: 'categoria', required: false, type: 'string' }, - { name: 'assentos', required: false, type: 'number' }, - { name: 'tipo_aeronave', required: false, type: 'string' }, - { name: 'descricao', required: false, type: 'string' }, - { name: 'folder_url', required: false, type: 'string' }, + ...common('Aeronave', { marca: 'Embraer', modelo: 'Phenom 300' }), + { name: 'categoria', required: false, type: 'string', description: 'Categoria da aeronave.', example: 'Jato executivo' }, + { name: 'assentos', required: false, type: 'number', description: 'Número de assentos, só números.', example: '8' }, + { name: 'tipo_aeronave', required: false, type: 'string', description: 'Tipo de aeronave.', example: 'Jato' }, + { name: 'descricao', required: false, type: 'string', description: 'Texto livre exibido na página do produto.', example: 'Aeronave com manutenção em dia' }, + FOLDER_URL, ]; diff --git a/backend/src/shared/services/xlsx-import.service.ts b/backend/src/shared/services/xlsx-import.service.ts index 0b09d82..73e6ab8 100644 --- a/backend/src/shared/services/xlsx-import.service.ts +++ b/backend/src/shared/services/xlsx-import.service.ts @@ -17,6 +17,9 @@ export interface XlsxColumnDefinition { name: string; required: boolean; type: 'string' | 'number' | 'boolean'; + /** Explicação exibida na aba "Instruções" do template. */ + description?: string; + example?: string; } /** @@ -86,13 +89,13 @@ export class XlsxImportService { headers.forEach((header, colIndex) => { if (!header) return; - const cell = row.getCell(colIndex + 1); - const value = cell.value; + // `text` em vez de `value`: o Excel transforma links (ex.: folder_url) + // em objetos hyperlink, que viravam "[object Object]" com String(). + const value = row.getCell(colIndex + 1).text.trim(); - if (value !== null && value !== undefined && value !== '') { + if (value !== '') { hasData = true; - // ExcelJS pode retornar números diretamente — converter para string pois ImportParsedRow usa Record - parsedRow[header] = String(value); + parsedRow[header] = value; } else { parsedRow[header] = ''; } @@ -454,84 +457,42 @@ export class XlsxImportService { } /** - * Gera um workbook XLSX template para download. - * @param columnDefinitions Definições de colunas - * @param exampleData Dados de exemplo para a segunda linha - * @param instructions Instruções por coluna (para comentários nas células do header) - * @returns Buffer do arquivo XLSX + * Gera o modelo de importação: aba de dados só com o cabeçalho (sem linha + * de exemplo, para não ser importada por engano) e aba "Instruções" com + * formato e exemplo de cada coluna. */ async generateTemplate( columnDefinitions: XlsxColumnDefinition[], - exampleData: Record, - instructions: Record, ): Promise { const workbook = new ExcelJS.Workbook(); - const worksheet = workbook.addWorksheet('Template'); - - // Definir colunas (sem 'imagens' — agora são embutidas) - const columns = columnDefinitions.map((col) => ({ + // A primeira aba é a lida pelo import (parseWorkbook). + const dataSheet = workbook.addWorksheet('Produtos'); + dataSheet.columns = columnDefinitions.map((col) => ({ header: col.name, key: col.name, width: Math.max(col.name.length + 5, 15), })); - worksheet.columns = columns; - - // Estilizar header - const headerRow = worksheet.getRow(1); - headerRow.eachCell((cell: ExcelJS.Cell, colNumber: number) => { - const colDef = columnDefinitions[colNumber - 1]; + dataSheet.getRow(1).eachCell((cell, colNumber) => { + const col = columnDefinitions[colNumber - 1]; cell.font = { bold: true, color: { argb: 'FFFFFFFF' } }; cell.fill = { type: 'pattern', pattern: 'solid', - fgColor: { argb: colDef?.required ? 'FF2563EB' : 'FF6B7280' }, - }; - cell.alignment = { horizontal: 'center', vertical: 'middle' }; - cell.border = { - bottom: { style: 'thin', color: { argb: 'FF000000' } }, + fgColor: { argb: col.required ? 'FF2563EB' : 'FF6B7280' }, }; - - // Adicionar nota/comentário com instrução - const colName = colDef?.name; - if (colName && instructions[colName]) { - cell.note = { - texts: [ - { - text: `${colDef.required ? '(Obrigatório) ' : '(Opcional) '}${instructions[colName]}`, - font: { size: 10 }, - }, - ], - }; - } - }); - - // Adicionar linha de exemplo - const exampleRow: Record = {}; - columnDefinitions.forEach((col) => { - if (exampleData[col.name] !== undefined) { - exampleRow[col.name] = exampleData[col.name]; - } + cell.note = `${col.required ? '(Obrigatório)' : '(Opcional)'} ${col.description ?? ''} Ex.: ${col.example ?? ''}`; }); - worksheet.addRow(exampleRow); + dataSheet.views = [{ state: 'frozen', ySplit: 1 }]; - // Estilizar linha de exemplo - const exRow = worksheet.getRow(2); - exRow.eachCell((cell: ExcelJS.Cell) => { - cell.font = { italic: true, color: { argb: 'FF9CA3AF' } }; - }); - - // Adicionar aba de instruções - const instrSheet = workbook.addWorksheet('Instruções'); - instrSheet.columns = [ + const instructions = workbook.addWorksheet('Instruções'); + instructions.columns = [ { header: 'Coluna', key: 'coluna', width: 20 }, - { header: 'Obrigatório', key: 'obrigatorio', width: 15 }, - { header: 'Tipo', key: 'tipo', width: 15 }, - { header: 'Descrição', key: 'descricao', width: 60 }, + { header: 'Obrigatório', key: 'obrigatorio', width: 13 }, + { header: 'Formato', key: 'formato', width: 12 }, + { header: 'Exemplo', key: 'exemplo', width: 30 }, + { header: 'Como preencher', key: 'descricao', width: 90 }, ]; - - // Estilizar header da aba de instruções - const instrHeader = instrSheet.getRow(1); - instrHeader.eachCell((cell: ExcelJS.Cell) => { + instructions.getRow(1).eachCell((cell) => { cell.font = { bold: true, color: { argb: 'FFFFFFFF' } }; cell.fill = { type: 'pattern', @@ -539,27 +500,27 @@ export class XlsxImportService { fgColor: { argb: 'FF2563EB' }, }; }); - - columnDefinitions.forEach((col) => { - instrSheet.addRow({ + for (const col of columnDefinitions) { + const row = instructions.addRow({ coluna: col.name, obrigatorio: col.required ? 'Sim' : 'Não', - tipo: col.type, - descricao: instructions[col.name] || '', + formato: col.type === 'number' ? 'Número' : 'Texto', + exemplo: col.example ?? '', + descricao: col.description ?? '', }); - }); - - // Adicionar instrução sobre imagens - instrSheet.addRow({}); - instrSheet.addRow({ - coluna: '📷 IMAGENS', - obrigatorio: '', - tipo: '', - descricao: - 'Para adicionar imagens, insira-as diretamente na planilha (aba Template). Cole/insira a imagem na linha do produto correspondente. A primeira imagem de cada linha será a principal.', - }); + row.alignment = { wrapText: true, vertical: 'top' }; + if (col.required) row.font = { bold: true }; + } + instructions.addRow({}); + for (const note of [ + 'Preencha uma linha por produto na aba "Produtos" e importe este arquivo (.xlsx) ou salve como .csv.', + 'Só valor e currency são obrigatórios. Colunas vazias recebem um valor padrão e podem ser completadas depois na edição do produto.', + 'Reimportar a mesma linha atualiza o produto existente em vez de criar outro.', + ]) { + instructions.addRow({ coluna: note }); + instructions.mergeCells(`A${instructions.rowCount}:E${instructions.rowCount}`); + } - const xlsxBuffer = await workbook.xlsx.writeBuffer(); - return Buffer.from(xlsxBuffer); + return Buffer.from(await workbook.xlsx.writeBuffer()); } } diff --git a/frontend/src/components/shared/XlsxImporter.tsx b/frontend/src/components/shared/XlsxImporter.tsx index dcf37ba..4c49906 100644 --- a/frontend/src/components/shared/XlsxImporter.tsx +++ b/frontend/src/components/shared/XlsxImporter.tsx @@ -56,8 +56,13 @@ const COLUMN_DEFINITIONS: Record< { required: string[]; optional: string[] } > = { CAR: { - required: ["identificador", "marca", "modelo", "valor", "estado", "ano"], + required: ["valor", "currency"], optional: [ + "identificador", + "marca", + "modelo", + "estado", + "ano", "cor", "km", "cambio", @@ -68,8 +73,13 @@ const COLUMN_DEFINITIONS: Record< ], }, BOAT: { - required: ["identificador", "marca", "modelo", "valor", "estado", "ano"], + required: ["valor", "currency"], optional: [ + "identificador", + "marca", + "modelo", + "estado", + "ano", "fabricante", "tamanho", "estilo", @@ -83,8 +93,13 @@ const COLUMN_DEFINITIONS: Record< ], }, AIRCRAFT: { - required: ["identificador", "marca", "modelo", "valor", "estado", "ano"], + required: ["valor", "currency"], optional: [ + "identificador", + "marca", + "modelo", + "estado", + "ano", "categoria", "assentos", "tipo_aeronave", @@ -126,8 +141,8 @@ export function XlsxImporter({ setFileError(null); // Validar extensão - if (!selectedFile.name.toLowerCase().endsWith(".csv")) { - setFileError("Apenas arquivos .csv são aceitos."); + if (!/\.(xlsx|csv)$/i.test(selectedFile.name)) { + setFileError("Envie a planilha modelo (.xlsx) ou um arquivo .csv."); setFile(null); return; } @@ -317,17 +332,21 @@ export function XlsxImporter({
  • - Formato aceito: .csv + Baixe o template: a aba{" "} + Instruções explica + cada coluna, com formato e exemplo. Aceita .xlsx ou .csv
  • - valor: numero inteiro - sem pontos + valor e{" "} + currency (BRL ou + USD) são os únicos obrigatórios; colunas vazias recebem um + valor padrão e podem ser completadas na edição do produto
  • - ano: 4 digitos (ex: - 2024) + valor: só números, + sem pontos (ex: 450000)
  • @@ -337,10 +356,11 @@ export function XlsxImporter({
  • - Produtos com o mesmo{" "} - identificador{" "} - serão atualizados em vez de duplicados (marca e modelo podem - se repetir entre produtos diferentes). + Reimportar a mesma linha atualiza o produto em vez de + duplicar. Sem{" "} + identificador, ele + é gerado a partir dos dados da linha; preencha-o se for + editar a linha depois.
@@ -365,7 +385,7 @@ export function XlsxImporter({ {isDragging ? "Solte o arquivo aqui" - : "Arraste um arquivo CSV ou clique para selecionar"} + : "Arraste a planilha ou clique para selecionar"}

- Apenas arquivos .csv (max {MAX_FILE_SIZE_MB} MB) + Planilha .xlsx ou .csv (max {MAX_FILE_SIZE_MB} MB)

diff --git a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx index a7d1134..eadd6fc 100644 --- a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx +++ b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx @@ -78,7 +78,7 @@ export default function SpecialistJourneyProductsPage() { ), ); } catch { - setError("CSV inválido ou incompatível com a especialidade selecionada."); + setError("Planilha inválida ou incompatível com a especialidade selecionada."); } }; @@ -139,13 +139,13 @@ export default function SpecialistJourneyProductsPage() {
-

Importação CSV segura

+

Importação de planilha segura

{ setFile(event.target.files?.[0] ?? null); setPreview(null); diff --git a/frontend/src/services/aircrafts.service.ts b/frontend/src/services/aircrafts.service.ts index c95a867..2b3dace 100644 --- a/frontend/src/services/aircrafts.service.ts +++ b/frontend/src/services/aircrafts.service.ts @@ -166,16 +166,16 @@ export async function deleteAircraft(id: string): Promise { } } -// Get /aircrafts/csv-template (downloads .csv file) +// Get /aircrafts/import-template (planilha .xlsx com aba de instruções) export async function getAircraftsCsvTemplate(): Promise { try { - const response = await api.get("/aircrafts/csv-template", { + const response = await api.get("/aircrafts/import-template", { responseType: "blob", }); const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement("a"); link.href = url; - link.setAttribute("download", "template_aeronaves.csv"); + link.setAttribute("download", "template_aeronaves.xlsx"); document.body.appendChild(link); link.click(); link.remove(); diff --git a/frontend/src/services/boats.service.ts b/frontend/src/services/boats.service.ts index 4c770c8..923ecff 100644 --- a/frontend/src/services/boats.service.ts +++ b/frontend/src/services/boats.service.ts @@ -180,16 +180,16 @@ export async function deleteBoat(id: string): Promise { } } -// Get /boats/csv-template (downloads .csv file) +// Get /boats/import-template (planilha .xlsx com aba de instruções) export async function getBoatsCsvTemplate(): Promise { try { - const response = await api.get("/boats/csv-template", { + const response = await api.get("/boats/import-template", { responseType: "blob", }); const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement("a"); link.href = url; - link.setAttribute("download", "template_lanchas.csv"); + link.setAttribute("download", "template_lanchas.xlsx"); document.body.appendChild(link); link.click(); link.remove(); diff --git a/frontend/src/services/cars.service.ts b/frontend/src/services/cars.service.ts index 1a6bd7a..2f6eb7d 100644 --- a/frontend/src/services/cars.service.ts +++ b/frontend/src/services/cars.service.ts @@ -169,16 +169,16 @@ export async function deleteCar(id: string): Promise { } } -// Get /cars/csv-template (downloads .csv file) +// Get /cars/import-template (planilha .xlsx com aba de instruções) export async function getCarsCsvTemplate(): Promise { try { - const response = await api.get("/cars/csv-template", { + const response = await api.get("/cars/import-template", { responseType: "blob", }); const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement("a"); link.href = url; - link.setAttribute("download", "template_carros.csv"); + link.setAttribute("download", "template_carros.xlsx"); document.body.appendChild(link); link.click(); link.remove(); From 001da8a9fdbc03a7571badf8033f5bf577860d14 Mon Sep 17 00:00:00 2001 From: "luiz.cazelatto" Date: Fri, 30 Oct 2026 21:37:49 -0300 Subject: [PATCH 08/11] fix(import): textos do importador falam em planilha e dicas sem quebra de layout --- .../src/components/shared/XlsxImporter.tsx | 22 +++++++++++-------- .../src/components/specialist/ProductForm.tsx | 4 ++-- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/frontend/src/components/shared/XlsxImporter.tsx b/frontend/src/components/shared/XlsxImporter.tsx index 4c49906..ea186f4 100644 --- a/frontend/src/components/shared/XlsxImporter.tsx +++ b/frontend/src/components/shared/XlsxImporter.tsx @@ -253,7 +253,7 @@ export function XlsxImporter({ Importar {PRODUCT_NAMES[productType]}

- Importe varios produtos de uma vez via CSV + Importe vários produtos de uma vez via planilha

@@ -332,16 +332,20 @@ export function XlsxImporter({
  • - Baixe o template: a aba{" "} - Instruções explica - cada coluna, com formato e exemplo. Aceita .xlsx ou .csv + + Baixe o template: a aba{" "} + Instruções explica + cada coluna, com formato e exemplo. Aceita .xlsx ou .csv +
  • - valor e{" "} - currency (BRL ou - USD) são os únicos obrigatórios; colunas vazias recebem um - valor padrão e podem ser completadas na edição do produto + + valor e{" "} + currency (BRL ou + USD) são os únicos obrigatórios; colunas vazias recebem um + valor padrão e podem ser completadas na edição do produto +
  • @@ -483,7 +487,7 @@ export function XlsxImporter({ ) : ( <> - Importar CSV + Importar planilha )} diff --git a/frontend/src/components/specialist/ProductForm.tsx b/frontend/src/components/specialist/ProductForm.tsx index 9519e15..a8667c5 100644 --- a/frontend/src/components/specialist/ProductForm.tsx +++ b/frontend/src/components/specialist/ProductForm.tsx @@ -417,7 +417,7 @@ export default function ProductForm({

    - Importe vários produtos de uma vez usando um arquivo CSV. + Importe vários produtos de uma vez usando a planilha modelo (.xlsx) ou um .csv.

    )} @@ -426,7 +426,7 @@ export default function ProductForm({ Date: Mon, 2 Nov 2026 13:09:15 -0300 Subject: [PATCH 09/11] =?UTF-8?q?fix(import):=20exige=20identificador=20ao?= =?UTF-8?q?=20sincronizar=20o=20cat=C3=A1logo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Na sincronização, o identificador gerado da linha muda quando a linha é corrigida, e o produto antigo seria desativado e trocado por outro. O modo aditivo continua aceitando só valor e moeda. Também mostra o erro da prévia na tela do admin e corrige testes que ainda esperavam o rótulo "Arquivo CSV" e linhas sem moeda. --- .../product-import-jobs.service.spec.ts | 12 ++++++- .../product-import-jobs.service.ts | 36 ++++++++++++++++--- .../product-sync-preview.postgres.spec.ts | 1 + .../src/shared/constants/product-columns.ts | 2 +- .../src/components/shared/XlsxImporter.tsx | 3 +- .../SpecialistJourneyProductsPage.test.tsx | 2 +- .../admin/SpecialistJourneyProductsPage.tsx | 7 ++-- 7 files changed, 53 insertions(+), 10 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 c424fdf..7d32bbb 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 @@ -837,7 +837,7 @@ describe('ProductImportJobsService', () => { }); describe('identificador automático', () => { - const parse = async (lines: string[]) => { + const parse = async (lines: string[], mode = 'ADDITIVE') => { const service = new ProductImportJobsService( {} as any, new XlsxImportService(), @@ -846,6 +846,7 @@ describe('ProductImportJobsService', () => { return (service as any).parseImportRows( Buffer.from(lines.join('\n'), 'utf-8'), ProductType.CAR, + mode, ); }; @@ -876,6 +877,15 @@ describe('ProductImportJobsService', () => { parse(['marca;valor;currency', 'BMW;100;BRL', 'BMW;200;BRL']), ).rejects.toThrow(/sem identificador com os mesmos dados/); }); + + it('sincronização exige identificador em todas as linhas', async () => { + const lines = ['identificador;valor;currency', 'BMW-1;100;BRL', ';200;BRL']; + + await expect(parse(lines, 'SYNCHRONIZE')).rejects.toThrow( + /preencha o identificador.*linhas 3\)/, + ); + await expect(parse(lines)).resolves.toHaveLength(2); + }); }); it('lanca erro quando identificador vem vazio', async () => { 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 5c20b03..1737d64 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 @@ -255,7 +255,11 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }); } - const normalizedRows = await this.parseImportRows(fileBuffer, productType); + const normalizedRows = await this.parseImportRows( + fileBuffer, + productType, + mode, + ); const specialistId = options.context?.specialistId ?? user.id; let creationResult; try { @@ -376,7 +380,11 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { 'Modo de importação inválido. Use ADDITIVE ou SYNCHRONIZE.', ); } - const normalizedRows = await this.parseImportRows(fileBuffer, productType); + const normalizedRows = await this.parseImportRows( + fileBuffer, + productType, + mode, + ); const catalogSnapshot = await this.getSynchronizationCatalogSnapshot( productType, specialistId, @@ -2174,6 +2182,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { private async parseImportRows( fileBuffer: Buffer, productType: ProductType, + mode: string, ): Promise { // .xlsx é um zip: começa com "PK". const isXlsx = fileBuffer[0] === 0x50 && fileBuffer[1] === 0x4b; @@ -2193,8 +2202,12 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { unknownColumns: structureValidation.unknownColumns, }); } - const normalizedRows = rows.map((row) => - this.withIdentifier(productType, this.normalizeProductRow(row), columns), + const parsedRows = rows.map((row) => this.normalizeProductRow(row)); + if (mode === 'SYNCHRONIZE') { + this.requireIdentifiers(parsedRows); + } + const normalizedRows = parsedRows.map((row) => + this.withIdentifier(productType, row, columns), ); this.validateUniqueIdentifiers(normalizedRows); return normalizedRows; @@ -2247,6 +2260,21 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }; } + /** + * Na sincronização, um id gerado que muda com a linha desativaria o produto + * antigo e criaria outro no lugar; por isso ali o identificador é exigido. + */ + private requireIdentifiers(rows: ImportParsedRow[]): void { + // +2: cabeçalho na linha 1 e linhas da planilha começando em 1. + const lines = rows.flatMap((row, index) => + row.identificador ? [] : [index + 2], + ); + if (lines.length === 0) return; + throw new BadRequestException( + `Para sincronizar o catálogo, preencha o identificador de todas as linhas (faltando nas linhas ${lines.join(', ')}).`, + ); + } + private validateUniqueIdentifiers(rows: ImportParsedRow[]): void { const seen = new Set(); const duplicates = new Set(); 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 3dbc129..0a4ddbd 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 @@ -23,6 +23,7 @@ describeWithPostgres('product synchronization preview — PostgreSQL', () => { modelo: 'Roma', identificador: `KEEP-${suffix}`, valor: '1000000', + currency: 'BRL', estado: 'SP', ano: '2024', }; diff --git a/backend/src/shared/constants/product-columns.ts b/backend/src/shared/constants/product-columns.ts index 82ce391..4091bde 100644 --- a/backend/src/shared/constants/product-columns.ts +++ b/backend/src/shared/constants/product-columns.ts @@ -38,7 +38,7 @@ const IDENTIFICADOR: XlsxColumnDefinition = { required: false, type: 'string', description: - 'Código único do produto no seu catálogo. Reimportar o mesmo código atualiza o produto em vez de duplicar. Se ficar vazio, é gerado a partir dos dados da linha — nesse caso, mudar marca, modelo ou outro dado descritivo cria um produto novo. Preencha se for editar a linha depois.', + 'Código único do produto no seu catálogo. Reimportar o mesmo código atualiza o produto em vez de duplicar. Se ficar vazio, é gerado a partir dos dados da linha — nesse caso, mudar marca, modelo ou outro dado descritivo cria um produto novo. Preencha se for editar a linha depois. Obrigatório para sincronizar o catálogo.', example: 'BMW-X5-2023-01', }; diff --git a/frontend/src/components/shared/XlsxImporter.tsx b/frontend/src/components/shared/XlsxImporter.tsx index ea186f4..8e343cf 100644 --- a/frontend/src/components/shared/XlsxImporter.tsx +++ b/frontend/src/components/shared/XlsxImporter.tsx @@ -364,7 +364,8 @@ export function XlsxImporter({ duplicar. Sem{" "} identificador, ele é gerado a partir dos dados da linha; preencha-o se for - editar a linha depois. + editar a linha depois (na sincronização do catálogo ele é + obrigatório).
diff --git a/frontend/src/pages/admin/SpecialistJourneyProductsPage.test.tsx b/frontend/src/pages/admin/SpecialistJourneyProductsPage.test.tsx index 5178c34..593e401 100644 --- a/frontend/src/pages/admin/SpecialistJourneyProductsPage.test.tsx +++ b/frontend/src/pages/admin/SpecialistJourneyProductsPage.test.tsx @@ -56,7 +56,7 @@ describe("SpecialistJourneyProductsPage", () => { fireEvent.change(screen.getByLabelText("Modo da importação"), { target: { value: "SYNCHRONIZE" }, }); - fireEvent.change(screen.getByLabelText("Arquivo CSV"), { + fireEvent.change(screen.getByLabelText("Planilha de produtos"), { target: { files: [new File(["csv"], "catalog.csv", { type: "text/csv" })], }, diff --git a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx index eadd6fc..b87b7c0 100644 --- a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx +++ b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx @@ -77,8 +77,11 @@ export default function SpecialistJourneyProductsPage() { mode, ), ); - } catch { - setError("Planilha inválida ou incompatível com a especialidade selecionada."); + } catch (caught) { + setError( + (caught as { friendlyMessage?: string }).friendlyMessage ?? + "Planilha inválida ou incompatível com a especialidade selecionada.", + ); } }; From 6514663b5eadb25e511df8a30659790951052c52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius?= Date: Wed, 4 Nov 2026 23:08:01 -0300 Subject: [PATCH 10/11] =?UTF-8?q?fix(release):=20resolve=20review=20do=20#?= =?UTF-8?q?268=20sobre=20importa=C3=A7=C3=A3o,=20contrato=20e=20transfer?= =?UTF-8?q?=C3=AAncia?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Identificador automático passa a usar a linha inteira (inclusive valor, moeda e pasta): unidades que só diferem no preço ou nas fotos não se fundem entre importações; reimportar a linha idêntica continua atualizando. - .xlsx corrompido responde 400 em vez de 500. - Prefill do contrato devolve ano nulo (campo vazio) em vez de 0. - Hyperlink com rótulo em folder_url é lido pela URL de destino. - Erros de linha apontam a linha real mesmo com linhas em branco. - Transferência checa colisão de identificador no especialista de destino (409 PRODUCT_IDENTIFIER_CONFLICT). - Estado importado é normalizado para novo/seminovo/colecao; instruções deixam de citar "usado". - Doc do GET /appointments/check atualizada com o retorno atual. - Teste do XlsxImporter ajustado ao texto da dica. --- .../contracts/contracts.service.spec.ts | 12 +++ .../features/contracts/contracts.service.ts | 8 +- .../dto/prefill-contract-response.dto.ts | 2 +- .../product-import-jobs.service.spec.ts | 94 ++++++++++++++++--- .../product-import-jobs.service.ts | 76 ++++++++------- .../product-sync-preview.postgres.spec.ts | 6 +- .../features/product-template-columns.spec.ts | 41 ++++++++ .../products/product-transfer.spec.ts | 25 +++++ .../src/features/products/product-transfer.ts | 21 ++++- .../src/shared/constants/product-columns.ts | 4 +- .../shared/services/xlsx-import.service.ts | 38 ++++++-- docs/docs/agendamento-sem-calendly.md | 8 +- .../components/shared/XlsxImporter.test.tsx | 4 +- .../src/components/shared/XlsxImporter.tsx | 5 +- .../pages/specialist/CreateContractPage.tsx | 5 +- frontend/src/services/contracts.service.ts | 2 +- 16 files changed, 276 insertions(+), 75 deletions(-) diff --git a/backend/src/features/contracts/contracts.service.spec.ts b/backend/src/features/contracts/contracts.service.spec.ts index 2bb7e39..032db16 100644 --- a/backend/src/features/contracts/contracts.service.spec.ts +++ b/backend/src/features/contracts/contracts.service.spec.ts @@ -170,6 +170,18 @@ describe('ContractsService — prefillContract', () => { expect(result.product.price).toBe(120000); }); + it('keeps the year empty when the product was imported without one', async () => { + const prisma = mkPrisma(); + prisma.process.findUnique.mockResolvedValue( + processFixture({ car: { ...carFixture, ano: null } }), + ); + const service = mkSvc(prisma, mkPlatformCompanyService(10)); + + const result = await service.prefillContract('process-1', 'specialist-1'); + + expect(result.product.year).toBeNull(); + }); + it('rejects contract prefill without a negotiation snapshot', async () => { const prisma = mkPrisma(); prisma.process.findUnique.mockResolvedValue( diff --git a/backend/src/features/contracts/contracts.service.ts b/backend/src/features/contracts/contracts.service.ts index da73515..8cdefe7 100644 --- a/backend/src/features/contracts/contracts.service.ts +++ b/backend/src/features/contracts/contracts.service.ts @@ -733,7 +733,7 @@ export class ContractsService { id: string; brand: string; model: string; - year: number; + year: number | null; price: number; registration_id?: string; serial_number?: string; @@ -760,7 +760,7 @@ export class ContractsService { id: processData.car.id, brand: processData.car.marca || '', model: processData.car.modelo || '', - year: processData.car.ano || 0, + year: processData.car.ano ?? null, price: frozenProductPrice, registration_id: '', // Placa - preenchido pelo especialista serial_number: '', // Chassi - preenchido pelo especialista @@ -787,7 +787,7 @@ export class ContractsService { id: processData.boat.id, brand: processData.boat.marca || '', model: processData.boat.modelo || '', - year: processData.boat.ano || 0, + year: processData.boat.ano ?? null, price: frozenProductPrice, registration_id: '', // Inscrição - preenchido pelo especialista serial_number: '', // Hull number - preenchido pelo especialista @@ -814,7 +814,7 @@ export class ContractsService { id: processData.aircraft.id, brand: processData.aircraft.marca || '', model: processData.aircraft.modelo || '', - year: processData.aircraft.ano || 0, + year: processData.aircraft.ano ?? null, price: frozenProductPrice, registration_id: '', // Prefixo - preenchido pelo especialista serial_number: '', // Serial number - preenchido pelo especialista diff --git a/backend/src/features/contracts/dto/prefill-contract-response.dto.ts b/backend/src/features/contracts/dto/prefill-contract-response.dto.ts index b95fcbd..a460201 100644 --- a/backend/src/features/contracts/dto/prefill-contract-response.dto.ts +++ b/backend/src/features/contracts/dto/prefill-contract-response.dto.ts @@ -38,7 +38,7 @@ export class PrefillContractResponseDto { id: string; brand: string; model: string; - year: number; + year: number | null; // null quando o produto foi importado sem ano price: number; registration_id?: string; // placa/inscrição/prefixo serial_number?: string; // chassi/hull_number/serial 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 7d32bbb..1e332e0 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 @@ -448,7 +448,9 @@ describe('ProductImportJobsService', () => { it('exige confirmação explícita para sincronizar', async () => { const xlsxImportService = { - parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }), + parseCsv: jest + .fn() + .mockReturnValue({ rows: [validCarRow], rowNumbers: [2] }), validateStructure: jest.fn().mockReturnValue({ valid: true }), } as any; const service = new ProductImportJobsService( @@ -481,6 +483,7 @@ describe('ProductImportJobsService', () => { const xlsxImportService = { parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow, { ...validCarRow, modelo: 'Duplicado' }], + rowNumbers: [2, 3], }), validateStructure: jest.fn().mockReturnValue({ valid: true }), } as any; @@ -502,7 +505,9 @@ describe('ProductImportJobsService', () => { it('exige token da prévia mesmo quando a sincronização foi confirmada', async () => { const xlsxImportService = { - parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }), + parseCsv: jest + .fn() + .mockReturnValue({ rows: [validCarRow], rowNumbers: [2] }), validateStructure: jest.fn().mockReturnValue({ valid: true }), } as any; const prisma = { @@ -554,7 +559,9 @@ describe('ProductImportJobsService', () => { it('calcula o impacto da sincronização antes de criar o job', async () => { const xlsxImportService = { - parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }), + parseCsv: jest + .fn() + .mockReturnValue({ rows: [validCarRow], rowNumbers: [2] }), validateStructure: jest.fn().mockReturnValue({ valid: true }), } as any; const prisma = { @@ -611,7 +618,9 @@ describe('ProductImportJobsService', () => { catalogReads.shift() ?? [productA, productC], ); const xlsxImportService = { - parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }), + parseCsv: jest + .fn() + .mockReturnValue({ rows: [validCarRow], rowNumbers: [2] }), validateStructure: jest.fn().mockReturnValue({ valid: true }), } as any; const prisma = { @@ -680,7 +689,9 @@ describe('ProductImportJobsService', () => { { id: '22222222-2222-4222-8222-222222222222', identificador: 'STALE-B' }, ]; const xlsxImportService = { - parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }), + parseCsv: jest + .fn() + .mockReturnValue({ rows: [validCarRow], rowNumbers: [2] }), validateStructure: jest.fn().mockReturnValue({ valid: true }), } as any; const findMany = jest.fn().mockImplementation(async () => [...activeProducts]); @@ -843,49 +854,104 @@ describe('ProductImportJobsService', () => { new XlsxImportService(), {} as any, ); - return (service as any).parseImportRows( + const { rows } = await (service as any).parseImportRows( Buffer.from(lines.join('\n'), 'utf-8'), ProductType.CAR, mode, ); + return rows; }; - it('a mesma linha gera o mesmo identificador, mesmo com outro preço', async () => { - const [first] = await parse(['marca;modelo;valor;currency', 'BMW;X5;450000;BRL']); - const [repriced] = await parse(['marca;modelo;valor;currency', 'bmw;X5;399000;USD']); - const [other] = await parse(['marca;modelo;valor;currency', 'BMW;X6;450000;BRL']); + it('a mesma linha gera o mesmo identificador em importações diferentes', async () => { + const header = 'marca;modelo;valor;currency;folder_url'; + const [first] = await parse([header, 'BMW;X5;450000;BRL;https://d/1']); + const [again] = await parse([header, 'bmw;X5;450000;brl;https://d/1']); + const [other] = await parse([header, 'BMW;X6;450000;BRL;https://d/1']); expect(first.identificador).toMatch(/^auto-[0-9a-f]{12}$/); - expect(repriced.identificador).toBe(first.identificador); + expect(again.identificador).toBe(first.identificador); expect(other.identificador).not.toBe(first.identificador); }); + it('unidades que só diferem no preço, na moeda ou nas fotos não se fundem', async () => { + const header = 'marca;modelo;ano;valor;currency;folder_url'; + const [base] = await parse([ + header, + 'BMW;X5;2023;450000;BRL;https://d/1', + ]); + const variants = await Promise.all( + [ + 'BMW;X5;2023;500000;BRL;https://d/1', + 'BMW;X5;2023;450000;USD;https://d/1', + 'BMW;X5;2023;450000;BRL;https://d/2', + ].map(async (line) => (await parse([header, line]))[0]), + ); + + for (const variant of variants) { + expect(variant.identificador).not.toBe(base.identificador); + } + }); + it('linhas só com valor e moeda se distinguem pelo preço', async () => { const rows = await parse(['valor;currency', '100;BRL', '200;BRL']); expect(rows[0].identificador).not.toBe(rows[1].identificador); }); + it('estado com maiúscula ou acento vira o valor do formulário', async () => { + const rows = await parse([ + 'identificador;estado;valor;currency', + 'A;Seminovo;1;BRL', + 'B;Coleção;1;BRL', + 'C;usado;1;BRL', + ]); + + expect(rows.map((row: any) => row.estado)).toEqual([ + 'seminovo', + 'colecao', + 'usado', + ]); + }); + it('identificador informado é mantido', async () => { - const [row] = await parse(['identificador;valor;currency', 'BMW-1;100;BRL']); + const [row] = await parse([ + 'identificador;valor;currency', + 'BMW-1;100;BRL', + ]); expect(row.identificador).toBe('BMW-1'); }); it('rejeita linhas sem identificador com os mesmos dados', async () => { await expect( - parse(['marca;valor;currency', 'BMW;100;BRL', 'BMW;200;BRL']), + parse(['marca;valor;currency', 'BMW;100;BRL', 'BMW;100;BRL']), ).rejects.toThrow(/sem identificador com os mesmos dados/); }); it('sincronização exige identificador em todas as linhas', async () => { - const lines = ['identificador;valor;currency', 'BMW-1;100;BRL', ';200;BRL']; + const lines = [ + 'identificador;valor;currency', + 'BMW-1;100;BRL', + ';200;BRL', + ]; await expect(parse(lines, 'SYNCHRONIZE')).rejects.toThrow( /preencha o identificador.*linhas 3\)/, ); await expect(parse(lines)).resolves.toHaveLength(2); }); + + it('aponta a linha real do arquivo quando há linhas em branco', async () => { + const lines = [ + 'identificador;valor;currency', + 'BMW-1;100;BRL', + '', + 'BMW-2;150;BRL', + ';200;BRL', + ]; + + await expect(parse(lines, 'SYNCHRONIZE')).rejects.toThrow(/linhas 5\)/); + }); }); it('lanca erro quando identificador vem vazio', async () => { 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 1737d64..362bedf 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 @@ -145,15 +145,15 @@ const DEFAULT_MARCA: Record = { }; const DEFAULT_ESTADO = 'não informado'; -// Colunas que não descrevem o produto: ficam fora do identificador automático -// para que reimportar com outro preço ou outras fotos atualize o mesmo produto. -const NON_DESCRIPTIVE_COLUMNS = new Set([ - 'identificador', - 'valor', - 'currency', - 'folder_url', -]); +// Sem identificador, não há como saber se duas linhas de importações diferentes +// são a mesma unidade. O id gerado usa a linha inteira (inclusive preço, moeda +// e pasta de fotos): reimportar a linha igual atualiza o mesmo produto, e duas +// unidades que só diferem no preço ou nas fotos nunca se fundem. Mudar qualquer +// dado de uma linha sem identificador cria outro produto; para atualizar depois +// (ex.: novo preço), o identificador precisa ser preenchido. export const AUTO_IDENTIFIER_PREFIX = 'auto-'; +// Valores do select de estado em CommonProductFields.tsx. +const PRODUCT_ESTADOS = new Set(['novo', 'seminovo', 'colecao']); export function isImportSpreadsheet(fileName?: string): boolean { return /\.(xlsx|csv)$/i.test(fileName ?? ''); @@ -255,7 +255,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }); } - const normalizedRows = await this.parseImportRows( + const { rows: normalizedRows, rowNumbers } = await this.parseImportRows( fileBuffer, productType, mode, @@ -305,7 +305,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { items: { createMany: { data: normalizedRows.map((row, index) => ({ - row_number: index + 2, + row_number: rowNumbers[index], payload: row, folder_url: row.folder_url?.trim() || null, })), @@ -380,7 +380,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { 'Modo de importação inválido. Use ADDITIVE ou SYNCHRONIZE.', ); } - const normalizedRows = await this.parseImportRows( + const { rows: normalizedRows } = await this.parseImportRows( fileBuffer, productType, mode, @@ -2163,11 +2163,26 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { return Object.fromEntries( Object.entries(row).map(([key, rawValue]) => { const value = String(rawValue ?? '').trim(); - return [key, value === '-' ? '' : value]; + if (value === '-') return [key, '']; + return [key, key === 'estado' ? this.canonicalEstado(value) : value]; }), ); } + /** + * "Seminovo", "Coleção" etc. viram o valor do select do formulário de + * edição (novo/seminovo/colecao); sem isso o campo abre vazio ao editar. + * Outros valores passam como vieram. + */ + private canonicalEstado(value: string): string { + const key = value + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .toLowerCase() + .replace(/[\s-]+/g, ''); + return PRODUCT_ESTADOS.has(key) ? key : value; + } + /** * Lê .xlsx (o modelo baixado) ou .csv, valida o cabeçalho e devolve as * linhas normalizadas, já com identificador. Todo o resto do import (prévia, @@ -2183,10 +2198,10 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { fileBuffer: Buffer, productType: ProductType, mode: string, - ): Promise { + ): Promise<{ rows: ImportParsedRow[]; rowNumbers: number[] }> { // .xlsx é um zip: começa com "PK". const isXlsx = fileBuffer[0] === 0x50 && fileBuffer[1] === 0x4b; - const { rows } = isXlsx + const { rows, rowNumbers } = isXlsx ? await this.xlsxImportService.parseWorkbook(fileBuffer) : this.xlsxImportService.parseCsv(fileBuffer); const columns = this.getColumnsForType(productType); @@ -2204,21 +2219,19 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { } const parsedRows = rows.map((row) => this.normalizeProductRow(row)); if (mode === 'SYNCHRONIZE') { - this.requireIdentifiers(parsedRows); + this.requireIdentifiers(parsedRows, rowNumbers); } const normalizedRows = parsedRows.map((row) => this.withIdentifier(productType, row, columns), ); this.validateUniqueIdentifiers(normalizedRows); - return normalizedRows; + return { rows: normalizedRows, rowNumbers }; } /** - * Linha sem identificador ganha um derivado dos dados descritivos, para que - * reimportar a mesma linha atualize o produto em vez de duplicar. - * ponytail: mudar um dado descritivo (marca, km...) numa linha sem - * identificador gera outro id e cria um produto novo; a aba Instruções - * orienta a preencher o identificador quando a linha for editada depois. + * Linha sem identificador ganha um derivado da linha inteira, para que + * reimportar a mesma linha atualize o produto em vez de duplicar (ver + * comentário de AUTO_IDENTIFIER_PREFIX). */ private withIdentifier( productType: ProductType, @@ -2226,17 +2239,10 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { columns: XlsxColumnDefinition[], ): ImportParsedRow { if (row.identificador) return row; - const descriptive = columns + const basis = columns .map((column) => column.name) - .filter((name) => !NON_DESCRIPTIVE_COLUMNS.has(name) && row[name]) - .map((name) => [name, row[name].toLowerCase()]); - // Sem nenhum dado descritivo, só o preço distingue uma linha da outra. - const basis = descriptive.length - ? descriptive - : [ - ['valor', row.valor], - ['currency', row.currency?.toUpperCase()], - ]; + .filter((name) => name !== 'identificador' && row[name]) + .map((name) => [name, row[name].trim().toLowerCase()]); const hash = this.sha256(JSON.stringify([productType, basis])).slice(0, 12); return { ...row, identificador: `${AUTO_IDENTIFIER_PREFIX}${hash}` }; } @@ -2264,10 +2270,12 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { * Na sincronização, um id gerado que muda com a linha desativaria o produto * antigo e criaria outro no lugar; por isso ali o identificador é exigido. */ - private requireIdentifiers(rows: ImportParsedRow[]): void { - // +2: cabeçalho na linha 1 e linhas da planilha começando em 1. + private requireIdentifiers( + rows: ImportParsedRow[], + rowNumbers: number[], + ): void { const lines = rows.flatMap((row, index) => - row.identificador ? [] : [index + 2], + row.identificador ? [] : [rowNumbers[index]], ); if (lines.length === 0) return; throw new BadRequestException( 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 0a4ddbd..87a367f 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 @@ -28,7 +28,7 @@ describeWithPostgres('product synchronization preview — PostgreSQL', () => { ano: '2024', }; const xlsx = { - parseCsv: jest.fn().mockReturnValue({ rows: [row] }), + parseCsv: jest.fn().mockReturnValue({ rows: [row], rowNumbers: [2] }), validateStructure: jest.fn().mockReturnValue({ valid: true }), } as any; @@ -49,7 +49,7 @@ describeWithPostgres('product synchronization preview — PostgreSQL', () => { }); beforeEach(async () => { - xlsx.parseCsv.mockReturnValue({ rows: [row] }); + xlsx.parseCsv.mockReturnValue({ rows: [row], rowNumbers: [2] }); await prisma.productImportJob.deleteMany({ where: { specialist_id: specialistId }, }); @@ -722,7 +722,7 @@ describeWithPostgres('product synchronization preview — PostgreSQL', () => { identificador: `CREATED-THEN-DELETED-${suffix}`, modelo: 'Created then deleted', }; - xlsx.parseCsv.mockReturnValue({ rows: [createdRow] }); + xlsx.parseCsv.mockReturnValue({ rows: [createdRow], rowNumbers: [2] }); let createdId = ''; const drive = { importImagesForProductFromFolder: jest.fn(async ({ product_id }) => { diff --git a/backend/src/features/product-template-columns.spec.ts b/backend/src/features/product-template-columns.spec.ts index bec6892..1898617 100644 --- a/backend/src/features/product-template-columns.spec.ts +++ b/backend/src/features/product-template-columns.spec.ts @@ -1,4 +1,5 @@ import * as ExcelJS from 'exceljs'; +import { BadRequestException } from '@nestjs/common'; import { AIRCRAFT_COLUMNS, BOAT_COLUMNS, @@ -98,6 +99,46 @@ describe('template de importação de produtos', () => { expect(rows[0].folder_url).toBe(url); }); + it('hyperlink com rótulo ("Fotos") é lido pela URL de destino', async () => { + const workbook = await loadTemplate(xlsx, CAR_COLUMNS); + const data = workbook.worksheets[0]; + const url = 'https://drive.google.com/drive/folders/abc'; + data.getRow(2).getCell(CAR_COLUMNS.length).value = { + text: 'Fotos', + hyperlink: url, + }; + data.getRow(2).getCell(4).value = 1; + + const { rows } = await xlsx.parseWorkbook( + Buffer.from(await workbook.xlsx.writeBuffer()), + ); + + expect(rows[0].folder_url).toBe(url); + }); + + it('.xlsx corrompido responde 400, não erro interno', async () => { + await expect( + xlsx.parseWorkbook(Buffer.from('PK\x03\x04não é um xlsx', 'latin1')), + ).rejects.toBeInstanceOf(BadRequestException); + }); + + it('número da linha ignora linhas em branco puladas', async () => { + const workbook = await loadTemplate(xlsx, CAR_COLUMNS); + const data = workbook.worksheets[0]; + const valor = CAR_COLUMNS.findIndex((c) => c.name === 'valor') + 1; + data.getRow(2).getCell(valor).value = 100; + data.getRow(4).getCell(valor).value = 200; + const { rowNumbers } = await xlsx.parseWorkbook( + Buffer.from(await workbook.xlsx.writeBuffer()), + ); + expect(rowNumbers).toEqual([2, 4]); + + const csv = xlsx.parseCsv( + Buffer.from('valor;currency\n100;BRL\n\n200;BRL', 'utf-8'), + ); + expect(csv.rowNumbers).toEqual([2, 4]); + }); + it('CSV em outra ordem de colunas continua válido', () => { const csv = [ 'marca;modelo;identificador;valor;currency;estado;ano', diff --git a/backend/src/features/products/product-transfer.spec.ts b/backend/src/features/products/product-transfer.spec.ts index 495cae1..440d687 100644 --- a/backend/src/features/products/product-transfer.spec.ts +++ b/backend/src/features/products/product-transfer.spec.ts @@ -66,6 +66,31 @@ describe('transferProductSpecialist', () => { ); }); + it('blocks with a clear code when the target already uses the identifier', async () => { + const tx = db({ + car: { + findUnique: jest.fn().mockResolvedValue({ + id: 'car-1', + specialist_id: 'old', + identificador: 'auto-abc123', + }), + findFirst: jest.fn().mockResolvedValue({ id: 'car-2' }), + update: jest.fn(), + }, + }); + + await expect(transferProductSpecialist(tx, input)).rejects.toMatchObject({ + response: expect.objectContaining({ + code: 'PRODUCT_IDENTIFIER_CONFLICT', + }), + }); + expect(tx.car.findFirst).toHaveBeenCalledWith({ + where: { specialist_id: 'new', identificador: 'auto-abc123' }, + select: { id: true }, + }); + expect(tx.car.update).not.toHaveBeenCalled(); + }); + it('blocks when a process is in progress', async () => { const tx = db({ process: { findFirst: jest.fn().mockResolvedValue({ id: 'p-1' }) }, diff --git a/backend/src/features/products/product-transfer.ts b/backend/src/features/products/product-transfer.ts index b444dc7..e7a0033 100644 --- a/backend/src/features/products/product-transfer.ts +++ b/backend/src/features/products/product-transfer.ts @@ -39,7 +39,7 @@ export async function transferProductSpecialist( const delegate = (tx as any)[PRODUCT_DELEGATE_BY_TYPE[input.productType]]; const product = await delegate.findUnique({ where: { id: input.productId }, - select: { id: true, specialist_id: true }, + select: { id: true, specialist_id: true, identificador: true }, }); if (!product) throw new NotFoundException('Produto não encontrado'); if (product.specialist_id === input.toSpecialistId) { @@ -76,6 +76,25 @@ export async function transferProductSpecialist( }); } + // O identificador é único por especialista, e o automático (`auto-…`) não + // inclui o especialista: a mesma linha importada por dois deles gera o mesmo + // id. Sem esta checagem o update cai no P2002 genérico. + if (product.identificador) { + const clash = await delegate.findFirst({ + where: { + specialist_id: input.toSpecialistId, + identificador: product.identificador, + }, + select: { id: true }, + }); + if (clash) { + throw new ConflictException({ + code: 'PRODUCT_IDENTIFIER_CONFLICT', + message: `O especialista de destino já tem um produto com o identificador "${product.identificador}". Altere o identificador de um dos produtos antes de transferir.`, + }); + } + } + await delegate.update({ where: { id: input.productId }, data: { specialist_id: input.toSpecialistId }, diff --git a/backend/src/shared/constants/product-columns.ts b/backend/src/shared/constants/product-columns.ts index 4091bde..23e294c 100644 --- a/backend/src/shared/constants/product-columns.ts +++ b/backend/src/shared/constants/product-columns.ts @@ -38,7 +38,7 @@ const IDENTIFICADOR: XlsxColumnDefinition = { required: false, type: 'string', description: - 'Código único do produto no seu catálogo. Reimportar o mesmo código atualiza o produto em vez de duplicar. Se ficar vazio, é gerado a partir dos dados da linha — nesse caso, mudar marca, modelo ou outro dado descritivo cria um produto novo. Preencha se for editar a linha depois. Obrigatório para sincronizar o catálogo.', + 'Código único do produto no seu catálogo. Reimportar o mesmo código atualiza o produto (inclusive preço e fotos) em vez de duplicar. Se ficar vazio, é gerado a partir da linha inteira — reimportar a linha idêntica atualiza o mesmo produto, mas mudar qualquer dado (inclusive valor, moeda ou pasta de fotos) cria um produto novo. Preencha se for atualizar a linha depois. Obrigatório para sincronizar o catálogo.', example: 'BMW-X5-2023-01', }; @@ -79,7 +79,7 @@ function common( required: false, type: 'string', description: - 'Estado de conservação (ex.: novo, seminovo, usado). Se vazio, "não informado".', + 'Estado de conservação: novo, seminovo ou colecao. Se vazio, "não informado".', example: 'seminovo', }, { diff --git a/backend/src/shared/services/xlsx-import.service.ts b/backend/src/shared/services/xlsx-import.service.ts index 73e6ab8..0964b4b 100644 --- a/backend/src/shared/services/xlsx-import.service.ts +++ b/backend/src/shared/services/xlsx-import.service.ts @@ -35,11 +35,15 @@ export interface EmbeddedImage { */ export interface XlsxParseResult { rows: ImportParsedRow[]; + /** Linha da planilha (1 = cabeçalho) de cada item de `rows`; linhas em branco são puladas. */ + rowNumbers: number[]; imageMap: Map; } export interface CsvParseResult { rows: ImportParsedRow[]; + /** Linha do arquivo (1 = cabeçalho) de cada item de `rows`; linhas em branco são puladas. */ + rowNumbers: number[]; } @Injectable() @@ -51,7 +55,14 @@ export class XlsxImportService { */ async parseWorkbook(fileBuffer: Buffer): Promise { const workbook = new ExcelJS.Workbook(); - await workbook.xlsx.load(fileBuffer as any); + try { + await workbook.xlsx.load(fileBuffer as any); + } catch { + // Zip truncado ou renomeado para .xlsx: o exceljs lança Error comum. + throw new BadRequestException( + 'Não foi possível ler a planilha: o arquivo .xlsx está corrompido ou não é uma planilha válida. Baixe o modelo novamente e salve como .xlsx.', + ); + } const worksheet = workbook.worksheets[0]; if (!worksheet) { @@ -80,6 +91,7 @@ export class XlsxImportService { // 2. Extrair dados (linha 2 em diante) const rows: ImportParsedRow[] = []; + const rowNumbers: number[] = []; const rowCount = worksheet.rowCount; for (let rowNum = 2; rowNum <= rowCount; rowNum++) { @@ -89,9 +101,11 @@ export class XlsxImportService { headers.forEach((header, colIndex) => { if (!header) return; - // `text` em vez de `value`: o Excel transforma links (ex.: folder_url) - // em objetos hyperlink, que viravam "[object Object]" com String(). - const value = row.getCell(colIndex + 1).text.trim(); + // O Excel transforma links (ex.: folder_url) em objetos hyperlink, que + // viravam "[object Object]" com String(). Num link com rótulo ("Fotos"), + // `text` é o rótulo; o dado é o destino, em `hyperlink`. + const cell = row.getCell(colIndex + 1); + const value = (cell.hyperlink ?? cell.text).trim(); if (value !== '') { hasData = true; @@ -103,6 +117,7 @@ export class XlsxImportService { if (hasData) { rows.push(parsedRow); + rowNumbers.push(rowNum); } } @@ -158,7 +173,7 @@ export class XlsxImportService { }); } - return { rows, imageMap }; + return { rows, rowNumbers, imageMap }; } /** @@ -179,10 +194,13 @@ export class XlsxImportService { const rawText = utf8Attempt.includes('\uFFFD') ? iconv.decode(withoutBom, 'windows-1252') : utf8Attempt; - const lines = rawText + // Guarda o número original de cada linha para os erros apontarem a linha + // certa mesmo com linhas em branco no meio do arquivo. + const numberedLines = rawText .split(/\r\n|\n|\r/) - .map((line) => line.trim()) - .filter((line) => line.length > 0); + .map((line, index) => ({ text: line.trim(), number: index + 1 })) + .filter((line) => line.text.length > 0); + const lines = numberedLines.map((line) => line.text); if (lines.length < 2) { throw new BadRequestException( @@ -201,6 +219,7 @@ export class XlsxImportService { } const rows: ImportParsedRow[] = []; + const rowNumbers: number[] = []; for (let lineIndex = 1; lineIndex < lines.length; lineIndex++) { const columns = this.splitCsvLine(lines[lineIndex], delimiter); @@ -219,6 +238,7 @@ export class XlsxImportService { if (hasData) { rows.push(parsedRow); + rowNumbers.push(numberedLines[lineIndex].number); } } @@ -228,7 +248,7 @@ export class XlsxImportService { ); } - return { rows }; + return { rows, rowNumbers }; } /** diff --git a/docs/docs/agendamento-sem-calendly.md b/docs/docs/agendamento-sem-calendly.md index cb925ca..de25bc7 100644 --- a/docs/docs/agendamento-sem-calendly.md +++ b/docs/docs/agendamento-sem-calendly.md @@ -43,7 +43,13 @@ A remarcação de um compromisso já confirmado continua sendo uma ação separa | `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. | -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. +A consulta do próprio pedido retorna somente: + +- `{ exists: false, process: null }` quando o cliente nunca abriu processo para esse produto e especialista; +- `{ exists: false, process }` quando o processo mais recente já foi encerrado (`COMPLETED` ou `REJECTED`); +- `{ exists: true, appointment_id, process_id, appointment_status, scheduling_method, appointment_datetime, process }` quando há processo ativo. Os campos do agendamento vêm `null` se o processo ativo não tiver agendamento `PENDING`/`SCHEDULED` do próprio cliente. Em pedido `EMAIL`, inclui também `specialist_contact_email` (o e-mail comercial, que já é público). + +`process` é a linha do tempo mínima: `{ id, status, is_active, status_history: [{ status, changed_at }] }`. Nenhuma das formas traz nomes ou contatos do cliente. Um pedido ativo duplicado responde `409/ACTIVE_PROCESS_EXISTS` com `error.details.existing_request` no formato do caso ativo, sem `exists` e sem `process`. Outros conflitos não expõem IDs ou contatos do compromisso concorrente. 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. diff --git a/frontend/src/components/shared/XlsxImporter.test.tsx b/frontend/src/components/shared/XlsxImporter.test.tsx index c9377b6..5115f29 100644 --- a/frontend/src/components/shared/XlsxImporter.test.tsx +++ b/frontend/src/components/shared/XlsxImporter.test.tsx @@ -19,14 +19,14 @@ describe("XlsxImporter", () => { const tip = screen.getByText( (_, element) => element?.tagName === "LI" && - element.textContent?.includes("Produtos com") === true && + element.textContent?.includes("Reimportar a mesma linha") === 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).", + "Reimportar a mesma linha atualiza o produto em vez de duplicar. Sem identificador, ele é gerado a partir da linha inteira: mudar qualquer dado, inclusive o valor, cria um produto novo. Preencha-o se for atualizar a linha depois (na sincronização do catálogo ele é obrigatório).", ); expect(sentence?.querySelector("strong")?.textContent).toBe( "identificador", diff --git a/frontend/src/components/shared/XlsxImporter.tsx b/frontend/src/components/shared/XlsxImporter.tsx index 8e343cf..b7c7593 100644 --- a/frontend/src/components/shared/XlsxImporter.tsx +++ b/frontend/src/components/shared/XlsxImporter.tsx @@ -363,8 +363,9 @@ export function XlsxImporter({ Reimportar a mesma linha atualiza o produto em vez de duplicar. Sem{" "} identificador, ele - é gerado a partir dos dados da linha; preencha-o se for - editar a linha depois (na sincronização do catálogo ele é + é gerado a partir da linha inteira: mudar qualquer dado, + inclusive o valor, cria um produto novo. Preencha-o se for + atualizar a linha depois (na sincronização do catálogo ele é obrigatório). diff --git a/frontend/src/pages/specialist/CreateContractPage.tsx b/frontend/src/pages/specialist/CreateContractPage.tsx index 5a58ccc..531506d 100644 --- a/frontend/src/pages/specialist/CreateContractPage.tsx +++ b/frontend/src/pages/specialist/CreateContractPage.tsx @@ -291,7 +291,10 @@ export default function CreateContractPage() { "vehicle_model", `${data.product.brand} ${data.product.model}`, ); - setValue("vehicle_year", String(data.product.year)); + setValue( + "vehicle_year", + data.product.year ? String(data.product.year) : "", + ); setValue("vehicle_registration_id", data.product.registration_id || ""); setValue("vehicle_serial_number", data.product.serial_number || ""); setValue("vehicle_technical_info", data.product.technical_info || ""); diff --git a/frontend/src/services/contracts.service.ts b/frontend/src/services/contracts.service.ts index 76d09c7..8f552b6 100644 --- a/frontend/src/services/contracts.service.ts +++ b/frontend/src/services/contracts.service.ts @@ -28,7 +28,7 @@ export interface PrefillProduct { id: number; brand: string; model: string; - year: number; + year: number | null; price: number; registration_id?: string; serial_number?: string; From 6ebb58605bf807cd4437707705bc175005625dde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius?= Date: Fri, 6 Nov 2026 12:31:20 -0300 Subject: [PATCH 11/11] fix(import): resolve segundo review do #269 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Hyperlink só vale pelo destino em folder_url; nas demais colunas o texto exibido é mantido (um link num "modelo" não vira a URL no catálogo). - folder_url aceita a fórmula =HYPERLINK(...) e é recusado quando não é link ou ID de pasta do Drive (extractDriveFolderId compartilhado com o Drive). - Hash do identificador automático normaliza números (450000 = 450000.00) e compara a pasta pelo ID do Drive (ignora ?usp=sharing). - Prévia (impact.autoIdentifierNewItems/autoIdentifierReactivatedItems) e resultado (autoIdentifierCreatedCount/autoIdentifierReactivatedCount) avisam quantas linhas sem identificador criam ou reativam produto; o front mostra o aviso no importador e na prévia do admin. - Aba Instruções explica o comportamento das linhas sem identificador. - Transferência checa colisão de identificador sem a guarda inútil. - architecture.md atualizado (hash e 409 PRODUCT_IDENTIFIER_CONFLICT). --- architecture.md | 4 +- .../features/drive-import/drive-folder-id.ts | 16 ++++ .../drive-import/drive-import.service.ts | 17 +--- .../product-import-jobs.service.spec.ts | 95 ++++++++++++++++-- .../product-import-jobs.service.ts | 96 +++++++++++++++++-- .../features/product-template-columns.spec.ts | 36 +++++++ .../products/product-transfer.spec.ts | 7 +- .../src/features/products/product-transfer.ts | 24 +++-- backend/src/shared/dto/import-response.dto.ts | 7 ++ .../shared/services/xlsx-import.service.ts | 33 +++++-- .../src/components/shared/XlsxImporter.tsx | 31 ++++++ .../admin/SpecialistJourneyProductsPage.tsx | 9 ++ .../admin-specialist-journey.service.ts | 2 + .../services/product-import-jobs.service.ts | 4 + 14 files changed, 328 insertions(+), 53 deletions(-) create mode 100644 backend/src/features/drive-import/drive-folder-id.ts diff --git a/architecture.md b/architecture.md index 7e49181..c453c82 100644 --- a/architecture.md +++ b/architecture.md @@ -285,7 +285,7 @@ Cada domínio expõe: "images": [] } ``` -- `POST /cars|boats|aircrafts/import-csv` — aceita `.xlsx` (template) ou `.csv`. Só `valor` e `currency` (`BRL`/`USD`) são obrigatórios. Sem `identificador`, o import gera `auto-` a partir dos campos descritivos da linha (sem valor/moeda/folder_url), então reimportar a mesma linha atualiza em vez de duplicar. Na criação, campos vazios viram padrão: `marca` = tipo (Carro/Lancha/Aeronave), `modelo` = identificador, `estado` = "não informado", `ano` = null; no update, campos vazios não sobrescrevem o que existe. +- `POST /cars|boats|aircrafts/import-csv` — aceita `.xlsx` (template) ou `.csv`. Só `valor` e `currency` (`BRL`/`USD`) são obrigatórios. Sem `identificador`, o import gera `auto-` a partir da linha inteira, inclusive `valor`, `currency` e `folder_url` (normalizados: `450000` = `450000.00`; link da pasta comparado pelo ID do Drive). Reimportar a linha idêntica atualiza o mesmo produto (e reativa se estiver desativado); mudar qualquer dado, inclusive o preço, cria outro produto. Para atualizar uma linha depois, preencha o `identificador`. A prévia (`impact.autoIdentifierNewItems`/`autoIdentifierReactivatedItems`) e o resultado (`autoIdentifierCreatedCount`/`autoIdentifierReactivatedCount`) mostram quantas linhas sem identificador criam ou reativam produto. `folder_url` precisa ser link ou ID de pasta do Drive; no `.xlsx`, hyperlink e fórmula `HYPERLINK` valem pelo destino (só nessa coluna). Na criação, campos vazios viram padrão: `marca` = tipo (Carro/Lancha/Aeronave), `modelo` = identificador, `estado` = "não informado", `ano` = null; no update, campos vazios não sobrescrevem o que existe. - payload: ```json { @@ -357,7 +357,7 @@ Cada domínio expõe: "updated": true } ``` -- `PATCH /cars|boats|aircrafts/:id/specialist` (somente ADMIN) — transfere o produto para outro especialista ativo da mesma especialidade. `409 PRODUCT_HAS_OPEN_PROCESSES` se houver processo não concluído/rejeitado ou agendamento pendente/agendado; processos antigos mantêm o especialista original. Auditado como `PRODUCT_TRANSFER`. +- `PATCH /cars|boats|aircrafts/:id/specialist` (somente ADMIN) — transfere o produto para outro especialista ativo da mesma especialidade. `409 PRODUCT_HAS_OPEN_PROCESSES` se houver processo não concluído/rejeitado ou agendamento pendente/agendado; `409 PRODUCT_IDENTIFIER_CONFLICT` se o especialista de destino já tiver produto com o mesmo `identificador`; processos antigos mantêm o especialista original. Auditado como `PRODUCT_TRANSFER`. - payload: ```json { diff --git a/backend/src/features/drive-import/drive-folder-id.ts b/backend/src/features/drive-import/drive-folder-id.ts new file mode 100644 index 0000000..d0b778d --- /dev/null +++ b/backend/src/features/drive-import/drive-folder-id.ts @@ -0,0 +1,16 @@ +/** + * ID da pasta do Google Drive a partir do link (`/folders/` ou `?id=`) + * ou do próprio ID. `null` quando não é nenhum dos dois. + * + * Variações do mesmo link (`?usp=sharing`, `/u/0/`) dão o mesmo ID. + */ +export function extractDriveFolderId(urlOrId: string): string | null { + const trimmed = urlOrId.trim(); + const fromFolderPath = trimmed.match(/\/folders\/([a-zA-Z0-9_-]{10,})/)?.[1]; + if (fromFolderPath) return fromFolderPath; + + const fromQuery = trimmed.match(/[?&]id=([a-zA-Z0-9_-]{10,})/)?.[1]; + if (fromQuery) return fromQuery; + + return /^[a-zA-Z0-9_-]{10,}$/.test(trimmed) ? trimmed : null; +} diff --git a/backend/src/features/drive-import/drive-import.service.ts b/backend/src/features/drive-import/drive-import.service.ts index cb9a115..5253224 100644 --- a/backend/src/features/drive-import/drive-import.service.ts +++ b/backend/src/features/drive-import/drive-import.service.ts @@ -16,6 +16,7 @@ import { PrismaService } from 'src/prisma/prisma.service'; import { S3Service } from 'src/aws/s3.service'; import { ImportDriveImagesDto } from './dto/import-drive-images.dto'; import { UserEntity } from 'src/auth/entities/user.entity'; +import { extractDriveFolderId } from './drive-folder-id'; type DriveFile = { id: string; @@ -426,20 +427,8 @@ export class DriveImportService { } private extractFolderId(urlOrId: string): string { - const trimmed = urlOrId.trim(); - const folderRegex = /\/folders\/([a-zA-Z0-9_-]{10,})/; - const idRegex = /[?&]id=([a-zA-Z0-9_-]{10,})/; - - const fromFolderPath = trimmed.match(folderRegex)?.[1]; - if (fromFolderPath) return fromFolderPath; - - const fromQuery = trimmed.match(idRegex)?.[1]; - if (fromQuery) return fromQuery; - - if (/^[a-zA-Z0-9_-]{10,}$/.test(trimmed)) { - return trimmed; - } - + const folderId = extractDriveFolderId(urlOrId); + if (folderId) return folderId; throw new BadRequestException('Link/ID da pasta do Google Drive inválido'); } 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 1e332e0..f6a0c6b 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 @@ -864,9 +864,9 @@ describe('ProductImportJobsService', () => { it('a mesma linha gera o mesmo identificador em importações diferentes', async () => { const header = 'marca;modelo;valor;currency;folder_url'; - const [first] = await parse([header, 'BMW;X5;450000;BRL;https://d/1']); - const [again] = await parse([header, 'bmw;X5;450000;brl;https://d/1']); - const [other] = await parse([header, 'BMW;X6;450000;BRL;https://d/1']); + const [first] = await parse([header, 'BMW;X5;450000;BRL;https://drive.google.com/drive/folders/1AbCdEfGhIjK']); + const [again] = await parse([header, 'bmw;X5;450000;brl;https://drive.google.com/drive/folders/1AbCdEfGhIjK']); + const [other] = await parse([header, 'BMW;X6;450000;BRL;https://drive.google.com/drive/folders/1AbCdEfGhIjK']); expect(first.identificador).toMatch(/^auto-[0-9a-f]{12}$/); expect(again.identificador).toBe(first.identificador); @@ -877,13 +877,13 @@ describe('ProductImportJobsService', () => { const header = 'marca;modelo;ano;valor;currency;folder_url'; const [base] = await parse([ header, - 'BMW;X5;2023;450000;BRL;https://d/1', + 'BMW;X5;2023;450000;BRL;https://drive.google.com/drive/folders/1AbCdEfGhIjK', ]); const variants = await Promise.all( [ - 'BMW;X5;2023;500000;BRL;https://d/1', - 'BMW;X5;2023;450000;USD;https://d/1', - 'BMW;X5;2023;450000;BRL;https://d/2', + 'BMW;X5;2023;500000;BRL;https://drive.google.com/drive/folders/1AbCdEfGhIjK', + 'BMW;X5;2023;450000;USD;https://drive.google.com/drive/folders/1AbCdEfGhIjK', + 'BMW;X5;2023;450000;BRL;https://drive.google.com/drive/folders/2ZyXwVuTsRqP', ].map(async (line) => (await parse([header, line]))[0]), ); @@ -913,6 +913,87 @@ describe('ProductImportJobsService', () => { ]); }); + it('mesmo preço ou mesma pasta escritos de outro jeito geram o mesmo id', async () => { + const header = 'marca;valor;currency;folder_url'; + const folder = 'https://drive.google.com/drive/folders/1AbCdEfGhIjK'; + const [base] = await parse([header, `BMW;450000;BRL;${folder}`]); + const [variant] = await parse([ + header, + `BMW;450000.00;BRL;${folder}?usp=sharing`, + ]); + + expect(variant.identificador).toBe(base.identificador); + }); + + it('recusa folder_url que não é link de pasta do Drive', async () => { + await expect( + parse([ + 'identificador;valor;currency;folder_url', + 'A;1;BRL;https://drive.google.com/drive/folders/1AbCdEfGhIjK', + 'B;1;BRL;Fotos', + ]), + ).rejects.toThrow(/folder_url.*linhas 3\./); + }); + + it('conta linhas sem identificador que criam ou reativam produto', () => { + const service = new ProductImportJobsService( + {} as any, + {} as any, + {} as any, + ); + const impact = (service as any).autoIdentifierImpact( + [ + { identificador: 'auto-novo' }, + { identificador: 'auto-ativo' }, + { identificador: 'auto-inativo' }, + { identificador: 'MANUAL-1' }, + ], + [ + { identificador: 'auto-ativo', isActive: true }, + { identificador: 'auto-inativo', isActive: false }, + { identificador: 'MANUAL-1', isActive: false }, + ], + ); + + expect(impact).toEqual({ + autoIdentifierNewItems: 1, + autoIdentifierReactivatedItems: 1, + }); + }); + + it('resultado informa produtos criados e reativados sem identificador', () => { + const service = new ProductImportJobsService( + {} as any, + {} as any, + {} as any, + ); + const item = (overrides: Record) => ({ + row_number: 2, + status: 'COMPLETED', + action: 'CREATED', + product_id: 'p', + error_message: null, + warnings: null, + ...overrides, + }); + const result = (service as any).buildImportResponse([ + item({ payload: { identificador: 'auto-a' } }), + item({ + action: 'UPDATED', + payload: { + identificador: 'auto-b', + __productImportEffect: { reactivated: true }, + }, + }), + item({ payload: { identificador: 'MANUAL-1' } }), + ]); + + expect(result).toMatchObject({ + autoIdentifierCreatedCount: 1, + autoIdentifierReactivatedCount: 1, + }); + }); + it('identificador informado é mantido', async () => { const [row] = await parse([ 'identificador;valor;currency', 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 362bedf..de6966b 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 @@ -44,6 +44,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 { extractDriveFolderId } from '../drive-import/drive-folder-id'; import { createHash, createHmac, @@ -92,8 +93,18 @@ type ImportImpact = { matchingItems: number; newOrReactivatedItems: number; deactivationCandidates: number; + // Linhas sem identificador: sem como casar com uma edição anterior, então + // criam produto novo (ex.: mesmo carro com preço novo) ou, se a linha for + // idêntica à de um produto desativado, reativam esse produto. + autoIdentifierNewItems: number; + autoIdentifierReactivatedItems: number; }; +type AutoIdentifierImpact = Pick< + ImportImpact, + 'autoIdentifierNewItems' | 'autoIdentifierReactivatedItems' +>; + type SynchronizationCatalogSnapshot = { candidateIds: string[]; catalogDigest: string; @@ -393,12 +404,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { const impact = mode === 'SYNCHRONIZE' ? catalogSnapshot.impact - : this.deriveImportImpact( - catalogSnapshot.impact.activeItemsBefore, - catalogSnapshot.impact.matchingItems, - normalizedRows, - 0, - ); + : { ...catalogSnapshot.impact, deactivationCandidates: 0 }; const synchronizePreviewToken = mode === 'SYNCHRONIZE' ? this.createSynchronizePreviewToken( @@ -545,6 +551,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { matchingItems, rows, candidateIds.length, + this.autoIdentifierImpact(rows, catalogProducts), ), }; } @@ -1408,11 +1415,30 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { return { ...snapshot.impact, deactivationCandidates: 0 }; } + private autoIdentifierImpact( + rows: ImportParsedRow[], + catalogProducts: CatalogProductSnapshot[], + ): AutoIdentifierImpact { + const catalog = new Map( + catalogProducts.map((product) => [product.identificador, product]), + ); + let autoIdentifierNewItems = 0; + let autoIdentifierReactivatedItems = 0; + for (const row of rows) { + if (!row.identificador?.startsWith(AUTO_IDENTIFIER_PREFIX)) continue; + const existing = catalog.get(row.identificador); + if (!existing) autoIdentifierNewItems += 1; + else if (!existing.isActive) autoIdentifierReactivatedItems += 1; + } + return { autoIdentifierNewItems, autoIdentifierReactivatedItems }; + } + private deriveImportImpact( activeItemsBefore: number, matchingItems: number, rows: ImportParsedRow[], deactivationCandidates: number, + autoIdentifier: AutoIdentifierImpact, ): ImportImpact { const incomingIdentifiers = new Set( rows.map((row) => row.identificador?.trim()).filter(Boolean), @@ -1426,6 +1452,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { incomingIdentifiers.size - matchingItems, ), deactivationCandidates, + ...autoIdentifier, }; } @@ -2202,7 +2229,9 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { // .xlsx é um zip: começa com "PK". const isXlsx = fileBuffer[0] === 0x50 && fileBuffer[1] === 0x4b; const { rows, rowNumbers } = isXlsx - ? await this.xlsxImportService.parseWorkbook(fileBuffer) + ? await this.xlsxImportService.parseWorkbook(fileBuffer, { + linkColumns: ['folder_url'], + }) : this.xlsxImportService.parseCsv(fileBuffer); const columns = this.getColumnsForType(productType); const structureValidation = this.xlsxImportService.validateStructure( @@ -2218,6 +2247,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }); } const parsedRows = rows.map((row) => this.normalizeProductRow(row)); + this.validateFolderUrls(parsedRows, rowNumbers); if (mode === 'SYNCHRONIZE') { this.requireIdentifiers(parsedRows, rowNumbers); } @@ -2240,13 +2270,28 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { ): ImportParsedRow { if (row.identificador) return row; const basis = columns - .map((column) => column.name) - .filter((name) => name !== 'identificador' && row[name]) - .map((name) => [name, row[name].trim().toLowerCase()]); + .filter((column) => column.name !== 'identificador' && row[column.name]) + .map((column) => [column.name, this.hashValue(column, row[column.name])]); const hash = this.sha256(JSON.stringify([productType, basis])).slice(0, 12); return { ...row, identificador: `${AUTO_IDENTIFIER_PREFIX}${hash}` }; } + /** + * Mesmo dado escrito de outro jeito gera o mesmo id: 450000 e 450000.00, + * ou o link da pasta com e sem ?usp=sharing. + */ + private hashValue(column: XlsxColumnDefinition, raw: string): string { + const value = raw.trim(); + if (column.type === 'number') { + const number = Number(value); + if (Number.isFinite(number)) return String(number); + } + if (column.name === 'folder_url') { + return extractDriveFolderId(value) ?? value; + } + return value.toLowerCase(); + } + private withCreationDefaults< T extends { identificador: string; @@ -2283,6 +2328,25 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { ); } + /** + * folder_url que não é link nem ID de pasta do Drive (ex.: o rótulo "Fotos" + * de um link que não deu para ler) é recusado antes de virar produto. + */ + private validateFolderUrls( + rows: ImportParsedRow[], + rowNumbers: number[], + ): void { + const lines = rows.flatMap((row, index) => + row.folder_url && !extractDriveFolderId(row.folder_url) + ? [rowNumbers[index]] + : [], + ); + if (lines.length === 0) return; + throw new BadRequestException( + `folder_url precisa ser o link de uma pasta do Google Drive (https://drive.google.com/drive/folders/...). Valor inválido nas linhas ${lines.join(', ')}.`, + ); + } + private validateUniqueIdentifiers(rows: ImportParsedRow[]): void { const seen = new Set(); const duplicates = new Set(); @@ -2366,12 +2430,22 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { const updatedIds: string[] = []; const errorRows: ImportErrorRow[] = []; const warningRows: ImportErrorRow[] = []; + let autoIdentifierCreatedCount = 0; + let autoIdentifierReactivatedCount = 0; for (const item of items) { if ( item.status === ProductImportItemStatus.COMPLETED || item.status === ProductImportItemStatus.COMPLETED_WITH_WARNINGS ) { + const payload = item.payload as ImportItemPayload | null; + if (payload?.identificador?.startsWith(AUTO_IDENTIFIER_PREFIX)) { + if (item.action === 'CREATED') autoIdentifierCreatedCount += 1; + if (payload.__productImportEffect?.reactivated) { + autoIdentifierReactivatedCount += 1; + } + } + if (item.action === 'CREATED' && item.product_id) { insertedIds.push(item.product_id); } @@ -2439,6 +2513,8 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { deactivatedCount, deactivatedIds, reactivatedCount, + autoIdentifierCreatedCount, + autoIdentifierReactivatedCount, }; } diff --git a/backend/src/features/product-template-columns.spec.ts b/backend/src/features/product-template-columns.spec.ts index 1898617..7e8eda7 100644 --- a/backend/src/features/product-template-columns.spec.ts +++ b/backend/src/features/product-template-columns.spec.ts @@ -94,6 +94,7 @@ describe('template de importação de produtos', () => { const { rows } = await xlsx.parseWorkbook( Buffer.from(await workbook.xlsx.writeBuffer()), + { linkColumns: ['folder_url'] }, ); expect(rows[0].folder_url).toBe(url); @@ -111,6 +112,41 @@ describe('template de importação de produtos', () => { const { rows } = await xlsx.parseWorkbook( Buffer.from(await workbook.xlsx.writeBuffer()), + { linkColumns: ['folder_url'] }, + ); + + expect(rows[0].folder_url).toBe(url); + }); + + it('link em coluna que não é de link mantém o texto exibido', async () => { + const workbook = await loadTemplate(xlsx, CAR_COLUMNS); + const data = workbook.worksheets[0]; + const modelo = CAR_COLUMNS.findIndex((c) => c.name === 'modelo') + 1; + data.getRow(2).getCell(modelo).value = { + text: 'Phenom 300', + hyperlink: 'https://vendedor.com/phenom', + }; + + const { rows } = await xlsx.parseWorkbook( + Buffer.from(await workbook.xlsx.writeBuffer()), + { linkColumns: ['folder_url'] }, + ); + + expect(rows[0].modelo).toBe('Phenom 300'); + }); + + it('fórmula HYPERLINK em folder_url é lida pela URL', async () => { + const workbook = await loadTemplate(xlsx, CAR_COLUMNS); + const data = workbook.worksheets[0]; + const url = 'https://drive.google.com/drive/folders/1AbCdEfGhIjK'; + data.getRow(2).getCell(CAR_COLUMNS.length).value = { + formula: `HYPERLINK("${url}","Fotos")`, + result: 'Fotos', + } as ExcelJS.CellFormulaValue; + + const { rows } = await xlsx.parseWorkbook( + Buffer.from(await workbook.xlsx.writeBuffer()), + { linkColumns: ['folder_url'] }, ); expect(rows[0].folder_url).toBe(url); diff --git a/backend/src/features/products/product-transfer.spec.ts b/backend/src/features/products/product-transfer.spec.ts index 440d687..41cc517 100644 --- a/backend/src/features/products/product-transfer.spec.ts +++ b/backend/src/features/products/product-transfer.spec.ts @@ -16,7 +16,12 @@ function db(overrides: Record = {}) { car: { findUnique: jest .fn() - .mockResolvedValue({ id: 'car-1', specialist_id: 'old' }), + .mockResolvedValue({ + id: 'car-1', + specialist_id: 'old', + identificador: 'BMW-1', + }), + findFirst: jest.fn().mockResolvedValue(null), update: jest.fn().mockResolvedValue({}), }, process: { findFirst: jest.fn().mockResolvedValue(null) }, diff --git a/backend/src/features/products/product-transfer.ts b/backend/src/features/products/product-transfer.ts index e7a0033..7f6e0fb 100644 --- a/backend/src/features/products/product-transfer.ts +++ b/backend/src/features/products/product-transfer.ts @@ -79,20 +79,18 @@ export async function transferProductSpecialist( // O identificador é único por especialista, e o automático (`auto-…`) não // inclui o especialista: a mesma linha importada por dois deles gera o mesmo // id. Sem esta checagem o update cai no P2002 genérico. - if (product.identificador) { - const clash = await delegate.findFirst({ - where: { - specialist_id: input.toSpecialistId, - identificador: product.identificador, - }, - select: { id: true }, + const clash = await delegate.findFirst({ + where: { + specialist_id: input.toSpecialistId, + identificador: product.identificador, + }, + select: { id: true }, + }); + if (clash) { + throw new ConflictException({ + code: 'PRODUCT_IDENTIFIER_CONFLICT', + message: `O especialista de destino já tem um produto com o identificador "${product.identificador}". Altere o identificador de um dos produtos antes de transferir.`, }); - if (clash) { - throw new ConflictException({ - code: 'PRODUCT_IDENTIFIER_CONFLICT', - message: `O especialista de destino já tem um produto com o identificador "${product.identificador}". Altere o identificador de um dos produtos antes de transferir.`, - }); - } } await delegate.update({ diff --git a/backend/src/shared/dto/import-response.dto.ts b/backend/src/shared/dto/import-response.dto.ts index a8c8ed8..305deb4 100644 --- a/backend/src/shared/dto/import-response.dto.ts +++ b/backend/src/shared/dto/import-response.dto.ts @@ -42,6 +42,13 @@ export interface ImportResponseDto { deactivatedIds: string[]; /** Quantidade de produtos reativados (voltaram na planilha) */ reactivatedCount: number; + /** + * Produtos criados por linhas sem identificador. Mudar o preço numa dessas + * linhas e reimportar cria outro produto em vez de atualizar. + */ + autoIdentifierCreatedCount?: number; + /** Produtos desativados reativados por uma linha sem identificador idêntica. */ + autoIdentifierReactivatedCount?: number; } /** diff --git a/backend/src/shared/services/xlsx-import.service.ts b/backend/src/shared/services/xlsx-import.service.ts index 0964b4b..9dfabdd 100644 --- a/backend/src/shared/services/xlsx-import.service.ts +++ b/backend/src/shared/services/xlsx-import.service.ts @@ -53,7 +53,11 @@ export class XlsxImportService { * @param fileBuffer Buffer do arquivo XLSX * @returns Linhas parseadas + mapa de imagens por índice de linha (0-based, dados) */ - async parseWorkbook(fileBuffer: Buffer): Promise { + async parseWorkbook( + fileBuffer: Buffer, + options: { linkColumns?: string[] } = {}, + ): Promise { + const linkColumns = new Set(options.linkColumns ?? []); const workbook = new ExcelJS.Workbook(); try { await workbook.xlsx.load(fileBuffer as any); @@ -101,11 +105,15 @@ export class XlsxImportService { headers.forEach((header, colIndex) => { if (!header) return; - // O Excel transforma links (ex.: folder_url) em objetos hyperlink, que - // viravam "[object Object]" com String(). Num link com rótulo ("Fotos"), - // `text` é o rótulo; o dado é o destino, em `hyperlink`. + // `text` em vez de `value`: o Excel transforma links em objetos + // hyperlink, que viravam "[object Object]" com String(). Só nas + // colunas de link (ex.: folder_url) o dado é o destino, e não o rótulo + // exibido ("Fotos"); nas demais, um link num "modelo" não pode + // trocar o nome do produto pela URL. const cell = row.getCell(colIndex + 1); - const value = (cell.hyperlink ?? cell.text).trim(); + const value = ( + linkColumns.has(header) ? this.linkTarget(cell) : cell.text + ).trim(); if (value !== '') { hasData = true; @@ -176,6 +184,18 @@ export class XlsxImportService { return { rows, rowNumbers, imageMap }; } + /** + * Destino de uma célula de link: hyperlink inserido pelo Excel, fórmula + * =HYPERLINK("url"; "rótulo") ou, sem link, o texto digitado. + */ + private linkTarget(cell: ExcelJS.Cell): string { + if (cell.hyperlink) return cell.hyperlink; + const formulaUrl = cell.formula?.match( + /^\s*=?\s*HYPERLINK\(\s*"([^"]+)"/i, + )?.[1]; + return formulaUrl ?? cell.text; + } + /** * Parseia um arquivo CSV e extrai apenas dados tabulares. * Aceita delimitadores "," e ";" com suporte a valores entre aspas. @@ -535,7 +555,8 @@ export class XlsxImportService { for (const note of [ 'Preencha uma linha por produto na aba "Produtos" e importe este arquivo (.xlsx) ou salve como .csv.', 'Só valor e currency são obrigatórios. Colunas vazias recebem um valor padrão e podem ser completadas depois na edição do produto.', - 'Reimportar a mesma linha atualiza o produto existente em vez de criar outro.', + 'Com identificador preenchido, reimportar a linha atualiza o produto existente (inclusive preço e fotos) em vez de criar outro.', + 'Sem identificador, só a linha idêntica atualiza o mesmo produto: mudar qualquer dado, inclusive o valor, cria um produto novo e o anterior continua no catálogo. Uma linha idêntica à de um produto desativado o reativa.', ]) { instructions.addRow({ coluna: note }); instructions.mergeCells(`A${instructions.rowCount}:E${instructions.rowCount}`); diff --git a/frontend/src/components/shared/XlsxImporter.tsx b/frontend/src/components/shared/XlsxImporter.tsx index b7c7593..2ebbf67 100644 --- a/frontend/src/components/shared/XlsxImporter.tsx +++ b/frontend/src/components/shared/XlsxImporter.tsx @@ -23,6 +23,10 @@ export interface CsvImportResponse { deactivatedCount: number; deactivatedIds: number[]; reactivatedCount: number; + /** Criados por linhas sem identificador (preço novo nessas linhas cria outro produto). */ + autoIdentifierCreatedCount?: number; + /** Desativados reativados por linha sem identificador idêntica. */ + autoIdentifierReactivatedCount?: number; errorRows: CsvErrorRow[]; warningRows: CsvErrorRow[]; insertedIds?: number[]; @@ -599,6 +603,33 @@ export function XlsxImporter({ + {((importResult.autoIdentifierCreatedCount ?? 0) > 0 || + (importResult.autoIdentifierReactivatedCount ?? 0) > 0) && ( +
+ +
+ {(importResult.autoIdentifierCreatedCount ?? 0) > 0 && ( +

+ {importResult.autoIdentifierCreatedCount} produto(s) + criado(s) a partir de linhas sem identificador. Se + alguma dessas linhas era um produto já cadastrado com + outro dado (ex.: preço novo), o anúncio anterior + continua no catálogo. Para atualizar produtos depois, + preencha o identificador. +

+ )} + {(importResult.autoIdentifierReactivatedCount ?? 0) > 0 && ( +

+ {importResult.autoIdentifierReactivatedCount}{" "} + produto(s) desativado(s) foram reativados por uma linha + sem identificador idêntica. Confira se não é outra + unidade. +

+ )} +
+
+ )} + {importResult.deactivatedCount > 0 && (

Produtos ausentes na planilha foram removidos do catálogo diff --git a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx index e9893e4..f4bfe17 100644 --- a/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx +++ b/frontend/src/pages/admin/SpecialistJourneyProductsPage.tsx @@ -222,6 +222,15 @@ export default function SpecialistJourneyProductsPage() {

{preview.impact.incomingItems} linhas · {preview.impact.newOrReactivatedItems} criações/reativações · {preview.impact.matchingItems} atualizações · {preview.impact.deactivationCandidates} desativações

+ {((preview.impact.autoIdentifierNewItems ?? 0) > 0 || + (preview.impact.autoIdentifierReactivatedItems ?? 0) > 0) && ( +

+ Linhas sem identificador: {preview.impact.autoIdentifierNewItems ?? 0} vão criar produto novo + (um produto já cadastrado com preço ou outro dado alterado vira um segundo anúncio) e{" "} + {preview.impact.autoIdentifierReactivatedItems ?? 0} vão reativar um produto desativado. + Preencha o identificador para atualizar em vez de duplicar. +

+ )} {mode === "SYNCHRONIZE" && (