diff --git a/README.md b/README.md index 4bcf607d..98323273 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ Além do `DATABASE_URL`, o projeto depende de variáveis importantes para integr - `DOCUSIGN_INTEGRATION_KEY`, `DOCUSIGN_USER_ID`, `DOCUSIGN_ACCOUNT_ID`, `DOCUSIGN_PRIVATE_KEY`, `DOCUSIGN_ENV`, `DOCUSIGN_WEBHOOK_SECRET` - `GOOGLE_DRIVE_API_KEY` - `MEETING_PROVIDER`, `MEETING_DEMO_FALLBACK_ENABLED`, `JITSI_BASE_URL` -- Calendly OAuth (quando habilitado): `CALENDLY_OAUTH_CLIENT_ID`, `CALENDLY_OAUTH_CLIENT_SECRET`, `CALENDLY_OAUTH_REDIRECT_URI`, `CALENDLY_TOKEN_ENCRYPTION_KEY`, `CALENDLY_WEBHOOK_CALLBACK_URL`, `CALENDLY_WEBHOOK_SIGNING_KEY` +- Calendly OAuth (quando habilitado): `CALENDLY_OAUTH_CLIENT_ID`, `CALENDLY_OAUTH_CLIENT_SECRET`, `CALENDLY_OAUTH_REDIRECT_URI`, `CALENDLY_TOKEN_ENCRYPTION_KEY`; se `CALENDLY_WEBHOOK_CALLBACK_URL` for configurada, `CALENDLY_WEBHOOK_SIGNING_KEY` é obrigatória --- diff --git a/backend/.env.example b/backend/.env.example index 834d4379..8117bee3 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -52,6 +52,9 @@ BACKEND_URL=http://localhost:3000 # ===== CALENDLY INTEGRATION ===== # Token de acesso do Calendly para agendamentos (opcional) CALENDLY_ACCESS_TOKEN=your-calendly-access-token +# Se a URL de callback for configurada, a signing key também é obrigatória. +CALENDLY_WEBHOOK_CALLBACK_URL= +CALENDLY_WEBHOOK_SIGNING_KEY= # ===== GOOGLE DRIVE IMPORT ===== # Chave de API para listar/baixar imagens de pasta pública do Google Drive diff --git a/backend/README.md b/backend/README.md index 0fa72cf1..2a77adc0 100644 --- a/backend/README.md +++ b/backend/README.md @@ -75,8 +75,13 @@ cp .env.example .env - `CALENDLY_OAUTH_CLIENT_SECRET` - `CALENDLY_OAUTH_REDIRECT_URI` - `CALENDLY_TOKEN_ENCRYPTION_KEY` -- `CALENDLY_WEBHOOK_CALLBACK_URL` (recomendado) -- `CALENDLY_WEBHOOK_SIGNING_KEY` (recomendado) +- `CALENDLY_WEBHOOK_CALLBACK_URL` (opcional; habilita callbacks) +- `CALENDLY_WEBHOOK_SIGNING_KEY` (obrigatório quando `CALENDLY_WEBHOOK_CALLBACK_URL` estiver configurado) + +O backend não cria assinaturas de webhook sem `CALENDLY_WEBHOOK_SIGNING_KEY` e +rejeita callbacks quando a chave estiver ausente. A chave gerada pelo Calendly +na criação do aplicativo OAuth deve ser copiada para o backend. Ela valida os +callbacks localmente e não é reenviada no payload da subscription OAuth. > Observação: `CALENDLY_ACCESS_TOKEN` pode existir como fallback simples, mas o fluxo recomendado no projeto atual é OAuth por especialista. diff --git a/backend/package.json b/backend/package.json index f7aa54d2..a30abdfe 100644 --- a/backend/package.json +++ b/backend/package.json @@ -18,7 +18,8 @@ "test:cov": "jest --coverage", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", "test:e2e": "jest --config ./test/jest-e2e.json", - "seed": "ts-node prisma/seed.ts" + "seed": "ts-node prisma/seed.ts", + "seed:email-scheduling-e2e": "ts-node prisma/seed-email-scheduling-e2e.ts" }, "dependencies": { "@aws-sdk/client-s3": "^3.911.0", diff --git a/backend/prisma/migrations/20261023110500_add_delegated_action_audit/migration.sql b/backend/prisma/migrations/20261023110500_add_delegated_action_audit/migration.sql new file mode 100644 index 00000000..01f8c214 --- /dev/null +++ b/backend/prisma/migrations/20261023110500_add_delegated_action_audit/migration.sql @@ -0,0 +1,22 @@ +CREATE TABLE "DelegatedActionAudit" ( + "id" UUID NOT NULL DEFAULT gen_random_uuid(), + "actor_id" UUID NOT NULL, + "actor_role" "UserRole" NOT NULL, + "represented_specialist_id" UUID NOT NULL, + "action" VARCHAR(80) NOT NULL, + "resource_type" VARCHAR(80) NOT NULL, + "resource_id" VARCHAR(128) NOT NULL, + "metadata" JSONB, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "DelegatedActionAudit_pkey" PRIMARY KEY ("id") +); + +CREATE INDEX "DelegatedActionAudit_actor_id_created_at_idx" + ON "DelegatedActionAudit"("actor_id", "created_at"); +CREATE INDEX "DelegatedActionAudit_represented_specialist_id_created_at_idx" + ON "DelegatedActionAudit"("represented_specialist_id", "created_at"); +CREATE INDEX "DelegatedActionAudit_resource_type_resource_id_idx" + ON "DelegatedActionAudit"("resource_type", "resource_id"); +CREATE INDEX "DelegatedActionAudit_action_created_at_idx" + ON "DelegatedActionAudit"("action", "created_at"); diff --git a/backend/prisma/migrations/20261023111500_add_product_import_policy/migration.sql b/backend/prisma/migrations/20261023111500_add_product_import_policy/migration.sql new file mode 100644 index 00000000..b5bb4e03 --- /dev/null +++ b/backend/prisma/migrations/20261023111500_add_product_import_policy/migration.sql @@ -0,0 +1,11 @@ +ALTER TABLE "ProductImportJob" + ADD COLUMN "created_by_id" UUID, + ADD COLUMN "mode" VARCHAR(20) NOT NULL DEFAULT 'ADDITIVE', + ADD COLUMN "sync_confirmed" BOOLEAN NOT NULL DEFAULT false; + +CREATE INDEX "ProductImportJob_created_by_id_idx" + ON "ProductImportJob"("created_by_id"); + +ALTER TABLE "ProductImportJob" + ADD CONSTRAINT "ProductImportJob_mode_check" + CHECK ("mode" IN ('ADDITIVE', 'SYNCHRONIZE')); diff --git a/backend/prisma/migrations/20261023113000_enforce_single_pending_proposal/migration.sql b/backend/prisma/migrations/20261023113000_enforce_single_pending_proposal/migration.sql new file mode 100644 index 00000000..8e3c5a60 --- /dev/null +++ b/backend/prisma/migrations/20261023113000_enforce_single_pending_proposal/migration.sql @@ -0,0 +1,3 @@ +CREATE UNIQUE INDEX "NegotiationProposal_one_pending_per_process_idx" + ON "NegotiationProposal"("process_id") + WHERE "status" = 'PENDING'; diff --git a/backend/prisma/migrations/20261023114500_bind_product_sync_preview/migration.sql b/backend/prisma/migrations/20261023114500_bind_product_sync_preview/migration.sql new file mode 100644 index 00000000..a1f3b606 --- /dev/null +++ b/backend/prisma/migrations/20261023114500_bind_product_sync_preview/migration.sql @@ -0,0 +1,2 @@ +ALTER TABLE "ProductImportJob" + ADD COLUMN "sync_preview_snapshot" JSONB; diff --git a/backend/prisma/migrations/20261023120000_add_product_import_job_lease/migration.sql b/backend/prisma/migrations/20261023120000_add_product_import_job_lease/migration.sql new file mode 100644 index 00000000..9c30ae9d --- /dev/null +++ b/backend/prisma/migrations/20261023120000_add_product_import_job_lease/migration.sql @@ -0,0 +1,6 @@ +ALTER TABLE "ProductImportJob" +ADD COLUMN "processing_lease_token" UUID, +ADD COLUMN "processing_lease_expires_at" TIMESTAMP(3); + +CREATE INDEX "ProductImportJob_status_processing_lease_expires_at_idx" +ON "ProductImportJob"("status", "processing_lease_expires_at"); diff --git a/backend/prisma/migrations/20261025120000_add_process_removal/migration.sql b/backend/prisma/migrations/20261025120000_add_process_removal/migration.sql new file mode 100644 index 00000000..8ee1d8ff --- /dev/null +++ b/backend/prisma/migrations/20261025120000_add_process_removal/migration.sql @@ -0,0 +1,6 @@ +ALTER TABLE "Process" + ADD COLUMN "removed_at" TIMESTAMP(3), + ADD COLUMN "removed_by" UUID, + ADD COLUMN "removal_reason" VARCHAR(1000); + +CREATE INDEX "Process_removed_at_idx" ON "Process"("removed_at"); diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index a0a8bf3a..09f91643 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -867,6 +867,9 @@ model Process { negotiation_product_value Decimal? @db.Decimal(15, 2) created_at DateTime @default(now()) updated_at DateTime @updatedAt + removed_at DateTime? + removed_by String? @db.Uuid + removal_reason String? @db.VarChar(1000) car Car? @relation(fields: [car_id], references: [id]) boat Boat? @relation(fields: [boat_id], references: [id]) @@ -902,6 +905,7 @@ model Process { @@index([product_id]) @@index([created_at]) @@index([status, updated_at]) + @@index([removed_at]) } // MeetingSession: sessão de videoconferência criada na plataforma para um processo @@ -958,6 +962,26 @@ model ProcessRejection { @@index([rejected_at]) } +// Trilha aditiva de ações executadas por um ator em nome de um especialista. +// IDs são intencionalmente mantidos sem FK/onDelete para preservar a prova +// mesmo quando o recurso operacional for removido por regras legadas. +model DelegatedActionAudit { + id String @id @default(uuid()) @db.Uuid + actor_id String @db.Uuid + actor_role UserRole + represented_specialist_id String @db.Uuid + action String @db.VarChar(80) + resource_type String @db.VarChar(80) + resource_id String @db.VarChar(128) + metadata Json? + created_at DateTime @default(now()) + + @@index([actor_id, created_at]) + @@index([represented_specialist_id, created_at]) + @@index([resource_type, resource_id]) + @@index([action, created_at]) +} + // ───────────────────────────────────────────────────────────────────────────── // ▸ PROPOSTAS DE NEGOCIAÇÃO // ───────────────────────────────────────────────────────────────────────────── @@ -1318,6 +1342,10 @@ model ProductImportJob { id String @id @default(uuid()) @db.Uuid product_type ProductType specialist_id String @db.Uuid + created_by_id String? @db.Uuid + mode String @default("ADDITIVE") @db.VarChar(20) + sync_confirmed Boolean @default(false) + sync_preview_snapshot Json? status ProductImportJobStatus @default(PENDING) total_items Int @default(0) processed_items Int @default(0) @@ -1330,6 +1358,8 @@ model ProductImportJob { started_at DateTime? finished_at DateTime? error_message String? + processing_lease_token String? @db.Uuid + processing_lease_expires_at DateTime? created_at DateTime @default(now()) updated_at DateTime @updatedAt @@ -1337,7 +1367,9 @@ model ProductImportJob { items ProductImportJobItem[] @@index([specialist_id]) + @@index([created_by_id]) @@index([status]) + @@index([status, processing_lease_expires_at]) @@index([product_type]) @@index([created_at]) } diff --git a/backend/prisma/seed-email-scheduling-e2e.ts b/backend/prisma/seed-email-scheduling-e2e.ts new file mode 100644 index 00000000..5a5e4b12 --- /dev/null +++ b/backend/prisma/seed-email-scheduling-e2e.ts @@ -0,0 +1,397 @@ +/** + * Local-only fixtures for the no-Calendly scheduling gate. No .env fallback, + * truncation, user deletion or product deletion. Generated workflow IDs are + * resolved from an allowlist and validated before transactional cleanup. + */ +import type { Prisma, PrismaClient } from '@prisma/client'; +import * as bcrypt from 'bcrypt'; + +type Actor = 'customer' | 'specialist' | 'outsider'; +type Namespace = 'browser' | 'http'; + +export interface EmailSchedulingE2EConfig { + databaseUrl: string; + namespace: Namespace; + credentials: Record; +} + +export function emailSchedulingFixtures(namespace: Namespace) { + const prefix = + namespace === 'browser' + ? 'c848f474-6492-4ac1-8a7d' + : '8c26e2a3-fd13-447a-9b6c'; + const rgPrefix = namespace === 'browser' ? '990801' : '990802'; + const users = [ + { + actor: 'customer' as const, + id: `${prefix}-000000000001`, + name: 'E2E Cliente', + surname: `Email ${namespace}`, + rg: `${rgPrefix}00001`, + phone: '11987654321', + role: 'CUSTOMER' as const, + speciality: null, + }, + { + actor: 'specialist' as const, + id: `${prefix}-000000000002`, + name: 'E2E Especialista', + surname: `Email ${namespace}`, + rg: `${rgPrefix}00002`, + phone: '11976543210', + role: 'SPECIALIST' as const, + speciality: 'CAR' as const, + }, + { + actor: 'outsider' as const, + id: `${prefix}-000000000003`, + name: 'E2E Nao Atribuido', + surname: `Email ${namespace}`, + rg: `${rgPrefix}00003`, + phone: '21998765432', + role: 'SPECIALIST' as const, + speciality: 'CAR' as const, + }, + ]; + return { + namespace, + users, + cars: [ + { + id: `${prefix}-000000000101`, + specialist_id: users[1].id, + marca: 'E2E Email', + modelo: 'Produto A', + identificador: `email-scheduling-${namespace}-a`, + }, + { + id: `${prefix}-000000000102`, + specialist_id: users[1].id, + marca: 'E2E Email', + modelo: 'Produto B', + identificador: `email-scheduling-${namespace}-b`, + }, + ], + }; +} + +type Fixtures = ReturnType; + +export function readEmailSchedulingE2EConfig( + env: NodeJS.ProcessEnv, + namespace: Namespace = 'browser', +): EmailSchedulingE2EConfig { + const databaseUrl = env.EMAIL_SCHEDULING_E2E_DATABASE_URL?.trim(); + try { + const url = new URL(databaseUrl ?? ''); + if ( + !['postgresql:', 'postgres:'].includes(url.protocol) || + !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) || + !/(?:^|_)email_scheduling_e2e$/.test(url.pathname.slice(1)) + ) + throw new Error('invalid'); + } catch { + throw new Error( + 'EMAIL_SCHEDULING_E2E_DATABASE_URL must name a dedicated *_email_scheduling_e2e PostgreSQL database on loopback', + ); + } + + const credentials = {} as EmailSchedulingE2EConfig['credentials']; + const namespaceEmails: string[] = []; + for (const actor of ['customer', 'specialist', 'outsider'] as const) { + const emailKey = `EMAIL_SCHEDULING_E2E_${actor.toUpperCase()}_EMAIL`; + const passwordKey = `EMAIL_SCHEDULING_E2E_${actor.toUpperCase()}_PASSWORD`; + const email = env[emailKey]?.trim().toLowerCase(); + const password = env[passwordKey]; + if (!email || !/^[^\s@]+@[a-z0-9.-]+\.test$/.test(email)) { + throw new Error(`${emailKey} must be a reserved .test email address`); + } + if (!password || password.length < 6 || !password.trim()) { + throw new Error(`${passwordKey} must contain at least 6 characters`); + } + const [local, domain] = email.split('@'); + const httpEmail = `${local}+http@${domain}`; + namespaceEmails.push(email, httpEmail); + credentials[actor] = { + email: namespace === 'http' ? httpEmail : email, + password, + }; + } + if (new Set(namespaceEmails).size !== 6) { + throw new Error( + 'E2E emails must be distinct across browser and HTTP namespaces', + ); + } + return { databaseUrl: databaseUrl!, namespace, credentials }; +} + +async function assertBaseOwnership( + tx: Prisma.TransactionClient, + fixture: Fixtures, + config?: EmailSchedulingE2EConfig, +) { + for (const expected of fixture.users) { + const user = await tx.user.findUnique({ + where: { id: expected.id }, + select: { + name: true, + surname: true, + rg: true, + role: true, + email: true, + address_id: true, + consultant_id: true, + company_id: true, + calendly_url: true, + calendly_user_uri: true, + calendly_organization_uri: true, + calendly_connection: { select: { user_id: true } }, + }, + }); + if (!user) continue; + if ( + user.name !== expected.name || + user.surname !== expected.surname || + user.rg !== expected.rg || + user.role !== expected.role || + (config && user.email !== config.credentials[expected.actor].email) || + user.address_id || + user.consultant_id || + user.company_id || + user.calendly_url || + user.calendly_user_uri || + user.calendly_organization_uri || + user.calendly_connection + ) { + throw new Error( + 'Refusing to reset a fixture user with unexpected ownership or relationships', + ); + } + } + for (const expected of fixture.cars) { + const car = await tx.car.findUnique({ + where: { id: expected.id }, + select: { + identificador: true, + specialist_id: true, + marca: true, + modelo: true, + }, + }); + if ( + car && + (car.identificador !== expected.identificador || + car.specialist_id !== expected.specialist_id || + car.marca !== expected.marca || + car.modelo !== expected.modelo) + ) { + throw new Error( + 'Refusing to reset a fixture product with unexpected ownership', + ); + } + } +} + +async function cleanupInTransaction( + tx: Prisma.TransactionClient, + fixture: Fixtures, +) { + await assertBaseOwnership(tx, fixture); + const userIds = fixture.users.map(({ id }) => id); + const carIds = fixture.cars.map(({ id }) => id); + const appointments = await tx.appointment.findMany({ + where: { + OR: [ + { client_id: { in: userIds } }, + { specialist_id: { in: userIds } }, + { product_id: { in: carIds } }, + ], + }, + include: { process: { select: { id: true } } }, + }); + const appointmentIds = appointments.map(({ id }) => id); + const processes = await tx.process.findMany({ + where: { + OR: [ + { client_id: { in: userIds } }, + { specialist_id: { in: userIds } }, + { car_id: { in: carIds } }, + { product_id: { in: carIds } }, + { appointment_id: { in: appointmentIds } }, + ], + }, + include: { + appointment: { select: { id: true } }, + ProcessStatusHistory: true, + meeting_session: { select: { id: true } }, + _count: { + select: { + contracts: true, + proposals: true, + products: true, + rejections: true, + }, + }, + }, + }); + // All candidates are checked before the first delete. Unexpected cross-links + // abort the whole reset, even when only one side matches a deterministic ID. + for (const appointment of appointments) { + const process = processes.find(({ id }) => id === appointment.process?.id); + if ( + appointment.client_id !== fixture.users[0].id || + appointment.specialist_id !== fixture.users[1].id || + appointment.product_type !== 'CAR' || + !appointment.product_id || + !carIds.includes(appointment.product_id) || + appointment.scheduling_method !== 'EMAIL' || + !['PENDING', 'SCHEDULED'].includes(appointment.status) || + appointment.calendly_event_uri || + appointment.calendly_invitee_uri || + !process || + process.appointment_id !== appointment.id + ) { + throw new Error( + 'Refusing cleanup: unexpected appointment ownership, method or link', + ); + } + } + for (const process of processes) { + const appointment = appointments.find( + ({ id }) => id === process.appointment_id, + ); + if ( + process.client_id !== fixture.users[0].id || + process.specialist_id !== fixture.users[1].id || + process.product_type !== 'CAR' || + !process.car_id || + !carIds.includes(process.car_id) || + process.boat_id || + process.aircraft_id || + (process.product_id && process.product_id !== process.car_id) || + process.status !== 'SCHEDULING' || + !appointment || + appointment.product_id !== process.car_id || + process.meeting_session || + process.active_contract_id || + process.accepted_proposal_id || + Object.values(process._count).some((count) => count !== 0) || + process.ProcessStatusHistory.some( + (history) => + history.status !== 'SCHEDULING' || + history.reason !== null || + (history.changed_by !== null && + !userIds.includes(history.changed_by)), + ) + ) { + throw new Error( + 'Refusing cleanup: unexpected process ownership or downstream data', + ); + } + } + const processIds = processes.map(({ id }) => id); + await tx.processStatusHistory.deleteMany({ + where: { processId: { in: processIds } }, + }); + await tx.process.deleteMany({ where: { id: { in: processIds } } }); + await tx.appointment.deleteMany({ where: { id: { in: appointmentIds } } }); + await tx.refreshToken.deleteMany({ where: { user_id: { in: userIds } } }); +} + +export async function cleanupEmailSchedulingFixtures( + prisma: PrismaClient, + fixture: Fixtures, +) { + await prisma.$transaction((tx) => cleanupInTransaction(tx, fixture), { + isolationLevel: 'Serializable', + }); +} + +export async function seedEmailSchedulingFixtures( + prisma: PrismaClient, + config: EmailSchedulingE2EConfig, + fixture: Fixtures, +) { + if (config.namespace !== fixture.namespace) + throw new Error('Fixture namespace mismatch'); + const hashes: Record = { + customer: await bcrypt.hash(config.credentials.customer.password, 10), + specialist: await bcrypt.hash(config.credentials.specialist.password, 10), + outsider: await bcrypt.hash(config.credentials.outsider.password, 10), + }; + await prisma.$transaction( + async (tx) => { + await assertBaseOwnership(tx, fixture, config); + await cleanupInTransaction(tx, fixture); + for (const user of fixture.users) { + const { actor, ...fields } = user; + const data = { + ...fields, + email: config.credentials[actor].email, + password_hash: hashes[actor], + is_active: true, + deactivated_at: null, + deactivated_by: null, + calendly_url: null, + calendly_user_uri: null, + calendly_organization_uri: null, + }; + await tx.user.upsert({ + where: { id: user.id }, + create: data, + update: data, + }); + } + for (const [index, car] of fixture.cars.entries()) { + const data = { + ...car, + is_active: true, + deactivated_at: null, + valor: 100000 + index * 10000, + currency: 'BRL' as const, + estado: 'SP', + ano: 2026, + descricao: + 'Produto sintético para o fluxo de reunião por e-mail E2E.', + }; + await tx.car.upsert({ + where: { id: car.id }, + create: data, + update: data, + }); + } + }, + { timeout: 15_000, isolationLevel: 'Serializable' }, + ); +} + +async function main() { + // Validate before importing or constructing Prisma. Never echo the URL, + // credential values, Prisma error metadata or fixture contacts to logs. + const config = readEmailSchedulingE2EConfig(process.env); + const { PrismaClient } = await import('@prisma/client'); + const prisma = new PrismaClient({ + datasources: { db: { url: config.databaseUrl } }, + }); + try { + await seedEmailSchedulingFixtures( + prisma, + config, + emailSchedulingFixtures('browser'), + ); + console.log( + 'Email scheduling E2E fixtures ready: 3 users, 2 products (browser namespace).', + ); + } finally { + await prisma.$disconnect(); + } +} + +if (require.main === module) { + main().catch(() => { + console.error( + 'Email scheduling E2E seed failed. Check local database, required test variables and fixture ownership; no credentials logged.', + ); + process.exitCode = 1; + }); +} diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts index 2a270ee7..7e7f3aed 100644 --- a/backend/src/app.module.ts +++ b/backend/src/app.module.ts @@ -31,12 +31,14 @@ import { CustomerAdvisorsModule } from './features/customer-advisors/customer-ad import { OfficeModule } from './features/office/office.module'; import { CommissionsModule } from './features/commissions/commissions.module'; import { AdminDatabaseModule } from './features/admin-database/admin-database.module'; +import { ActorContextModule } from './shared/actor-context/actor-context.module'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, }), + ActorContextModule, HealthModule, ConsultantsModule, SpecialistsModule, diff --git a/backend/src/features/admin-database/admin-database.columns.ts b/backend/src/features/admin-database/admin-database.columns.ts index 7e9130be..3f3c2281 100644 --- a/backend/src/features/admin-database/admin-database.columns.ts +++ b/backend/src/features/admin-database/admin-database.columns.ts @@ -268,6 +268,7 @@ export const ENTITIES: Record = { select: { id: true, product_type: true, status: true, notes: true, active_contract_id: true, created_at: true, + removed_at: true, removed_by: true, removal_reason: true, client: { select: { name: true, surname: true } }, specialist: { select: { name: true, surname: true } }, car: { select: { marca: true, modelo: true } }, @@ -289,6 +290,9 @@ export const ENTITIES: Record = { { label: 'Contrato', get: (r) => r.active_contract_id != null, format: f.bool }, { label: 'Observações', get: (r) => r.notes, wide: true }, { label: 'Criado em', get: (r) => r.created_at, format: f.date }, + { label: 'Excluído em', get: (r) => r.removed_at, format: f.datetime }, + { label: 'Excluído por', get: (r) => r.removed_by }, + { label: 'Motivo da exclusão', get: (r) => r.removal_reason, wide: true }, ], }, contracts: { diff --git a/backend/src/features/admin-database/admin-database.controller.ts b/backend/src/features/admin-database/admin-database.controller.ts index 4f23c458..6c5c2a94 100644 --- a/backend/src/features/admin-database/admin-database.controller.ts +++ b/backend/src/features/admin-database/admin-database.controller.ts @@ -4,6 +4,7 @@ import { Delete, Get, Param, + ParseUUIDPipe, Patch, Post, Query, @@ -18,6 +19,8 @@ import { AdminUserManagementService } from './admin-user-management.service'; import { ChangeRoleDto } from './dto/change-role.dto'; import { ChangeSpecialityDto } from './dto/change-speciality.dto'; import { ChangeSpecialistDetailsDto } from './dto/change-specialist-details.dto'; +import { AdminProcessRemovalService } from './admin-process-removal.service'; +import { RemoveProcessDto } from './dto/remove-process.dto'; // Navegador read-only da base de dados — só ADMIN. @Controller('admin/database') @@ -25,6 +28,7 @@ export class AdminDatabaseController { constructor( private readonly service: AdminDatabaseService, private readonly management: AdminUserManagementService, + private readonly processRemoval: AdminProcessRemovalService, ) {} @Get('entities') @@ -57,6 +61,18 @@ export class AdminDatabaseController { } return this.management.deleteUser(id, actor.id); } + @Delete('processes/:id') + @Roles(UserRole.ADMIN) + deleteProcess( + @Param('id', new ParseUUIDPipe()) id: string, + @Body() dto: RemoveProcessDto, + @Req() req: { user?: UserEntity }, + ) { + if (!req.user) { + throw new UnauthorizedException('Usuário autenticado não identificado'); + } + return this.processRemoval.remove(id, req.user.id, dto.reason); + } @Post('users/:id/role-change/validate') @Roles(UserRole.ADMIN) diff --git a/backend/src/features/admin-database/admin-database.module.ts b/backend/src/features/admin-database/admin-database.module.ts index 9711ba50..32328f72 100644 --- a/backend/src/features/admin-database/admin-database.module.ts +++ b/backend/src/features/admin-database/admin-database.module.ts @@ -2,10 +2,15 @@ import { Module } from '@nestjs/common'; import { AdminDatabaseService } from './admin-database.service'; import { AdminDatabaseController } from './admin-database.controller'; import { AdminUserManagementService } from './admin-user-management.service'; +import { AdminProcessRemovalService } from './admin-process-removal.service'; @Module({ controllers: [AdminDatabaseController], - providers: [AdminDatabaseService, AdminUserManagementService], + providers: [ + AdminDatabaseService, + AdminUserManagementService, + AdminProcessRemovalService, + ], exports: [AdminDatabaseService], }) export class AdminDatabaseModule {} diff --git a/backend/src/features/admin-database/admin-database.service.ts b/backend/src/features/admin-database/admin-database.service.ts index dd39a4df..8986d29f 100644 --- a/backend/src/features/admin-database/admin-database.service.ts +++ b/backend/src/features/admin-database/admin-database.service.ts @@ -48,7 +48,7 @@ export class AdminDatabaseService { speciality: string | null; commission_rate: number | null; } - | { id: string } + | { id: string; removed_at?: string | null } )[]; total: number; page: number; @@ -96,7 +96,9 @@ export class AdminDatabaseService { commission_rate: row.commission_rate === null ? null : Number(row.commission_rate), } - : { id: row.id }, + : entity === 'processes' + ? { id: row.id, removed_at: row.removed_at?.toISOString() ?? null } + : { id: row.id }, ); return { columns, data, rowMeta, total, page: currentPage, pageSize: take }; diff --git a/backend/src/features/admin-database/admin-process-removal.service.spec.ts b/backend/src/features/admin-database/admin-process-removal.service.spec.ts new file mode 100644 index 00000000..7e184994 --- /dev/null +++ b/backend/src/features/admin-database/admin-process-removal.service.spec.ts @@ -0,0 +1,144 @@ +import { ConflictException } from '@nestjs/common'; +import { + AppointmentSchedulingMethod, + ProviderStatus, + StatusAgendamento, +} from '@prisma/client'; +import { AdminProcessRemovalService } from './admin-process-removal.service'; + +const processId = '11111111-1111-4111-8111-111111111111'; +const actorId = '22222222-2222-4222-8222-222222222222'; +const specialistId = '33333333-3333-4333-8333-333333333333'; +const clientId = '44444444-4444-4444-8444-444444444444'; +const appointmentId = '55555555-5555-4555-8555-555555555555'; +const changedAt = new Date('2026-10-25T12:00:00Z'); + +function fixture(overrides: Record = {}) { + return { + id: processId, + client_id: clientId, + specialist_id: specialistId, + removed_at: null, + updated_at: changedAt, + appointment_id: appointmentId, + appointment: { + id: appointmentId, + client_id: clientId, + specialist_id: specialistId, + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + calendly_event_uri: null, + calendly_invitee_uri: null, + updated_at: changedAt, + }, + meeting_session: null, + contracts: [], + ...overrides, + }; +} + +function harness(process = fixture()) { + const tx = { + $queryRaw: jest.fn().mockResolvedValue([]), + process: { + findUnique: jest.fn().mockResolvedValue(process), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + appointment: { updateMany: jest.fn().mockResolvedValue({ count: 1 }) }, + }; + const prisma = { + process: { + findUnique: jest.fn().mockResolvedValue({ specialist_id: specialistId }), + }, + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + return { service: new AdminProcessRemovalService(prisma), tx }; +} + +describe('AdminProcessRemovalService', () => { + it('preserva o processo e cancela o agendamento local na mesma transação', async () => { + const { service, tx } = harness(); + const result = await service.remove( + processId, + actorId, + ' pedido do cliente ', + ); + expect(result).toMatchObject({ id: processId, removed_by: actorId }); + expect(tx.process.updateMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ + id: processId, + removed_at: null, + updated_at: changedAt, + }), + data: expect.objectContaining({ + removed_by: actorId, + removal_reason: 'pedido do cliente', + }), + }), + ); + expect(tx.appointment.updateMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ + id: appointmentId, + updated_at: changedAt, + }), + data: expect.objectContaining({ status: StatusAgendamento.CANCELLED }), + }), + ); + }); + + it.each([ + ['reunião aberta', { meeting_session: { ended_at: null } }], + [ + 'envelope enviado', + { + contracts: [ + { provider_id: 'env-1', provider_status: ProviderStatus.SENT }, + ], + }, + ], + [ + 'Calendly marcado', + { + appointment: { + ...fixture().appointment, + status: StatusAgendamento.SCHEDULED, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + }, + }, + ], + ])('bloqueia %s antes de escrever', async (_case, overrides) => { + const { service, tx } = harness(fixture(overrides)); + await expect( + service.remove(processId, actorId, 'motivo'), + ).rejects.toBeInstanceOf(ConflictException); + expect(tx.process.updateMany).not.toHaveBeenCalled(); + expect(tx.appointment.updateMany).not.toHaveBeenCalled(); + }); + + it('permite remover processo com contrato já assinado sem apagar o contrato', async () => { + const { service, tx } = harness( + fixture({ + appointment_id: null, + appointment: null, + contracts: [ + { provider_id: 'env-1', provider_status: ProviderStatus.COMPLETED }, + ], + }), + ); + await expect( + service.remove(processId, actorId, 'encerramento'), + ).resolves.toMatchObject({ id: processId }); + expect(tx.appointment.updateMany).not.toHaveBeenCalled(); + expect(tx.process.updateMany).toHaveBeenCalledTimes(1); + }); + + it('não permite excluir duas vezes', async () => { + const { service, tx } = harness(fixture({ removed_at: changedAt })); + await expect( + service.remove(processId, actorId, 'motivo'), + ).rejects.toBeInstanceOf(ConflictException); + expect(tx.process.updateMany).not.toHaveBeenCalled(); + }); +}); diff --git a/backend/src/features/admin-database/admin-process-removal.service.ts b/backend/src/features/admin-database/admin-process-removal.service.ts new file mode 100644 index 00000000..b6bdc3ff --- /dev/null +++ b/backend/src/features/admin-database/admin-process-removal.service.ts @@ -0,0 +1,184 @@ +import { + BadRequestException, + ConflictException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { + AppointmentSchedulingMethod, + Prisma, + ProviderStatus, + StatusAgendamento, +} from '@prisma/client'; +import { PrismaService } from 'src/prisma/prisma.service'; +import { acquireSpecialistScheduleLock } from '../appointments/appointment-schedule-lock'; +import { isStaleMeetingInitializationClaim } from '../meetings/meeting-initialization-claim'; + +const TERMINAL_ENVELOPES = new Set([ + ProviderStatus.COMPLETED, + ProviderStatus.DECLINED, + ProviderStatus.VOIDED, + ProviderStatus.TIMEDOUT, + ProviderStatus.ERROR, +]); + +@Injectable() +export class AdminProcessRemovalService { + constructor(private readonly prisma: PrismaService) {} + + async remove(processId: string, actorId: string, reason: string) { + const normalizedReason = reason?.trim(); + if (!normalizedReason) { + throw new BadRequestException('Informe o motivo da exclusão.'); + } + + const candidate = await this.prisma.process.findUnique({ + where: { id: processId }, + select: { specialist_id: true }, + }); + if (!candidate) throw new NotFoundException('Processo não encontrado.'); + + return this.prisma.$transaction( + async (tx) => { + // A ordem de locks acompanha as transições de agendamento: agenda, + // depois processo. O contrato e as propostas têm locks próprios. + await acquireSpecialistScheduleLock(tx, candidate.specialist_id); + for (const key of [ + `contract-process:${processId}`, + `proposal-process:${processId}`, + ]) { + await tx.$queryRaw` + SELECT pg_advisory_xact_lock(hashtextextended(${key}, 0))::text AS locked + `; + } + + const process = await tx.process.findUnique({ + where: { id: processId }, + include: { + appointment: true, + meeting_session: true, + contracts: { + select: { provider_id: true, provider_status: true }, + }, + }, + }); + if (!process) throw new NotFoundException('Processo não encontrado.'); + if (process.removed_at) { + throw new ConflictException('Este processo já foi excluído.'); + } + if (process.specialist_id !== candidate.specialist_id) { + throw new ConflictException( + 'O especialista do processo mudou. Recarregue a página.', + ); + } + if ( + Boolean(process.appointment) !== Boolean(process.appointment_id) || + (process.appointment && + (process.appointment.id !== process.appointment_id || + process.appointment.client_id !== process.client_id || + process.appointment.specialist_id !== process.specialist_id)) + ) { + throw new ConflictException( + 'Agendamento não corresponde aos participantes do processo.', + ); + } + if (process.meeting_session && !process.meeting_session.ended_at) { + if (isStaleMeetingInitializationClaim(process.meeting_session)) { + const cleanup = await tx.meetingSession.deleteMany({ + where: { + id: process.meeting_session.id, + calendar_event_id: process.meeting_session.calendar_event_id, + }, + }); + if (cleanup.count !== 1) { + throw new ConflictException( + 'A inicialização da reunião mudou. Recarregue a página.', + ); + } + } else { + throw new ConflictException( + 'Encerre a reunião antes de excluir o processo.', + ); + } + } + if ( + process.contracts.some( + (contract) => + contract.provider_id && + !TERMINAL_ENVELOPES.has( + contract.provider_status as ProviderStatus, + ), + ) + ) { + throw new ConflictException( + 'O contrato possui um envelope DocuSign ativo. Anule e reconcilie o envelope antes de excluir o processo.', + ); + } + + const appointment = process.appointment; + const hasOpenAppointment = + appointment?.status === StatusAgendamento.PENDING || + appointment?.status === StatusAgendamento.SCHEDULED; + if ( + hasOpenAppointment && + (appointment?.calendly_event_uri || + appointment?.calendly_invitee_uri || + (appointment?.scheduling_method === + AppointmentSchedulingMethod.CALENDLY && + appointment.status === StatusAgendamento.SCHEDULED)) + ) { + throw new ConflictException( + 'Cancele o evento no Calendly e aguarde a sincronização antes de excluir o processo.', + ); + } + + const removedAt = new Date(); + const claim = await tx.process.updateMany({ + where: { + id: processId, + removed_at: null, + updated_at: process.updated_at, + }, + data: { + removed_at: removedAt, + removed_by: actorId, + removal_reason: normalizedReason, + updated_at: removedAt, + }, + }); + if (claim.count !== 1) { + throw new ConflictException( + 'O processo mudou. Recarregue a página e tente novamente.', + ); + } + if (hasOpenAppointment && appointment) { + const cancellation = await tx.appointment.updateMany({ + where: { + id: appointment.id, + status: { + in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], + }, + updated_at: appointment.updated_at, + }, + data: { + status: StatusAgendamento.CANCELLED, + pending_expires_at: null, + }, + }); + if (cancellation.count !== 1) { + throw new ConflictException( + 'O agendamento mudou. Recarregue a página e tente novamente.', + ); + } + } + + return { id: processId, removed_at: removedAt, removed_by: actorId }; + }, + { + isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted, + maxWait: 10_000, + timeout: 120_000, + }, + ); + } +} diff --git a/backend/src/features/admin-database/dto/remove-process.dto.ts b/backend/src/features/admin-database/dto/remove-process.dto.ts new file mode 100644 index 00000000..402fe955 --- /dev/null +++ b/backend/src/features/admin-database/dto/remove-process.dto.ts @@ -0,0 +1,8 @@ +import { IsNotEmpty, IsString, MaxLength } from 'class-validator'; + +export class RemoveProcessDto { + @IsString() + @IsNotEmpty({ message: 'Informe o motivo da exclusão.' }) + @MaxLength(1000, { message: 'O motivo deve ter no máximo 1000 caracteres.' }) + reason: string; +} diff --git a/backend/src/features/aircrafts/aircrafts.controller.spec.ts b/backend/src/features/aircrafts/aircrafts.controller.spec.ts index 3dfb6135..e825f560 100644 --- a/backend/src/features/aircrafts/aircrafts.controller.spec.ts +++ b/backend/src/features/aircrafts/aircrafts.controller.spec.ts @@ -4,15 +4,47 @@ import { AircraftsController } from './aircrafts.controller'; function mkController() { const aircraftsService = { create: jest.fn().mockResolvedValue({ id: 'aircraft-1' }), + findOne: jest.fn().mockResolvedValue({ + id: 'aircraft-1', + specialist_id: 'spec-1', + }), + update: jest.fn().mockResolvedValue({ id: 'aircraft-1' }), + prepareProductImages: jest.fn().mockResolvedValue([]), + cleanupPreparedImages: jest.fn().mockResolvedValue(undefined), } as any; const productImportJobsService = { createJobFromCsv: jest.fn().mockResolvedValue({ id: 'job-1' }), } as any; - const controller = new AircraftsController( + const actorContext = { + resolve: jest.fn().mockImplementation(async (user, target) => ({ + actorId: user.id, + actorRole: user.role, + specialistId: target ?? user.id, + delegated: user.role === 'ADMIN', + specialist: {}, + })), + assertResourceSpecialist: jest.fn(), + } as any; + const audit = { record: jest.fn().mockResolvedValue(undefined) } as any; + const tx = { name: 'tx' } as any; + const prisma = { + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const controller = new (AircraftsController as any)( aircraftsService, productImportJobsService, + actorContext, + audit, + prisma, ); - return { controller, aircraftsService, productImportJobsService }; + return { + controller, + aircraftsService, + productImportJobsService, + audit, + prisma, + tx, + }; } const specialist = { @@ -23,14 +55,108 @@ const specialist = { describe('AircraftsController — Calendly opcional', () => { it('permite criação manual sem consultar Calendly', async () => { - const { controller, aircraftsService } = mkController(); + const { controller, aircraftsService, tx } = mkController(); const dto = {} as any; await expect(controller.create(dto, specialist)).resolves.toEqual({ id: 'aircraft-1', }); expect(dto.specialist_id).toBe(specialist.id); - expect(aircraftsService.create).toHaveBeenCalledWith(dto); + expect(aircraftsService.create).toHaveBeenCalledWith( + dto, + tx, + expect.objectContaining({ productId: expect.any(String), images: [] }), + ); + }); + + it('não permite remover o owner no PATCH comum', async () => { + const { controller, aircraftsService } = mkController(); + + await expect( + controller.update( + 'aircraft-1', + { specialist_id: null } as any, + specialist, + ), + ).rejects.toMatchObject({ status: 400 }); + expect(aircraftsService.update).not.toHaveBeenCalled(); + }); + + it('executa criação manual e auditoria na mesma transação', async () => { + const { controller, aircraftsService, audit, prisma, tx } = mkController(); + audit.record.mockRejectedValueOnce(new Error('audit unavailable')); + + await expect(controller.create({} as any, specialist)).rejects.toThrow( + 'audit unavailable', + ); + + expect(prisma.$transaction).toHaveBeenCalledTimes(1); + expect(aircraftsService.create).toHaveBeenCalledWith( + expect.objectContaining({ specialist_id: specialist.id }), + tx, + expect.objectContaining({ productId: expect.any(String), images: [] }), + ); + expect(audit.record).toHaveBeenCalledWith(expect.any(Object), tx); + }); + + it('aguarda upload fora da transação e compensa se a auditoria falhar', async () => { + const { controller, aircraftsService, audit, prisma } = mkController(); + const prepared = [ + { image_url: 'aircrafts/new-key.jpg', is_primary: true }, + ]; + let finishUpload!: (images: typeof prepared) => void; + aircraftsService.prepareProductImages.mockReturnValueOnce( + new Promise((resolve) => { + finishUpload = resolve; + }), + ); + audit.record.mockRejectedValueOnce(new Error('audit unavailable')); + + const operation = controller.create( + { images: [{ data: 'base64', is_primary: true }] } as any, + specialist, + ); + const rejection = expect(operation).rejects.toThrow('audit unavailable'); + await Promise.resolve(); + + expect(aircraftsService.prepareProductImages).toHaveBeenCalledTimes(1); + expect(prisma.$transaction).not.toHaveBeenCalled(); + finishUpload(prepared); + await rejection; + expect(aircraftsService.cleanupPreparedImages).toHaveBeenCalledWith( + prepared, + ); + }); + + it('também prepara PATCH fora da transação e compensa falha de auditoria', async () => { + const { controller, aircraftsService, audit, prisma } = mkController(); + const prepared = [ + { image_url: 'aircrafts/patch-key.jpg', is_primary: true }, + ]; + let finishUpload!: (images: typeof prepared) => void; + aircraftsService.prepareProductImages.mockReturnValueOnce( + new Promise((resolve) => { + finishUpload = resolve; + }), + ); + audit.record.mockRejectedValueOnce(new Error('audit unavailable')); + + const operation = controller.update( + 'aircraft-1', + { images: [{ data: 'base64', is_primary: true }] } as any, + specialist, + ); + const rejection = expect(operation).rejects.toThrow('audit unavailable'); + await Promise.resolve(); + await Promise.resolve(); + + expect(aircraftsService.prepareProductImages).toHaveBeenCalledTimes(1); + expect(prisma.$transaction).not.toHaveBeenCalled(); + finishUpload(prepared); + await rejection; + expect(aircraftsService.cleanupPreparedImages).toHaveBeenCalledWith( + prepared, + ); }); it('permite importação CSV sem consultar Calendly', async () => { @@ -48,6 +174,11 @@ describe('AircraftsController — Calendly opcional', () => { file.buffer, specialist, ProductType.AIRCRAFT, + expect.objectContaining({ + mode: 'ADDITIVE', + confirmSynchronize: false, + context: expect.objectContaining({ specialistId: specialist.id }), + }), ); }); }); diff --git a/backend/src/features/aircrafts/aircrafts.controller.ts b/backend/src/features/aircrafts/aircrafts.controller.ts index ab931987..446bd779 100644 --- a/backend/src/features/aircrafts/aircrafts.controller.ts +++ b/backend/src/features/aircrafts/aircrafts.controller.ts @@ -27,27 +27,92 @@ import { UserEntity } from 'src/auth/entities/user.entity'; import { assertSpecialistCanCreate, assertSpecialistCanModify, + assertNoProductOwnerMutation, assertSpecialistOwnsProduct, } from 'src/shared/helpers/specialist-auth.helper'; import { Public } from 'src/shared/decorators/public.decorator'; import { ProductImportJobsService } from '../product-import-jobs/product-import-jobs.service'; +import { ActorContextService } from 'src/shared/actor-context/actor-context.service'; +import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service'; +import { ProductCsvImportDto } from '../product-import-jobs/dto/product-csv-import.dto'; +import { PrismaService } from 'src/prisma/prisma.service'; +import { randomUUID } from 'node:crypto'; @Controller('aircrafts') export class AircraftsController { constructor( private readonly aircraftsService: AircraftsService, private readonly productImportJobsService: ProductImportJobsService, + private readonly actorContextService: ActorContextService, + private readonly delegatedAudit: DelegatedActionAuditService, + private readonly prisma: PrismaService, ) {} @Post() @Roles(UserRole.ADMIN, UserRole.SPECIALIST) - create( + async create( @Body() createAircraftDto: CreateAircraftDto, @CurrentUser() user: UserEntity, ) { - assertSpecialistCanCreate('AIRCRAFT', user); - createAircraftDto.specialist_id = user.id; - return this.aircraftsService.create(createAircraftDto); + const context = await this.actorContextService.resolve( + user, + createAircraftDto.specialist_id, + ProductType.AIRCRAFT, + ); + createAircraftDto.specialist_id = context.specialistId; + const productId = randomUUID(); + const preparedImages = await this.aircraftsService.prepareProductImages( + productId, + createAircraftDto.images, + ); + try { + return await this.prisma.$transaction(async (tx) => { + const aircraft = await this.aircraftsService.create( + createAircraftDto, + tx, + { productId, images: preparedImages }, + ); + await this.delegatedAudit.record( + { + context, + action: 'PRODUCT_CREATE', + resourceType: 'AIRCRAFT', + resourceId: aircraft.id, + }, + tx, + ); + return aircraft; + }); + } catch (error) { + await this.aircraftsService.cleanupPreparedImages(preparedImages); + throw error; + } + } + + @Post('import-csv/preview') + @Roles(UserRole.ADMIN, UserRole.SPECIALIST) + @UseInterceptors( + FileInterceptor('file', { limits: { fileSize: 50 * 1024 * 1024 } }), + ) + async previewCsvImport( + @UploadedFile() file: Express.Multer.File, + @CurrentUser() user: UserEntity, + @Body() options: ProductCsvImportDto = new ProductCsvImportDto(), + ) { + const context = await this.actorContextService.resolve( + user, + options.specialist_id, + ProductType.AIRCRAFT, + ); + if (!file?.originalname?.toLowerCase().endsWith('.csv')) { + throw new BadRequestException('Arquivo CSV é obrigatório.'); + } + return this.productImportJobsService.previewCsvImport( + file.buffer, + ProductType.AIRCRAFT, + context.specialistId, + options.mode, + ); } @Post('import-csv') @@ -58,8 +123,13 @@ export class AircraftsController { async importCsv( @UploadedFile() file: Express.Multer.File, @CurrentUser() user: UserEntity, + @Body() options: ProductCsvImportDto = new ProductCsvImportDto(), ) { - assertSpecialistCanCreate('AIRCRAFT', user); + const context = await this.actorContextService.resolve( + user, + options.specialist_id, + ProductType.AIRCRAFT, + ); if (!file) { throw new BadRequestException('Arquivo CSV é obrigatório.'); @@ -78,6 +148,12 @@ export class AircraftsController { file.buffer, user, ProductType.AIRCRAFT, + { + context, + mode: options.mode, + confirmSynchronize: options.confirm_synchronize, + synchronizePreviewToken: options.synchronize_preview_token, + }, ); } @@ -138,6 +214,45 @@ export class AircraftsController { }; } + @Get('admin/all') + @Roles(UserRole.ADMIN) + async getAllAircraftsForAdmin( + @Query() query: any, + @CurrentUser() user: UserEntity, + ) { + let { page, perPage, target_specialist_id, ...rawFilters } = query; + page = Number(page) || 1; + perPage = Number(perPage) || 20; + const context = await this.actorContextService.resolve( + user, + target_specialist_id, + ProductType.AIRCRAFT, + ); + rawFilters.specialist_id = context.specialistId; + const { data, count, filters = {} } = + await this.aircraftsService.getAllAircrafts( + { page, perPage, appliedFilters: rawFilters }, + true, + ); + const skip = (page - 1) * perPage; + return { + success: true, + message: 'Catálogo administrativo de aeronaves listado com sucesso', + data, + meta: { + pagination: { + current_page: page, + total_pages: Math.ceil(count / perPage), + has_next: skip + perPage < count, + has_prev: skip > 0, + total: count, + per_page: perPage, + }, + filters: { applied_filters: filters, total_without_filters: count }, + }, + }; + } + @Get(':id') @Public() findOne(@Param('id') id: string) { @@ -150,19 +265,77 @@ export class AircraftsController { @Param('id') id: string, @Body() updateAircraftDto: UpdateAircraftDto, @CurrentUser() user: UserEntity, + @Query('target_specialist_id') targetSpecialistId?: string, ) { - assertSpecialistCanModify('AIRCRAFT', user); + assertNoProductOwnerMutation(updateAircraftDto as Record); + const context = await this.actorContextService.resolve( + user, + targetSpecialistId, + ProductType.AIRCRAFT, + ); const existing = await this.aircraftsService.findOne(id); - assertSpecialistOwnsProduct(user, existing?.specialist_id); - return this.aircraftsService.update(id, updateAircraftDto); + this.actorContextService.assertResourceSpecialist( + context, + existing?.specialist_id, + ); + const preparedImages = await this.aircraftsService.prepareProductImages( + id, + updateAircraftDto.images, + ); + try { + return await this.prisma.$transaction(async (tx) => { + const aircraft = await this.aircraftsService.update( + id, + updateAircraftDto, + tx, + { images: preparedImages }, + ); + await this.delegatedAudit.record( + { + context, + action: 'PRODUCT_UPDATE', + resourceType: 'AIRCRAFT', + resourceId: id, + }, + tx, + ); + return aircraft; + }); + } catch (error) { + await this.aircraftsService.cleanupPreparedImages(preparedImages); + throw error; + } } @Delete(':id') @Roles(UserRole.ADMIN, UserRole.SPECIALIST) - async remove(@Param('id') id: string, @CurrentUser() user: UserEntity) { - assertSpecialistCanModify('AIRCRAFT', user); + async remove( + @Param('id') id: string, + @CurrentUser() user: UserEntity, + @Query('target_specialist_id') targetSpecialistId?: string, + ) { + const context = await this.actorContextService.resolve( + user, + targetSpecialistId, + ProductType.AIRCRAFT, + ); const existing = await this.aircraftsService.findOne(id); - assertSpecialistOwnsProduct(user, existing?.specialist_id); - return this.aircraftsService.remove(id); + this.actorContextService.assertResourceSpecialist( + context, + existing?.specialist_id, + ); + return this.prisma.$transaction(async (tx) => { + const result = await this.aircraftsService.remove(id, tx); + await this.delegatedAudit.record( + { + context, + action: 'PRODUCT_DEACTIVATE', + resourceType: 'AIRCRAFT', + resourceId: id, + }, + tx, + ); + return result; + }); } } diff --git a/backend/src/features/aircrafts/aircrafts.service.ts b/backend/src/features/aircrafts/aircrafts.service.ts index 21319049..3c73d5ba 100644 --- a/backend/src/features/aircrafts/aircrafts.service.ts +++ b/backend/src/features/aircrafts/aircrafts.service.ts @@ -1,4 +1,9 @@ -import { Injectable, NotFoundException, Logger } from '@nestjs/common'; +import { + HttpException, + Injectable, + NotFoundException, + Logger, +} from '@nestjs/common'; import { CreateAircraftDto } from './dto/create-aircraft.dto'; import { UpdateAircraftDto } from './dto/update-aircraft.dto'; import { PrismaService } from 'src/prisma/prisma.service'; @@ -11,10 +16,16 @@ import { RangeAircraftFilters, } from 'src/shared/dto/filters.dto'; import { Prisma, ProductType } from '@prisma/client'; -import { Aircraft } from './entity/aircraft.entity'; -import { UserEntity } from 'src/auth/entities/user.entity'; import { AIRCRAFT_COLUMNS } from 'src/shared/constants/product-columns'; import { updateProductWithMonetaryLock } from '../products/product-monetary-lock'; +import { publicAircraftSelect } from 'src/shared/selects/public-catalog.select'; +import { randomUUID } from 'node:crypto'; +import { + cleanupPreparedProductImages, + prepareProductImages, + PreparedProductImage, + ProductImageInput, +} from '../products/product-image-preparation'; @Injectable() export class AircraftsService { @@ -28,9 +39,34 @@ export class AircraftsService { private s3Service: S3Service, ) {} - async create(createAircraftDto: CreateAircraftDto) { + prepareProductImages(productId: string, images?: ProductImageInput[]) { + return prepareProductImages( + this.s3Service, + 'aircrafts', + productId, + images, + ); + } + + cleanupPreparedImages(images: PreparedProductImage[]) { + return cleanupPreparedProductImages(this.s3Service, images); + } + + async create( + createAircraftDto: CreateAircraftDto, + client: PrismaService | Prisma.TransactionClient = this.prismaService, + preparedWrite?: { + productId: string; + images: PreparedProductImage[]; + }, + ) { this.logger.log('[create] Iniciando criação de nova aeronave'); const { specialist_id, images, ...aircraftData } = createAircraftDto; + const productId = preparedWrite?.productId ?? randomUUID(); + const ownsPreparedImages = !preparedWrite; + const preparedImages = + preparedWrite?.images ?? + (await this.prepareProductImages(productId, images)); const payload: Prisma.AircraftUncheckedCreateInput = { categoria: aircraftData.categoria, @@ -45,6 +81,7 @@ export class AircraftsService { currency: aircraftData.currency, tipo_aeronave: aircraftData.tipo_aeronave, specialist_id: specialist_id ?? null, + id: productId, }; try { @@ -52,49 +89,35 @@ export class AircraftsService { this.logger.debug( `[create] Criando aeronave: ${aircraftData.marca} ${aircraftData.modelo}`, ); - const aircraft = await this.prismaService.aircraft.create({ + const aircraft = await client.aircraft.create({ data: payload, }); this.logger.log( `[create] Aeronave criada com sucesso - ID: ${aircraft.id}`, ); - // 2. Processar e fazer upload das imagens, se existirem - if (images && images.length > 0) { + // 2. Persistir somente referências já preparadas fora da transação + if (preparedImages.length > 0) { this.logger.log( - `[create] Processando ${images.length} imagens para a aeronave ${aircraft.id}`, + `[create] Persistindo ${preparedImages.length} imagens para a aeronave ${aircraft.id}`, ); - for (let i = 0; i < images.length; i++) { - const image = images[i]; - - const timestamp = Date.now(); - const key = `aircrafts/${aircraft.id}/${timestamp}-${i}.jpg`; - - this.logger.debug( - `[create] Fazendo upload da imagem ${i + 1}/${images.length} para S3`, - ); - const imageKey = await this.s3Service.uploadBase64Image( - image.data, - key, - ); - - await this.prismaService.aircraft_image.create({ + for (const image of preparedImages) { + await client.aircraft_image.create({ data: { aircraft_id: aircraft.id, - image_url: imageKey, + image_url: image.image_url, is_primary: image.is_primary, product_type: 'AIRCRAFT', }, }); - this.logger.debug(`[create] Imagem ${i + 1} salva com sucesso`); } this.logger.log( - `[create] Todas as ${images.length} imagens processadas com sucesso`, + `[create] Todas as ${preparedImages.length} imagens persistidas com sucesso`, ); } // 3. Retornar a aeronave com as imagens - const aircraftWithImages = await this.prismaService.aircraft.findUnique({ + const aircraftWithImages = await client.aircraft.findUnique({ where: { id: aircraft.id }, include: { images: true }, }); @@ -106,7 +129,13 @@ export class AircraftsService { ); return aircraftWithImages; } catch (error) { - if (error instanceof Prisma.PrismaClientKnownRequestError) { + if (ownsPreparedImages) { + await this.cleanupPreparedImages(preparedImages); + } + if ( + error instanceof HttpException || + error instanceof Prisma.PrismaClientKnownRequestError + ) { throw error; } this.logger.error( @@ -126,14 +155,14 @@ export class AircraftsService { page, perPage, appliedFilters, - }: QueryDto) { + }: QueryDto, includeInactive = false) { // Cálculo das variáveis que serão utilizadas const take = perPage; const skip = page && take ? (page - 1) * take : 0; // Separação dos filtros const where: any = {}; - where.is_active = true; + if (!includeInactive) where.is_active = true; // Exact const exacts: ExactAircraftFilters = { @@ -195,16 +224,13 @@ export class AircraftsService { skip: skip, take: take, where: where, - include: { - images: true, - specialist: true, - }, + select: publicAircraftSelect, }), this.prismaService.aircraft.count({ where }), ]); // Converter as keys do S3 em URLs assinadas para cada aeronave - const aircraftsEntities: Aircraft[] = await Promise.all( + const aircraftsEntities = await Promise.all( aircrafts.map(async (aircraft) => { let imagesWithUrls: any[] = []; if (aircraft.images && aircraft.images.length > 0) { @@ -220,9 +246,7 @@ export class AircraftsService { ...aircraft, valor: aircraft.valor.toNumber(), images: imagesWithUrls, - specialist: aircraft.specialist - ? UserEntity.fromPrisma(aircraft.specialist) - : null, + specialist: aircraft.specialist, }; }), ); @@ -238,7 +262,7 @@ export class AircraftsService { this.logger.log(`[findOne] Buscando aeronave - ID: ${id}`); const aircraft = await this.prismaService.aircraft.findUnique({ where: { id }, - include: { images: true }, + select: publicAircraftSelect, }); if (!aircraft) { this.logger.warn(`[findOne] Aeronave não encontrada - ID: ${id}`); @@ -264,8 +288,16 @@ export class AircraftsService { // return `This action updates a #${id} aircraft`; // } - async update(id: string, updateAircraftDto: UpdateAircraftDto) { + async update( + id: string, + updateAircraftDto: UpdateAircraftDto, + client: PrismaService | Prisma.TransactionClient = this.prismaService, + preparedWrite?: { images: PreparedProductImage[] }, + ) { const { specialist_id, images, ...aircraftData } = updateAircraftDto; + const ownsPreparedImages = !preparedWrite; + const preparedImages = + preparedWrite?.images ?? (await this.prepareProductImages(id, images)); const payload: Prisma.AircraftUncheckedUpdateInput = {}; if (aircraftData.categoria !== undefined) { @@ -305,39 +337,29 @@ export class AircraftsService { payload.specialist_id = specialist_id ?? null; } - await updateProductWithMonetaryLock(this.prismaService, { - productType: ProductType.AIRCRAFT, - productId: id, - nextValue: updateAircraftDto.valor, - nextCurrency: updateAircraftDto.currency, - data: payload, - notFoundMessage: 'Aircraft not found', - }); - try { + await updateProductWithMonetaryLock(client, { + productType: ProductType.AIRCRAFT, + productId: id, + nextValue: updateAircraftDto.valor, + nextCurrency: updateAircraftDto.currency, + data: payload, + notFoundMessage: 'Aircraft not found', + }); + // 1. Se houver novas imagens, processar if (images && images.length > 0) { // Remover imagens antigas - await this.prismaService.aircraft_image.deleteMany({ + await client.aircraft_image.deleteMany({ where: { aircraft_id: id }, }); - // Adicionar novas imagens - for (let i = 0; i < images.length; i++) { - const image = images[i]; - - const timestamp = Date.now(); - const key = `aircrafts/${id}/${timestamp}-${i}.jpg`; - - const imageKey = await this.s3Service.uploadBase64Image( - image.data, - key, - ); - - await this.prismaService.aircraft_image.create({ + // Adicionar referências das imagens já preparadas + for (const image of preparedImages) { + await client.aircraft_image.create({ data: { aircraft_id: id, - image_url: imageKey, + image_url: image.image_url, is_primary: image.is_primary, product_type: 'AIRCRAFT', }, @@ -346,21 +368,30 @@ export class AircraftsService { } // 3. Retornar a aeronave atualizada com imagens - return await this.prismaService.aircraft.findUnique({ + return await client.aircraft.findUnique({ where: { id }, include: { images: true }, }); } catch (error) { - if (error instanceof Prisma.PrismaClientKnownRequestError) { + if (ownsPreparedImages) { + await this.cleanupPreparedImages(preparedImages); + } + if ( + error instanceof HttpException || + error instanceof Prisma.PrismaClientKnownRequestError + ) { throw error; } throw new Error(`Erro ao atualizar aeronave: ${error.message}`); } } - async remove(id: string) { + async remove( + id: string, + client: PrismaService | Prisma.TransactionClient = this.prismaService, + ) { try { - await updateProductWithMonetaryLock(this.prismaService, { + await updateProductWithMonetaryLock(client, { productType: ProductType.AIRCRAFT, productId: id, data: { diff --git a/backend/src/features/appointments/appointment-schedule-lock.spec.ts b/backend/src/features/appointments/appointment-schedule-lock.spec.ts new file mode 100644 index 00000000..445c1a77 --- /dev/null +++ b/backend/src/features/appointments/appointment-schedule-lock.spec.ts @@ -0,0 +1,220 @@ +import { ConflictException } from '@nestjs/common'; +import { + AppointmentSchedulingMethod, + CalendlySyncStatus, + StatusAgendamento, +} from '@prisma/client'; +import * as scheduleLock from './appointment-schedule-lock'; + +describe('specialist schedule occupation', () => { + const when = new Date('2099-01-01T10:00:00.000Z'); + const hour = 60 * 60 * 1000; + + // Evaluate the Prisma filter at the storage boundary so availability tests + // exercise the actual query produced by the domain helper. + function matches(record: any, where: any): boolean { + return Object.entries(where).every(([key, value]: [string, any]) => { + if (key === 'OR') + return value.some((branch: any) => matches(record, branch)); + if (key === 'appointment_datetime') { + return ( + record[key] !== null && + record[key] >= value.gte && + record[key] <= value.lte + ); + } + if (value && typeof value === 'object') { + if ('not' in value) return record[key] !== value.not; + if ('in' in value) return value.in.includes(record[key]); + } + return record[key] === value; + }); + } + + function transaction(record: any) { + return { + appointment: { + findFirst: jest.fn(async ({ where }) => + matches(record, where) ? record : null, + ), + }, + }; + } + + const occupied = { + id: 'competing-appointment', + client_id: 'competing-client', + process_id: 'competing-process', + specialist_id: 's1', + status: StatusAgendamento.SCHEDULED, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + calendly_sync_status: CalendlySyncStatus.PENDING, + appointment_datetime: when, + }; + + it('builds one occupation predicate with the original inclusive one-hour window', () => { + expect( + (scheduleLock as any).buildOccupiedScheduleWhere('s1', when), + ).toEqual({ + specialist_id: 's1', + appointment_datetime: { + gte: new Date(when.getTime() - hour), + lte: new Date(when.getTime() + hour), + }, + OR: [ + { status: StatusAgendamento.SCHEDULED }, + { + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + calendly_sync_status: CalendlySyncStatus.SYNCED, + }, + { status: StatusAgendamento.PENDING, scheduling_method: null }, + ], + }); + }); + + it.each([-hour, hour])( + 'conflicts at the inclusive boundary %i ms', + async (offset) => { + const tx = transaction({ + ...occupied, + appointment_datetime: new Date(when.getTime() + offset), + }); + await expect( + scheduleLock.assertSpecialistScheduleAvailable(tx, 's1', when), + ).rejects.toThrow(ConflictException); + }, + ); + + it.each([-hour - 1, hour + 1])( + 'allows one millisecond outside the boundary %i ms', + async (offset) => { + const tx = transaction({ + ...occupied, + appointment_datetime: new Date(when.getTime() + offset), + }); + await expect( + scheduleLock.assertSpecialistScheduleAvailable(tx, 's1', when), + ).resolves.toBeUndefined(); + }, + ); + + it.each([ + [AppointmentSchedulingMethod.EMAIL, CalendlySyncStatus.PENDING], + [AppointmentSchedulingMethod.EMAIL, CalendlySyncStatus.SYNCED], + [AppointmentSchedulingMethod.CALENDLY, CalendlySyncStatus.PENDING], + [AppointmentSchedulingMethod.CALENDLY, CalendlySyncStatus.FAILED], + ])( + 'does not reserve a pending %s request with sync %s', + async (method, sync) => { + const tx = transaction({ + ...occupied, + status: StatusAgendamento.PENDING, + scheduling_method: method, + calendly_sync_status: sync, + }); + await expect( + scheduleLock.assertSpecialistScheduleAvailable(tx, 's1', when), + ).resolves.toBeUndefined(); + }, + ); + + it.each([ + [AppointmentSchedulingMethod.CALENDLY, CalendlySyncStatus.SYNCED], + [null, CalendlySyncStatus.PENDING], + ])( + 'reserves synced Calendly and legacy dated pending requests: %s', + async (method, sync) => { + const tx = transaction({ + ...occupied, + status: StatusAgendamento.PENDING, + scheduling_method: method, + calendly_sync_status: sync, + }); + await expect( + scheduleLock.assertSpecialistScheduleAvailable(tx, 's1', when), + ).rejects.toThrow(ConflictException); + }, + ); + + it.each([StatusAgendamento.COMPLETED, StatusAgendamento.CANCELLED])( + 'does not reserve a %s appointment', + async (status) => { + await expect( + scheduleLock.assertSpecialistScheduleAvailable( + transaction({ ...occupied, status }), + 's1', + when, + ), + ).resolves.toBeUndefined(); + }, + ); + + it('does not reserve undated legacy pending requests or another specialist', async () => { + await expect( + scheduleLock.assertSpecialistScheduleAvailable( + transaction({ + ...occupied, + status: StatusAgendamento.PENDING, + scheduling_method: null, + appointment_datetime: null, + }), + 's1', + when, + ), + ).resolves.toBeUndefined(); + await expect( + scheduleLock.assertSpecialistScheduleAvailable( + transaction({ ...occupied, specialist_id: 's2' }), + 's1', + when, + ), + ).resolves.toBeUndefined(); + }); + + it('excludes the appointment being updated', async () => { + await expect( + scheduleLock.assertSpecialistScheduleAvailable( + transaction(occupied), + 's1', + when, + occupied.id, + ), + ).resolves.toBeUndefined(); + }); + + it('does not query availability for an absent datetime', async () => { + const tx = transaction(occupied); + await expect( + scheduleLock.assertSpecialistScheduleAvailable(tx, 's1', null), + ).resolves.toBeUndefined(); + expect(tx.appointment.findFirst).not.toHaveBeenCalled(); + }); + + it('returns a conflict without competing appointment, client or process identities', async () => { + const tx = transaction(occupied); + const error = await scheduleLock + .assertSpecialistScheduleAvailable(tx, 's1', when) + .catch((caught) => caught); + expect(error).toBeInstanceOf(ConflictException); + expect(error.getResponse()).toEqual({ + success: false, + error: { + code: 409, + message: expect.any(String), + details: { suggested_times: expect.any(Array) }, + }, + }); + const response = JSON.stringify(error.getResponse()); + for (const identity of [ + occupied.id, + occupied.client_id, + occupied.process_id, + ]) { + expect(response).not.toContain(identity); + } + expect(tx.appointment.findFirst).toHaveBeenCalledWith( + expect.objectContaining({ select: { id: true } }), + ); + }); +}); diff --git a/backend/src/features/appointments/appointment-schedule-lock.ts b/backend/src/features/appointments/appointment-schedule-lock.ts index 5a2d6cc4..b2ebf866 100644 --- a/backend/src/features/appointments/appointment-schedule-lock.ts +++ b/backend/src/features/appointments/appointment-schedule-lock.ts @@ -1,6 +1,36 @@ import { ConflictException } from '@nestjs/common'; -import { StatusAgendamento } from '@prisma/client'; -import { formatToISO, suggestNextAvailableSlots } from 'src/shared/utils/date.utils'; +import { + AppointmentSchedulingMethod, + CalendlySyncStatus, + Prisma, + StatusAgendamento, +} from '@prisma/client'; +import { suggestNextAvailableSlots } from 'src/shared/utils/date.utils'; + +export function buildOccupiedScheduleWhere( + specialistId: string, + appointmentDateTime: Date, + excludeAppointmentId?: string, +): Prisma.AppointmentWhereInput { + const hour = 60 * 60 * 1000; + return { + specialist_id: specialistId, + ...(excludeAppointmentId ? { id: { not: excludeAppointmentId } } : {}), + appointment_datetime: { + gte: new Date(appointmentDateTime.getTime() - hour), + lte: new Date(appointmentDateTime.getTime() + hour), + }, + OR: [ + { status: StatusAgendamento.SCHEDULED }, + { + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + calendly_sync_status: CalendlySyncStatus.SYNCED, + }, + { status: StatusAgendamento.PENDING, scheduling_method: null }, + ], + }; +} export async function acquireSpecialistScheduleLock( tx: any, @@ -19,17 +49,13 @@ export async function assertSpecialistScheduleAvailable( excludeAppointmentId?: string, ): Promise { if (!appointmentDateTime) return; - const conflictStart = new Date(appointmentDateTime.getTime() - 60 * 60 * 1000); - const conflictEnd = new Date(appointmentDateTime.getTime() + 60 * 60 * 1000); const existing = await tx.appointment.findFirst({ - where: { - specialist_id: specialistId, - ...(excludeAppointmentId ? { id: { not: excludeAppointmentId } } : {}), - appointment_datetime: { gte: conflictStart, lte: conflictEnd }, - status: { - in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], - }, - }, + where: buildOccupiedScheduleWhere( + specialistId, + appointmentDateTime, + excludeAppointmentId, + ), + select: { id: true }, }); if (!existing) return; @@ -39,13 +65,6 @@ export async function assertSpecialistScheduleAvailable( code: 409, message: 'Especialista já possui agendamento neste horário', details: { - conflicting_appointment: { - id: existing.id, - appointment_datetime: existing.appointment_datetime - ? formatToISO(existing.appointment_datetime) - : null, - client_id: existing.client_id, - }, suggested_times: suggestNextAvailableSlots(appointmentDateTime, 3), }, }, diff --git a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts index c16b71bc..fb7622e4 100644 --- a/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts +++ b/backend/src/features/appointments/appointments-concurrency.postgres.spec.ts @@ -2,24 +2,118 @@ import { randomUUID } from 'node:crypto'; import { ConflictException } from '@nestjs/common'; import { AppointmentSchedulingMethod, + CalendlySyncStatus, PrismaClient, + ProcessStatus, ProductCurrency, ProductType, StatusAgendamento, UserRole, } from '@prisma/client'; +import { ProcessesService } from '../processes/processes.service'; import { AppointmentsService } from './appointments.service'; -type Deferred = { promise: Promise; resolve: () => void }; +type Deferred = { promise: Promise; resolve: (value: T) => void }; -function deferred(): Deferred { - let resolve!: () => void; - const promise = new Promise((done) => { +function deferred(): Deferred { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { resolve = done; }); return { promise, resolve }; } +function observeFirstAdvisoryLock( + client: PrismaClient, + attempted: Deferred, + productAcquired: Deferred, +) { + let observed = false; + return new Proxy(client, { + get(target, property) { + if (property === '$transaction') { + return (callback: (tx: any) => Promise, options?: any) => + target.$transaction( + (tx) => + callback( + new Proxy(tx, { + get(transaction, member) { + if (member === '$queryRaw') { + return async ( + strings: TemplateStringsArray, + ...values: unknown[] + ) => { + const key = String(values[0]); + if (!observed) { + observed = true; + attempted.resolve(key); + } + const result = await transaction.$queryRaw( + strings, + ...values, + ); + if (key.startsWith('product-money:')) { + productAcquired.resolve(); + } + return result; + }; + } + return bindMember(transaction, member); + }, + }), + ), + options, + ); + } + return bindMember(target, property); + }, + }); +} + +function pauseAfterScheduleLock( + client: PrismaClient, + acquired: Deferred, + release: Deferred, +) { + return new Proxy(client, { + get(target, property) { + if (property === '$transaction') { + return (callback: (tx: any) => Promise, options?: any) => + target.$transaction( + (tx) => + callback( + new Proxy(tx, { + get(transaction, member) { + if (member === '$queryRaw') { + return async ( + strings: TemplateStringsArray, + ...values: unknown[] + ) => { + const result = await transaction.$queryRaw( + strings, + ...values, + ); + if ( + String(values[0]).startsWith('appointment-schedule:') + ) { + acquired.resolve(); + await release.promise; + } + return result; + }; + } + return bindMember(transaction, member); + }, + }), + ), + options, + ); + } + return bindMember(target, property); + }, + }); +} + function withApplicationName(url: string, name: string): string { const separator = url.includes('?') ? '&' : '?'; return `${url}${separator}application_name=${encodeURIComponent(name)}&connection_limit=1&pool_timeout=3`; @@ -31,25 +125,33 @@ function bindMember(target: any, property: PropertyKey): any { } function signalScheduleLockAttempt(client: PrismaClient, attempted: Deferred) { - const wrapTransaction = (tx: any) => - new Proxy(tx, { - get(target, property) { - if (property === '$queryRaw') { - return (strings: TemplateStringsArray, ...values: unknown[]) => { - if (String(values[0]).startsWith('appointment-schedule:')) { - attempted.resolve(); - } - return target.$queryRaw(strings, ...values); - }; - } - return bindMember(target, property); - }, - }); return new Proxy(client, { get(target, property) { if (property === '$transaction') { return (callback: (tx: any) => Promise, options?: any) => - target.$transaction((tx) => callback(wrapTransaction(tx)), options); + target.$transaction( + (tx) => + callback( + new Proxy(tx, { + get(transaction, member) { + if (member === '$queryRaw') { + return ( + strings: TemplateStringsArray, + ...values: unknown[] + ) => { + if ( + String(values[0]).startsWith('appointment-schedule:') + ) + attempted.resolve(); + return transaction.$queryRaw(strings, ...values); + }; + } + return bindMember(transaction, member); + }, + }), + ), + options, + ); } return bindMember(target, property); }, @@ -59,420 +161,841 @@ function signalScheduleLockAttempt(client: PrismaClient, attempted: Deferred) { const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL; const describeWithPostgres = databaseUrl ? describe : describe.skip; -describeWithPostgres('appointment schedule lock — PostgreSQL concurrency', () => { - const suffix = randomUUID().replaceAll('-', ''); - const firstClientId = randomUUID(); - const secondClientId = randomUUID(); - const specialistId = randomUUID(); - const firstCarId = randomUUID(); - const secondCarId = randomUUID(); - const first = new PrismaClient({ - datasources: { - db: { url: withApplicationName(databaseUrl!, `schedule_a_${suffix}`) }, - }, - }); - const second = new PrismaClient({ - datasources: { - db: { url: withApplicationName(databaseUrl!, `schedule_b_${suffix}`) }, - }, - }); - const holder = new PrismaClient({ - datasources: { - db: { - url: withApplicationName(databaseUrl!, `schedule_holder_${suffix}`), - }, - }, - }); +describeWithPostgres( + 'appointment schedule lock — PostgreSQL concurrency', + () => { + const suffix = randomUUID().replaceAll('-', ''); + const clientIds = [randomUUID(), randomUUID()]; + const specialistIds = [randomUUID(), randomUUID()]; + const carIds = [randomUUID(), randomUUID(), randomUUID()]; + const specialistId = specialistIds[0]; + const proposedIso = '2099-01-01T10:00:00.000Z'; + const proposedDate = new Date(proposedIso); + let first: PrismaClient; + let second: PrismaClient; + let holder: PrismaClient; + const notifications = { + sendAppointmentConfirmedEmail: jest.fn().mockResolvedValue(undefined), + sendAppointmentRescheduledEmail: jest.fn().mockResolvedValue(undefined), + sendAppointmentCancelledEmail: jest.fn().mockResolvedValue(undefined), + sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined), + }; - beforeAll(async () => { - await holder.user.createMany({ - data: [ - { - id: firstClientId, - name: 'First', - surname: 'Client', - email: `schedule-client-a-${suffix}@example.test`, - rg: suffix.slice(0, 10) + '1', - role: UserRole.CUSTOMER, - password_hash: 'not-used', - }, - { - id: secondClientId, - name: 'Second', - surname: 'Client', - email: `schedule-client-b-${suffix}@example.test`, - rg: suffix.slice(0, 10) + '2', - role: UserRole.CUSTOMER, - password_hash: 'not-used', - }, - { - id: specialistId, + beforeAll(async () => { + const client = (name: string) => + new PrismaClient({ + datasources: { + db: { url: withApplicationName(databaseUrl!, `${name}_${suffix}`) }, + }, + }); + first = client('schedule_a'); + second = client('schedule_b'); + holder = client('schedule_holder'); + await holder.user.createMany({ + data: [...clientIds, ...specialistIds].map((id, index) => ({ + id, name: 'Schedule', - surname: 'Specialist', - email: `schedule-specialist-${suffix}@example.test`, - rg: suffix.slice(11, 22), - role: UserRole.SPECIALIST, - speciality: ProductType.CAR, + surname: `Fixture ${index}`, + email: `schedule-${index}-${suffix}@example.test`, + rg: `${suffix.slice(0, 10)}${index}`, + role: index < 2 ? UserRole.CUSTOMER : UserRole.SPECIALIST, + speciality: index < 2 ? null : ProductType.CAR, password_hash: 'not-used', - }, - ], - }); - await holder.car.createMany({ - data: [firstCarId, secondCarId].map((id, index) => ({ - id, - specialist_id: specialistId, - marca: 'Schedule', - modelo: `Car ${index + 1}`, - identificador: `schedule-${index}-${suffix}`, - valor: 100000 + index, - currency: ProductCurrency.BRL, - estado: 'SP', - ano: 2026, - })), + })), + }); + await holder.car.createMany({ + data: carIds.map((id, index) => ({ + id, + specialist_id: index < 2 ? specialistId : specialistIds[1], + marca: 'Schedule', + modelo: `Car ${index}`, + identificador: `schedule-${index}-${suffix}`, + valor: 100000 + index, + currency: ProductCurrency.BRL, + estado: 'SP', + ano: 2026, + })), + }); }); - }); - beforeEach(async () => { - const appointments = await holder.appointment.findMany({ - where: { specialist_id: specialistId }, - select: { id: true }, - }); - const processes = await holder.process.findMany({ - where: { appointment_id: { in: appointments.map(({ id }) => id) } }, - select: { id: true }, - }); - await holder.processStatusHistory.deleteMany({ - where: { processId: { in: processes.map(({ id }) => id) } }, - }); - await holder.process.deleteMany({ - where: { id: { in: processes.map(({ id }) => id) } }, - }); - await holder.appointment.deleteMany({ - where: { id: { in: appointments.map(({ id }) => id) } }, - }); - }); + async function clearAppointments() { + const where = { + specialist_id: { in: specialistIds }, + client_id: { in: clientIds }, + }; + const processes = await holder.process.findMany({ + where, + select: { id: true }, + }); + await holder.processStatusHistory.deleteMany({ + where: { processId: { in: processes.map(({ id }) => id) } }, + }); + await holder.process.deleteMany({ + where: { id: { in: processes.map(({ id }) => id) } }, + }); + await holder.appointment.deleteMany({ where }); + } - afterAll(async () => { - const appointments = await holder.appointment.findMany({ - where: { specialist_id: specialistId }, - select: { id: true }, - }); - await holder.process.deleteMany({ - where: { appointment_id: { in: appointments.map(({ id }) => id) } }, + beforeEach(async () => { + await clearAppointments(); + jest.clearAllMocks(); }); - await holder.appointment.deleteMany({ - where: { specialist_id: specialistId }, - }); - await holder.car.deleteMany({ - where: { id: { in: [firstCarId, secondCarId] } }, - }); - await holder.user.deleteMany({ - where: { id: { in: [firstClientId, secondClientId, specialistId] } }, - }); - await Promise.all([first.$disconnect(), second.$disconnect(), holder.$disconnect()]); - }); - it('allows only one overlapping appointment across different products', async () => { - const lockKey = `appointment-schedule:${specialistId}`; - const holderReady = deferred(); - const releaseHolder = deferred(); - const firstAttempted = deferred(); - const secondAttempted = deferred(); - const held = holder.$transaction(async (tx) => { - await tx.$queryRaw` - SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))::text AS locked - `; - holderReady.resolve(); - await releaseHolder.promise; + afterAll(async () => { + try { + if (holder) { + await clearAppointments(); + await holder.car.deleteMany({ where: { id: { in: carIds } } }); + await holder.user.deleteMany({ + where: { id: { in: [...clientIds, ...specialistIds] } }, + }); + } + } finally { + await Promise.all([ + first?.$disconnect(), + second?.$disconnect(), + holder?.$disconnect(), + ]); + } }); - await holderReady.promise; - - const notification = { - sendAppointmentCreatedEmail: jest.fn().mockResolvedValue(undefined), - } as any; - const serviceA = new AppointmentsService( - signalScheduleLockAttempt(first, firstAttempted) as any, - notification, - {} as any, - ); - const serviceB = new AppointmentsService( - signalScheduleLockAttempt(second, secondAttempted) as any, - notification, - {} as any, - ); - const appointment_datetime = '2099-01-01T10:00:00.000Z'; - const outcomesPromise = Promise.allSettled([ - serviceA.create( + function appointments(client: PrismaClient, attempted?: Deferred) { + return new AppointmentsService( + (attempted + ? signalScheduleLockAttempt(client, attempted) + : client) as any, + notifications as any, { - client_id: firstClientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - product_id: firstCarId, - appointment_datetime, + resolveScheduledStartTime: jest.fn().mockResolvedValue(proposedDate), } as any, - firstClientId, - UserRole.CUSTOMER, - ), - serviceB.create( + ); + } + + function processes(client: PrismaClient, attempted: Deferred) { + return new ProcessesService( + signalScheduleLockAttempt(client, attempted) as any, + notifications as any, + ); + } + + function createRequest( + client: PrismaClient, + index: number, + otherSpecialist = false, + ) { + return appointments(client).createPending( { - client_id: secondClientId, - specialist_id: specialistId, + client_id: clientIds[index], + specialist_id: otherSpecialist ? specialistIds[1] : specialistId, product_type: ProductType.CAR, - product_id: secondCarId, - appointment_datetime, - } as any, - secondClientId, + product_id: otherSpecialist ? carIds[2] : carIds[index], + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: proposedIso, + }, + clientIds[index], UserRole.CUSTOMER, - ), - ]); - await Promise.all([firstAttempted.promise, secondAttempted.promise]); - releaseHolder.resolve(); - await held; - const outcomes = await outcomesPromise; - - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); - await expect(holder.appointment.count({ where: { specialist_id: specialistId } })).resolves.toBe(1); - }, 15_000); - - it('allows only one definitive reschedule under concurrent requests', async () => { - const appointment = await holder.appointment.create({ - data: { - client_id: firstClientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - product_id: firstCarId, + ); + } + + // Force both service calls to attempt the real advisory lock while it is held. + // Release even on an early failure so a broken prerequisite cannot hang Jest. + async function race( + start: (a: Deferred, b: Deferred) => [Promise, Promise], + lockSpecialist = specialistId, + ) { + const ready = deferred(); + const release = deferred(); + const a = deferred(); + const b = deferred(); + const held = holder.$transaction(async (tx) => { + const key = `appointment-schedule:${lockSpecialist}`; + await tx.$queryRaw`SELECT pg_advisory_xact_lock(hashtextextended(${key}, 0))::text AS locked`; + ready.resolve(); + await release.promise; + }); + await ready.promise; + const calls = start(a, b); + const outcomes = Promise.allSettled(calls); + let bothAttempted: boolean; + try { + bothAttempted = await Promise.race([ + Promise.all([a.promise, b.promise]).then(() => true), + Promise.race( + calls.map((call) => + call.then( + () => false, + () => false, + ), + ), + ), + ]); + } finally { + release.resolve(); + await held; + } + const result = await outcomes; + expect(bothAttempted).toBe(true); + return result; + } + + it('allows concurrent dated EMAIL proposals for the same specialist/time', async () => { + const outcomes = await Promise.allSettled([ + createRequest(first, 0), + createRequest(second, 1), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(2); + expect( + await holder.appointment.count({ + where: { + specialist_id: specialistId, + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: proposedDate, + }, + }), + ).toBe(2); + expect( + await holder.process.count({ + where: { + specialist_id: specialistId, + status: ProcessStatus.SCHEDULING, + }, + }), + ).toBe(2); + expect( + await holder.processStatusHistory.count({ + where: { process: { specialist_id: specialistId } }, + }), + ).toBe(2); + }, 15_000); + + it('serializes canonical confirmations and leaves the losing request completely pending', async () => { + const firstRequest = await createRequest(holder, 0); + const secondRequest = await createRequest(holder, 1); + const before = await holder.process.findMany({ + where: { + id: { in: [firstRequest.process_id, secondRequest.process_id] }, + }, + include: { appointment: true }, + }); + const outcomes = await race((a, b) => [ + processes(first, a).confirmAppointment( + firstRequest.process_id, + specialistId, + proposedIso, + ), + processes(second, b).confirmAppointment( + secondRequest.process_id, + specialistId, + proposedIso, + ), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + const failure = outcomes.find( + ({ status }) => status === 'rejected', + ) as PromiseRejectedResult; + expect(failure.reason).toBeInstanceOf(ConflictException); + const loserIndex = outcomes.findIndex( + ({ status }) => status === 'rejected', + ); + const loserId = [firstRequest.process_id, secondRequest.process_id][ + loserIndex + ]; + expect( + await holder.process.findUniqueOrThrow({ + where: { id: loserId }, + include: { appointment: true }, + }), + ).toEqual(before.find(({ id }) => id === loserId)); + expect( + await holder.appointment.count({ + where: { + specialist_id: specialistId, + appointment_datetime: proposedDate, + status: StatusAgendamento.SCHEDULED, + }, + }), + ).toBe(1); + expect( + await holder.process.count({ + where: { + specialist_id: specialistId, + status: ProcessStatus.SCHEDULING, + }, + }), + ).toBe(2); + expect( + await holder.processStatusHistory.count({ + where: { process: { specialist_id: specialistId } }, + }), + ).toBe(2); + }, 15_000); + + it('allows different specialists to confirm the same instant', async () => { + const firstRequest = await createRequest(holder, 0); + const secondRequest = await createRequest(holder, 1, true); + const outcomes = await Promise.allSettled([ + new ProcessesService( + first as any, + notifications as any, + ).confirmAppointment( + firstRequest.process_id, + specialistId, + proposedIso, + ), + new ProcessesService( + second as any, + notifications as any, + ).confirmAppointment( + secondRequest.process_id, + specialistIds[1], + proposedIso, + ), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(2); + expect( + await holder.appointment.count({ + where: { + specialist_id: { in: specialistIds }, + status: StatusAgendamento.SCHEDULED, + appointment_datetime: proposedDate, + }, + }), + ).toBe(2); + }, 15_000); + + it('makes a concurrent double-click idempotent without duplicate notes, histories or emails', async () => { + const request = await createRequest(holder, 0); + const outcomes = await race((a, b) => [ + processes(first, a).confirmAppointment( + request.process_id, + specialistId, + proposedIso, + ), + processes(second, b).confirmAppointment( + request.process_id, + specialistId, + proposedIso, + ), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(2); + expect(outcomes[0]).toEqual(outcomes[1]); + const stored = await holder.process.findUniqueOrThrow({ + where: { id: request.process_id }, + include: { appointment: true }, + }); + expect(stored.status).toBe(ProcessStatus.SCHEDULING); + expect( + stored.notes?.match(/Agendamento confirmado pelo especialista/g), + ).toHaveLength(1); + expect(stored.appointment).toMatchObject({ status: StatusAgendamento.SCHEDULED, - scheduling_method: AppointmentSchedulingMethod.PLATFORM, - appointment_datetime: new Date('2099-01-01T09:00:00.000Z'), - }, - }); - await holder.process.create({ - data: { - client_id: firstClientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - car_id: firstCarId, - appointment_id: appointment.id, - status: 'SCHEDULING', + appointment_datetime: proposedDate, + specialist_rescheduled_at: null, + specialist_rescheduled_from: null, + }); + expect( + await holder.processStatusHistory.count({ + where: { processId: stored.id }, + }), + ).toBe(1); + expect( + await holder.appointment.count({ + where: { specialist_id: specialistId }, + }), + ).toBe(1); + await new Promise((resolve) => setImmediate(resolve)); + expect(notifications.sendAppointmentConfirmedEmail).toHaveBeenCalledTimes( + 1, + ); + }, 15_000); + + it('rolls back the process claim if appointment persistence fails', async () => { + const request = await createRequest(holder, 0); + const before = await holder.process.findUniqueOrThrow({ + where: { id: request.process_id }, + include: { appointment: true }, + }); + const failingStorage = new Proxy(first, { + get(target, property) { + if (property === '$transaction') + return (callback: any) => + target.$transaction((tx) => + callback( + new Proxy(tx, { + get(transaction, member) { + if (member === 'appointment') + return new Proxy(transaction.appointment, { + get(repository, action) { + if (action === 'update') + return async () => { + throw new Error( + 'appointment persistence failed', + ); + }; + return bindMember(repository, action); + }, + }); + return bindMember(transaction, member); + }, + }), + ), + ); + return bindMember(target, property); + }, + }); + await expect( + new ProcessesService( + failingStorage as any, + notifications as any, + ).confirmAppointment(request.process_id, specialistId, proposedIso), + ).rejects.toThrow('appointment persistence failed'); + expect( + await holder.process.findUniqueOrThrow({ + where: { id: request.process_id }, + include: { appointment: true }, + }), + ).toEqual(before); + expect( + await holder.processStatusHistory.count({ + where: { processId: request.process_id }, + }), + ).toBe(1); + expect( + notifications.sendAppointmentConfirmedEmail, + ).not.toHaveBeenCalled(); + }, 15_000); + + it('allows only one definitive reschedule under concurrent requests', async () => { + const request = await createRequest(holder, 0); + await new ProcessesService( + holder as any, + notifications as any, + ).confirmAppointment(request.process_id, specialistId, proposedIso); + const outcomes = await race((a, b) => [ + appointments(first, a).reschedule( + request.id, + '2099-01-02T10:00:00Z', + specialistId, + ), + appointments(second, b).reschedule( + request.id, + '2099-01-03T10:00:00Z', + specialistId, + ), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + expect( + outcomes.find(({ status }) => status === 'rejected'), + ).toMatchObject({ reason: expect.any(ConflictException) }); + const stored = await holder.appointment.findUniqueOrThrow({ + where: { id: request.id }, + }); + expect(stored.specialist_rescheduled_at).not.toBeNull(); + expect(stored.specialist_rescheduled_from).toEqual(proposedDate); + }, 15_000); + + async function calendlyRequest(index: number) { + return holder.appointment.create({ + data: { + client_id: clientIds[index], + specialist_id: specialistId, + product_type: ProductType.CAR, + product_id: carIds[index], + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + }, + }); + } + + it.each([AppointmentSchedulingMethod.CALENDLY, null])( + 'serializes legacy confirmPending requests for the same specialist/time (%s)', + async (schedulingMethod) => { + const pending = await Promise.all( + clientIds.map(async (clientId, index) => { + const appointment = await holder.appointment.create({ + data: { + client_id: clientId, + specialist_id: specialistId, + product_type: ProductType.CAR, + product_id: carIds[index], + status: StatusAgendamento.PENDING, + scheduling_method: schedulingMethod, + appointment_datetime: null, + }, + }); + await holder.process.create({ + data: { + client_id: clientId, + specialist_id: specialistId, + product_type: ProductType.CAR, + car_id: carIds[index], + appointment_id: appointment.id, + status: ProcessStatus.SCHEDULING, + }, + }); + return appointment; + }), + ); + const before = await holder.process.findMany({ + where: { appointment_id: { in: pending.map(({ id }) => id) } }, + include: { appointment: true }, + }); + const outcomes = await race((a, b) => [ + appointments(first, a).confirmPending( + pending[0].id, + specialistId, + proposedDate, + ), + appointments(second, b).confirmPending( + pending[1].id, + specialistId, + proposedDate, + ), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + expect( + outcomes.find(({ status }) => status === 'rejected'), + ).toMatchObject({ reason: expect.any(ConflictException) }); + const loserId = + pending[outcomes.findIndex(({ status }) => status === 'rejected')].id; + expect( + await holder.process.findUniqueOrThrow({ + where: { appointment_id: loserId }, + include: { appointment: true }, + }), + ).toEqual( + before.find(({ appointment_id }) => appointment_id === loserId), + ); + expect( + await holder.appointment.count({ + where: { + specialist_id: specialistId, + status: StatusAgendamento.SCHEDULED, + appointment_datetime: proposedDate, + }, + }), + ).toBe(1); + expect( + await holder.process.count({ + where: { + specialist_id: specialistId, + status: ProcessStatus.NEGOTIATION, + }, + }), + ).toBe(1); + expect( + await holder.processStatusHistory.count({ + where: { process: { specialist_id: specialistId } }, + }), + ).toBe(1); + await new Promise((resolve) => setImmediate(resolve)); + expect( + notifications.sendAppointmentConfirmedEmail, + ).toHaveBeenCalledTimes(1); }, - }); + 15_000, + ); - const releaseHolder = deferred(); - const holderReady = deferred(); - const firstAttempted = deferred(); - const secondAttempted = deferred(); - const held = holdScheduleLock(releaseHolder, holderReady); - await holderReady.promise; - const serviceA = service(first, firstAttempted); - const serviceB = service(second, secondAttempted); - - const outcomesPromise = Promise.allSettled([ - serviceA.reschedule( - appointment.id, - '2099-01-02T10:00:00.000Z', + it('keeps schedule → product lock order across completion and legacy confirmation', async () => { + const confirmingAppointment = await holder.appointment.create({ + data: { + client_id: clientIds[0], + specialist_id: specialistId, + product_type: ProductType.CAR, + product_id: carIds[0], + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + }, + }); + await holder.process.create({ + data: { + client_id: clientIds[0], + specialist_id: specialistId, + product_type: ProductType.CAR, + car_id: carIds[0], + appointment_id: confirmingAppointment.id, + status: ProcessStatus.SCHEDULING, + }, + }); + const completingAppointment = await holder.appointment.create({ + data: { + client_id: clientIds[1], + specialist_id: specialistId, + product_type: ProductType.CAR, + product_id: carIds[0], + status: StatusAgendamento.SCHEDULED, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + appointment_datetime: new Date('2099-01-01T08:00:00.000Z'), + }, + }); + const completingProcess = await holder.process.create({ + data: { + client_id: clientIds[1], + specialist_id: specialistId, + product_type: ProductType.CAR, + car_id: carIds[0], + appointment_id: completingAppointment.id, + status: ProcessStatus.SCHEDULING, + }, + }); + await holder.meetingSession.create({ + data: { + process_id: completingProcess.id, + meet_link: 'https://meet.jit.si/appointment-lock-order', + calendar_event_id: `appointment-lock-order-${completingProcess.id}`, + started_by_id: specialistId, + ended_by_id: specialistId, + started_at: new Date('2099-01-01T08:00:00.000Z'), + ended_at: new Date('2099-01-01T09:00:00.000Z'), + }, + }); + + const completionHasSchedule = deferred(); + const releaseCompletion = deferred(); + const confirmationFirstAttempt = deferred(); + const confirmationProductAcquired = deferred(); + const completionService = new AppointmentsService( + pauseAfterScheduleLock( + second, + completionHasSchedule, + releaseCompletion, + ) as any, + notifications as any, + {} as any, + ); + const confirmationService = new AppointmentsService( + observeFirstAdvisoryLock( + first, + confirmationFirstAttempt, + confirmationProductAcquired, + ) as any, + notifications as any, + {} as any, + ); + + const completion = completionService.updateStatus( + completingAppointment.id, + { status: StatusAgendamento.COMPLETED }, specialistId, - ), - serviceB.reschedule( - appointment.id, - '2099-01-03T10:00:00.000Z', + UserRole.SPECIALIST, + ); + await completionHasSchedule.promise; + const confirmation = confirmationService.confirmPending( + confirmingAppointment.id, specialistId, - ), - ]); - const bothAttemptedBeforeCompletion = await Promise.race([ - Promise.all([firstAttempted.promise, secondAttempted.promise]).then( - () => true, - ), - outcomesPromise.then(() => false), - ]); - releaseHolder.resolve(); - await held; - const outcomes = await outcomesPromise; - - expect(bothAttemptedBeforeCompletion).toBe(true); - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); - const stored = await holder.appointment.findUniqueOrThrow({ - where: { id: appointment.id }, - }); - expect(stored.specialist_rescheduled_at).not.toBeNull(); - expect(stored.specialist_rescheduled_from).toEqual( - new Date('2099-01-01T09:00:00.000Z'), - ); - }, 15_000); - - async function createPendingWithProcess(clientId: string, carId: string) { - const appointment = await holder.appointment.create({ - data: { - client_id: clientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - product_id: carId, - status: 'PENDING', - }, - }); - await holder.process.create({ - data: { - client_id: clientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - car_id: carId, - appointment_id: appointment.id, - status: 'SCHEDULING', + new Date('2099-01-02T10:00:00.000Z'), + ); + const firstKey = await confirmationFirstAttempt.promise; + if (firstKey.startsWith('product-money:')) { + await confirmationProductAcquired.promise; + } + releaseCompletion.resolve(); + + await expect( + Promise.all([completion, confirmation]), + ).resolves.toHaveLength(2); + expect(firstKey).toBe(`appointment-schedule:${specialistId}`); + }, 15_000); + + it('keeps confirmation/cancellation races consistent and releases the product for a new request', async () => { + const request = await createRequest(holder, 0); + const outcomes = await race((a, b) => [ + appointments(first, a).updateStatus( + request.id, + { status: StatusAgendamento.CANCELLED }, + clientIds[0], + UserRole.CUSTOMER, + ), + processes(second, b).confirmAppointment( + request.process_id, + specialistId, + proposedIso, + ), + ]); + + expect(outcomes[0].status).toBe('fulfilled'); + expect( + await holder.appointment.findUniqueOrThrow({ + where: { id: request.id }, + include: { process: true }, + }), + ).toMatchObject({ + status: StatusAgendamento.CANCELLED, + process: null, + }); + expect( + await holder.process.findUnique({ where: { id: request.process_id } }), + ).toBeNull(); + + const replacement = await createRequest(holder, 0); + expect(replacement).toMatchObject({ + status: StatusAgendamento.PENDING, + }); + expect(replacement.id).not.toBe(request.id); + expect(replacement.process_id).not.toBe(request.process_id); + expect( + await holder.process.findUniqueOrThrow({ + where: { id: replacement.process_id }, + }), + ).toMatchObject({ status: ProcessStatus.SCHEDULING }); + }, 15_000); + + it('serializes the process cancellation route against confirmation without orphaning either record', async () => { + const request = await createRequest(holder, 0); + const outcomes = await race((a, b) => [ + processes(first, a).cancelAppointment(request.process_id, clientIds[0]), + processes(second, b).confirmAppointment( + request.process_id, + specialistId, + proposedIso, + ), + ]); + + expect(outcomes[0].status).toBe('fulfilled'); + expect( + await holder.appointment.findUnique({ where: { id: request.id } }), + ).toBeNull(); + expect( + await holder.process.findUnique({ where: { id: request.process_id } }), + ).toBeNull(); + + const replacement = await createRequest(holder, 0); + expect(replacement.status).toBe(StatusAgendamento.PENDING); + expect(replacement.id).not.toBe(request.id); + expect(replacement.process_id).not.toBe(request.process_id); + }, 15_000); + + it.each(['appointment', 'process'] as const)( + 'serializes %s cancellation against a process status advance', + async (route) => { + const request = await createRequest(holder, 0); + const outcomes = await race((a, b) => [ + route === 'appointment' + ? appointments(first, a).cancelPending(request.id, clientIds[0]) + : processes(first, a).cancelAppointment( + request.process_id, + clientIds[0], + ), + processes(second, b).update( + request.process_id, + { + status: ProcessStatus.NEGOTIATION, + notes: 'advance concorrente', + }, + specialistId, + UserRole.SPECIALIST, + ), + ]); + + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + const storedProcess = await holder.process.findUnique({ + where: { id: request.process_id }, + }); + const storedAppointment = await holder.appointment.findUnique({ + where: { id: request.id }, + }); + if (outcomes[0].status === 'fulfilled') { + expect(storedProcess).toBeNull(); + expect(storedAppointment).toBeNull(); + } else { + expect(storedProcess).toMatchObject({ + status: ProcessStatus.NEGOTIATION, + }); + expect(storedAppointment).toMatchObject({ + status: StatusAgendamento.PENDING, + }); + } }, - }); - return appointment; - } - - async function holdScheduleLock(release: Deferred, ready: Deferred) { - const lockKey = `appointment-schedule:${specialistId}`; - return holder.$transaction(async (tx) => { - await tx.$queryRaw` - SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))::text AS locked - `; - ready.resolve(); - await release.promise; - }); - } - - function service(client: PrismaClient, attempted: Deferred) { - return new AppointmentsService( - signalScheduleLockAttempt(client, attempted) as any, - { - sendAppointmentCreatedEmail: jest.fn().mockResolvedValue(undefined), - sendAppointmentConfirmedEmail: jest.fn().mockResolvedValue(undefined), - sendAppointmentRescheduledEmail: jest.fn().mockResolvedValue(undefined), - } as any, - {} as any, + 15_000, ); - } - - it('serializes direct create against confirming an overlapping pending appointment', async () => { - const pending = await createPendingWithProcess(secondClientId, secondCarId); - const release = deferred(); - const ready = deferred(); - const createAttempted = deferred(); - const confirmAttempted = deferred(); - const held = holdScheduleLock(release, ready); - await ready.promise; - const serviceA = service(first, createAttempted); - const serviceB = service(second, confirmAttempted); - const scheduledAt = new Date('2099-01-01T10:00:00.000Z'); - - const creating = serviceA.create( - { - client_id: firstClientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - product_id: firstCarId, - appointment_datetime: scheduledAt.toISOString(), - } as any, - firstClientId, - UserRole.CUSTOMER, - ); - const confirming = serviceB.confirmPending(pending.id, specialistId, scheduledAt); - const bothAttemptedBeforeCompletion = await Promise.race([ - Promise.all([createAttempted.promise, confirmAttempted.promise]).then(() => true), - confirming.then( - () => false, - () => false, - ), - ]); - release.resolve(); - await held; - const outcomes = await Promise.allSettled([creating, confirming]); - - expect(bothAttemptedBeforeCompletion).toBe(true); - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); - }, 15_000); - - it('serializes two confirmations that select the same specialist time', async () => { - const firstPending = await createPendingWithProcess(firstClientId, firstCarId); - const secondPending = await createPendingWithProcess(secondClientId, secondCarId); - const release = deferred(); - const ready = deferred(); - const firstAttempted = deferred(); - const secondAttempted = deferred(); - const held = holdScheduleLock(release, ready); - await ready.promise; - const serviceA = service(first, firstAttempted); - const serviceB = service(second, secondAttempted); - const scheduledAt = new Date('2099-01-01T11:00:00.000Z'); - const firstConfirm = serviceA.confirmPending(firstPending.id, specialistId, scheduledAt); - const secondConfirm = serviceB.confirmPending(secondPending.id, specialistId, scheduledAt); - const bothAttemptedBeforeCompletion = await Promise.race([ - Promise.all([firstAttempted.promise, secondAttempted.promise]).then(() => true), - Promise.allSettled([firstConfirm, secondConfirm]).then(() => false), - ]); - release.resolve(); - await held; - const outcomes = await Promise.allSettled([firstConfirm, secondConfirm]); - - expect(bothAttemptedBeforeCompletion).toBe(true); - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); - }, 15_000); - - it('serializes two Calendly callbacks that resolve to an overlapping time', async () => { - const firstPending = await holder.appointment.create({ - data: { - client_id: firstClientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - product_id: firstCarId, - status: 'PENDING', - }, - }); - const secondPending = await holder.appointment.create({ - data: { - client_id: secondClientId, - specialist_id: specialistId, - product_type: ProductType.CAR, - product_id: secondCarId, - status: 'PENDING', - }, - }); - const release = deferred(); - const ready = deferred(); - const firstAttempted = deferred(); - const secondAttempted = deferred(); - const held = holdScheduleLock(release, ready); - await ready.promise; - const serviceA = service(first, firstAttempted); - const serviceB = service(second, secondAttempted); - const scheduledStart = '2099-01-01T12:00:00.000Z'; - const firstRegister = serviceA.registerCalendlyScheduled(firstPending.id, firstClientId, { - event_uri: `https://calendly.test/events/${firstPending.id}`, - invitee_uri: `https://calendly.test/invitees/${firstPending.id}`, - scheduled_start_time: scheduledStart, - }); - const secondRegister = serviceB.registerCalendlyScheduled(secondPending.id, secondClientId, { - event_uri: `https://calendly.test/events/${secondPending.id}`, - invitee_uri: `https://calendly.test/invitees/${secondPending.id}`, - scheduled_start_time: scheduledStart, - }); - const bothAttemptedBeforeCompletion = await Promise.race([ - Promise.all([firstAttempted.promise, secondAttempted.promise]).then(() => true), - Promise.allSettled([firstRegister, secondRegister]).then(() => false), - ]); - release.resolve(); - await held; - const outcomes = await Promise.allSettled([firstRegister, secondRegister]); - - expect(bothAttemptedBeforeCompletion).toBe(true); - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); - }, 15_000); -}); + + function callback( + client: PrismaClient, + attempted: Deferred, + appointment: { id: string }, + index: number, + ) { + return appointments(client, attempted).registerCalendlyScheduled( + appointment.id, + clientIds[index], + { + event_uri: `https://api.calendly.com/scheduled_events/${appointment.id}`, + invitee_uri: `https://api.calendly.com/scheduled_events/${appointment.id}/invitees/${appointment.id}`, + }, + ); + } + + it('serializes two Calendly callbacks that resolve to an overlapping time', async () => { + const a = await calendlyRequest(0); + const b = await calendlyRequest(1); + const outcomes = await race((firstAttempt, secondAttempt) => [ + callback(first, firstAttempt, a, 0), + callback(second, secondAttempt, b, 1), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + expect( + outcomes.find(({ status }) => status === 'rejected'), + ).toMatchObject({ reason: expect.any(ConflictException) }); + expect( + await holder.appointment.count({ + where: { + specialist_id: specialistId, + calendly_sync_status: CalendlySyncStatus.SYNCED, + }, + }), + ).toBe(1); + }, 15_000); + + it('serializes the canonical confirmation against a Calendly callback', async () => { + const request = await createRequest(holder, 0); + const pendingCalendly = await calendlyRequest(1); + const outcomes = await race((a, b) => [ + processes(first, a).confirmAppointment( + request.process_id, + specialistId, + proposedIso, + ), + callback(second, b, pendingCalendly, 1), + ]); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + expect( + outcomes.find(({ status }) => status === 'rejected'), + ).toMatchObject({ reason: expect.any(ConflictException) }); + expect( + await holder.appointment.count({ + where: { + specialist_id: specialistId, + appointment_datetime: proposedDate, + OR: [ + { status: StatusAgendamento.SCHEDULED }, + { + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + calendly_sync_status: CalendlySyncStatus.SYNCED, + }, + ], + }, + }), + ).toBe(1); + }, 15_000); + }, +); diff --git a/backend/src/features/appointments/appointments-list-scope.spec.ts b/backend/src/features/appointments/appointments-list-scope.spec.ts new file mode 100644 index 00000000..078b5ff2 --- /dev/null +++ b/backend/src/features/appointments/appointments-list-scope.spec.ts @@ -0,0 +1,192 @@ +import { ForbiddenException } from '@nestjs/common'; +import { StatusAgendamento, UserRole } from '@prisma/client'; +import { AppointmentsService } from './appointments.service'; + +describe('AppointmentsService.getAppointments — escopo de visibilidade', () => { + const visibleProcessScope = { + OR: [ + { process: { is: null } }, + { process: { is: { removed_at: null } } }, + ], + }; + + function harness(companyId: string | null = 'company-a') { + const count = jest.fn().mockResolvedValue(3); + const findMany = jest.fn().mockResolvedValue([]); + const groupBy = jest.fn().mockResolvedValue([ + { status: StatusAgendamento.SCHEDULED, _count: 2 }, + { status: StatusAgendamento.COMPLETED, _count: 1 }, + ]); + const userFindUnique = jest.fn().mockResolvedValue({ company_id: companyId }); + const prisma = { + user: { findUnique: userFindUnique }, + appointment: { count, findMany, groupBy }, + } as any; + + return { + service: new AppointmentsService(prisma, {} as any, {} as any), + count, + findMany, + groupBy, + userFindUnique, + }; + } + + it.each(['company-a', 'company-b'])( + 'restringe OFFICE aos clientes vinculados à própria empresa (%s)', + async (companyId) => { + const { service, count, findMany, groupBy, userFindUnique } = + harness(companyId); + + const result = await service.getAppointments( + { page: 2, limit: 2, client_id: 'requested-client' }, + 'office-user', + UserRole.OFFICE, + ); + + expect(userFindUnique).toHaveBeenCalledWith({ + where: { id: 'office-user' }, + select: { company_id: true }, + }); + + const tenantScope = { + client: { + role: UserRole.CUSTOMER, + OR: [ + { consultant: { company_id: companyId } }, + { company_id: companyId }, + ], + }, + }; + const expectedWhere = { + ...visibleProcessScope, + AND: [tenantScope], + client_id: 'requested-client', + }; + + expect(count).toHaveBeenCalledWith({ where: expectedWhere }); + expect(findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: expectedWhere, + skip: 2, + take: 2, + }), + ); + expect(groupBy).toHaveBeenCalledWith( + expect.objectContaining({ where: expectedWhere }), + ); + expect(result).toEqual( + expect.objectContaining({ + success: true, + data: [], + meta: { + pagination: { + current_page: 2, + per_page: 2, + total: 3, + total_pages: 2, + has_next: false, + has_prev: true, + }, + summary: { upcoming: 2, completed: 1, cancelled: 0 }, + }, + }), + ); + }, + ); + + it('barra OFFICE sem company_id antes de consultar agendamentos', async () => { + const { service, count, findMany, groupBy } = harness(null); + + await expect( + service.getAppointments({}, 'office-without-company', UserRole.OFFICE), + ).rejects.toThrow(ForbiddenException); + + expect(count).not.toHaveBeenCalled(); + expect(findMany).not.toHaveBeenCalled(); + expect(groupBy).not.toHaveBeenCalled(); + }); + + it('barra papel desconhecido por padrão', async () => { + const { service, userFindUnique, count } = harness(); + + await expect( + service.getAppointments({}, 'unknown-user', 'NEW_ROLE' as UserRole), + ).rejects.toThrow(ForbiddenException); + + expect(userFindUnique).not.toHaveBeenCalled(); + expect(count).not.toHaveBeenCalled(); + }); + + it.each([ + [UserRole.CUSTOMER, 'customer-user', { client_id: 'customer-user' }], + [ + UserRole.SPECIALIST, + 'specialist-user', + { + OR: [ + { specialist_id: 'specialist-user' }, + { client_id: 'specialist-user' }, + ], + }, + ], + [ + UserRole.CONSULTANT, + 'consultant-user', + { + OR: [ + { specialist_id: 'consultant-user' }, + { client_id: 'consultant-user' }, + ], + }, + ], + ])('preserva o escopo de %s', async (role, userId, expectedWhere) => { + const { service, userFindUnique, count, findMany, groupBy } = harness(); + + await service.getAppointments({}, userId, role as UserRole); + + const filteredWhere = + 'OR' in expectedWhere + ? { ...visibleProcessScope, AND: [expectedWhere] } + : { ...visibleProcessScope, ...expectedWhere }; + expect(userFindUnique).not.toHaveBeenCalled(); + expect(count).toHaveBeenCalledWith({ where: filteredWhere }); + expect(findMany).toHaveBeenCalledWith( + expect.objectContaining({ where: filteredWhere }), + ); + expect(groupBy).toHaveBeenCalledWith( + expect.objectContaining({ where: filteredWhere }), + ); + }); + + it('preserva a visão global e a resposta paginada do ADMIN', async () => { + const { service, userFindUnique, count, findMany, groupBy } = harness(); + + const result = await service.getAppointments( + { page: 1, limit: 20 }, + 'admin-user', + UserRole.ADMIN, + ); + + expect(userFindUnique).not.toHaveBeenCalled(); + expect(count).toHaveBeenCalledWith({ where: visibleProcessScope }); + expect(findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: visibleProcessScope, + skip: 0, + take: 20, + }), + ); + expect(groupBy).toHaveBeenCalledWith( + expect.objectContaining({ where: visibleProcessScope }), + ); + expect(result.meta.pagination).toEqual({ + current_page: 1, + per_page: 20, + total: 3, + total_pages: 1, + has_next: false, + has_prev: false, + }); + }); +}); diff --git a/backend/src/features/appointments/appointments.controller.spec.ts b/backend/src/features/appointments/appointments.controller.spec.ts new file mode 100644 index 00000000..40b36fbb --- /dev/null +++ b/backend/src/features/appointments/appointments.controller.spec.ts @@ -0,0 +1,104 @@ +import { + BadRequestException, + ForbiddenException, + ValidationPipe, +} from '@nestjs/common'; +import { + AppointmentSchedulingMethod, + ProductType, + StatusAgendamento, + UserRole, +} from '@prisma/client'; +import { AppointmentsController } from './appointments.controller'; + +describe('AppointmentsController own request check', () => { + const query = { + specialist_id: '33333333-3333-4333-8333-333333333333', + product_type: ProductType.CAR, + product_id: '11111111-1111-4111-8111-111111111111', + }; + const request = { user: { id: 'customer-1', role: UserRole.CUSTOMER } }; + const snapshot = { + exists: true, + appointment_id: 'appointment-1', + process_id: 'process-1', + appointment_status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + }; + function harness(data: any = snapshot) { + const service = { + findExistingAppointment: jest.fn().mockResolvedValue(data), + }; + return { service, controller: new AppointmentsController(service as any) }; + } + + it('derives the customer exclusively from JWT and returns the minimal contract', async () => { + const { controller, service } = harness(); + expect( + await controller.checkExisting( + { ...query, client_id: 'another-customer' } as any, + request, + ), + ).toEqual({ + success: true, + message: 'Consulta realizada com sucesso', + data: snapshot, + }); + expect(service.findExistingAppointment).toHaveBeenCalledWith( + request.user.id, + query.specialist_id, + query.product_type, + query.product_id, + ); + }); + + it('returns the absent discriminant', async () => { + const { controller } = harness({ exists: false }); + expect(await controller.checkExisting(query, request)).toEqual({ + success: true, + message: 'Consulta realizada com sucesso', + data: { exists: false }, + }); + }); + + it.each([ + UserRole.SPECIALIST, + UserRole.ADMIN, + UserRole.OFFICE, + UserRole.CONSULTANT, + ])('denies %s before invoking the service', async (role) => { + const { controller, service } = harness(); + await expect( + controller.checkExisting(query, { user: { id: 'outsider', role } }), + ).rejects.toThrow(ForbiddenException); + expect(service.findExistingAppointment).not.toHaveBeenCalled(); + }); + + it('validates the query DTO and forbids client identity at the HTTP boundary', async () => { + const [queryType] = Reflect.getMetadata( + 'design:paramtypes', + AppointmentsController.prototype, + 'checkExisting', + ); + expect(queryType.name).toBe('CheckExistingAppointmentDto'); + const pipe = new ValidationPipe({ + whitelist: true, + forbidNonWhitelisted: true, + transform: true, + }); + const metadata = { type: 'query' as const, metatype: queryType }; + await expect(pipe.transform(query, metadata)).resolves.toMatchObject(query); + for (const invalid of [ + { ...query, client_id: request.user.id }, + { ...query, specialist_id: 'bad-uuid' }, + { ...query, product_type: 'OTHER' }, + { ...query, product_id: 'bad-uuid' }, + { specialist_id: query.specialist_id }, + ]) { + await expect(pipe.transform(invalid, metadata)).rejects.toThrow( + BadRequestException, + ); + } + }); +}); diff --git a/backend/src/features/appointments/appointments.controller.ts b/backend/src/features/appointments/appointments.controller.ts index c5de5426..7283ebe8 100644 --- a/backend/src/features/appointments/appointments.controller.ts +++ b/backend/src/features/appointments/appointments.controller.ts @@ -11,10 +11,14 @@ import { UseGuards, Request, HttpStatus, + ForbiddenException, + BadRequestException, + Optional, } from '@nestjs/common'; import { AppointmentsService } from './appointments.service'; import { CreatePendingAppointmentDto, + CheckExistingAppointmentDto, CreatePlatformAppointmentDto, CalendlyScheduledDto, GetAppointmentsQueryDto, @@ -25,6 +29,11 @@ import { AuthGuard } from 'src/auth/auth.guard'; import { AppointmentResponseEntity } from './entities/appointment.response'; import { UserEntity } from 'src/auth/entities/user.entity'; import { ConfirmProcessAppointmentDto } from 'src/features/processes/dto/confirm-process-appointment.dto'; +import { StatusAgendamento, UserRole } from '@prisma/client'; +import { + ActorContext, + ActorContextService, +} from 'src/shared/actor-context/actor-context.service'; /** * AppointmentsController @@ -48,7 +57,23 @@ import { ConfirmProcessAppointmentDto } from 'src/features/processes/dto/confirm @Controller('appointments') @UseGuards(AuthGuard) export class AppointmentsController { - constructor(private appointmentsService: AppointmentsService) {} + constructor( + private appointmentsService: AppointmentsService, + @Optional() private readonly actorContextService?: ActorContextService, + ) {} + + private async resolveSpecialistContext( + user: UserEntity, + targetSpecialistId?: string, + ): Promise { + if ( + !this.actorContextService || + (user.role !== UserRole.ADMIN && user.role !== UserRole.SPECIALIST) + ) { + return undefined; + } + return this.actorContextService.resolve(user, targetSpecialistId); + } /** * GET /api/appointments @@ -115,50 +140,25 @@ export class AppointmentsController { /** * GET /api/appointments/check * - * Verifica se existe agendamento SCHEDULED entre cliente e especialista para um produto específico - * Usado para impedir agendamentos duplicados e condicionalmente exibir botão de confirmação - * - * Query Parameters (todos obrigatórios): - * - client_id: UUID do cliente - * - specialist_id: UUID do especialista - * - product_type: CAR | BOAT | AIRCRAFT - * - product_id: ID numérico do produto - * - * Respostas esperadas: - * - 200 OK: Retorna null se não encontrado, ou Appointment se existe - * - 400 Bad Request: Parâmetros inválidos ou ausentes - * - 401 Unauthorized: Token JWT inválido - * - * Exemplo de resposta 200 (sem agendamento): - * { - * "success": true, - * "message": "Agendamento não encontrado", - * "data": null - * } - * - * Exemplo de resposta 200 (com agendamento): - * { - * "success": true, - * "message": "Agendamento encontrado", - * "data": { - * "id": "uuid", - * "appointment_datetime": "2024-10-10T14:00:00Z", - * "status": "SCHEDULED", - * "created_at": "2024-10-08T14:30:00Z" - * } - * } - * - * Frontend: - * - Usar este endpoint ao carregar ProductPage - * - Se retorna dados: Mostrar "Você já possui um agendamento marcado" - * - Se retorna null: Mostrar botão de confirmação normalmente + * Consulta o próprio pedido do cliente autenticado para especialista/produto. + * Aceita specialist_id, product_type e product_id; o cliente vem do JWT. + * Retorna um snapshot mínimo. O e-mail do especialista só é incluído para + * um pedido EMAIL pertencente ao próprio cliente autenticado. */ @Get('check') - async checkExisting(@Query() query: any, @Request() req: any) { - const { client_id, specialist_id, product_type, product_id } = query; + async checkExisting( + @Query() query: CheckExistingAppointmentDto, + @Request() req: any, + ) { + if (req.user.role !== UserRole.CUSTOMER) { + throw new ForbiddenException( + 'Apenas clientes podem consultar seus pedidos', + ); + } + const { specialist_id, product_type, product_id } = query; const appointment = await this.appointmentsService.findExistingAppointment( - client_id, + req.user.id, specialist_id, product_type, product_id, @@ -166,9 +166,7 @@ export class AppointmentsController { return { success: true, - message: appointment - ? 'Agendamento encontrado' - : 'Agendamento não encontrado', + message: 'Consulta realizada com sucesso', data: appointment, }; } @@ -185,68 +183,8 @@ export class AppointmentsController { /** * POST /api/appointments * - * Cria novo agendamento e auto-cria Process vinculado - * - * Request Body: - * { - * "client_id": "uuid-cliente", - * "specialist_id": "uuid-especialista", - * "product_type": "CAR", - * "product_id": 1, - * "appointment_datetime": "2024-10-10T14:00:00Z", - * "notes": "Test drive" - * } - * - * Respostas esperadas: - * - 201 Created: Agendamento criado com sucesso - * - 400 Bad Request: Dados inválidos, appointment_datetime no passado, etc - * - 409 Conflict: Conflito de horário (especialista já agendado) - * - 404 Not Found: Cliente, especialista ou produto não encontrado - * - 401 Unauthorized: Token JWT inválido - * - * Exemplo de resposta 201: - * { - * "success": true, - * "message": "Agendamento criado com sucesso", - * "data": { - * "id": "uuid", - * "appointment_datetime": "2024-10-10T14:00:00Z", - * "status": "SCHEDULED", - * "notes": "Test drive", - * "client": { "id", "name" }, - * "specialist": { "id", "name" }, - * "product": { "id": 1, "marca": "Ferrari", "modelo": "F8" }, - * "created_at": "2024-10-08T14:30:00Z" - * } - * } - * - * Exemplo de resposta 409 (conflito): - * { - * "success": false, - * "error": { - * "code": 409, - * "message": "Especialista já possui agendamento neste horário", - * "details": { - * "conflicting_appointment": { - * "id": "uuid", - * "appointment_datetime": "2024-10-10T14:00:00Z", - * "client_id": "uuid" - * }, - * "suggested_times": [ - * "2024-10-10T15:00:00Z", - * "2024-10-10T16:00:00Z", - * "2024-10-10T17:00:00Z" - * ] - * } - * } - * } - * - * Frontend: - * - Capturar 409 e exibir suggested_times ao usuário - * - Converter suggested_times de UTC para horário local para exibição - * - appointment_datetime enviado deve estar em UTC (converter do input local) - * - Após sucesso (201), redirecionare para página de confirmação - * - Auto-criação de Process é transparente (não precisa de ação adicional) + * A criação direta PLATFORM está desativada. Solicitações de reunião devem + * usar POST /appointments/pending e aguardar a confirmação do especialista. */ @Post() async create( @@ -381,16 +319,31 @@ export class AppointmentsController { @Param('id') id: string, @Body() updateAppointmentStatusDto: UpdateAppointmentStatusDto, @Request() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ) { // userId e userRole vêm do AuthGuard const userId = req.user.id; const userRole = req.user.role; + if ( + userRole === UserRole.ADMIN && + updateAppointmentStatusDto.status === StatusAgendamento.CANCELLED && + !updateAppointmentStatusDto.notes?.trim() + ) { + throw new BadRequestException( + 'Motivo é obrigatório para cancelamento administrativo.', + ); + } + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); const appointment = await this.appointmentsService.updateStatus( id, updateAppointmentStatusDto, userId, userRole, + context, ); return { @@ -405,11 +358,17 @@ export class AppointmentsController { @Param('id', new ParseUUIDPipe()) id: string, @Body() dto: RescheduleAppointmentDto, @Request() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ) { + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); const appointment = await this.appointmentsService.reschedule( id, dto.appointment_datetime, req.user.id, + context, ); return { @@ -422,23 +381,9 @@ export class AppointmentsController { /** * POST /api/appointments/pending * - * Cria um agendamento em status PENDING - * Usado quando cliente clica no link do Calendly e retorna à plataforma - * NÃO cria Process ainda - apenas registra intenção do cliente - * - * Request Body: - * { - * "client_id": "uuid-cliente", - * "specialist_id": "uuid-especialista", - * "product_type": "CAR", - * "product_id": 1, - * "notes": "Acessei o calendário do especialista" - * } - * - * Respostas: - * - 201 Created: Agendamento PENDING criado - * - 409 Conflict: Já existe agendamento PENDING ou SCHEDULED - * - 403 Forbidden: Apenas o próprio cliente pode criar + * Cria Appointment PENDING e Process SCHEDULING na mesma transação. + * EMAIL com produto exige uma proposta futura; CALENDLY não aceita horário + * do cliente. Retorna o appointment e seu process_id. */ @Post('pending') async createPending( @@ -496,13 +441,19 @@ export class AppointmentsController { @Param('id', new ParseUUIDPipe()) id: string, @Body() body: ConfirmProcessAppointmentDto, @Request() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ) { const userId = req.user.id; + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); const appointment = await this.appointmentsService.confirmPending( id, userId, body.appointment_datetime, + context, ); return { @@ -519,10 +470,30 @@ export class AppointmentsController { * Cliente ou especialista podem cancelar */ @Post('pending/:id/cancel') - async cancelPending(@Param('id') id: string, @Request() req: any) { + async cancelPending( + @Param('id') id: string, + @Request() req: any, + @Body('reason') reason?: string, + @Query('target_specialist_id') targetSpecialistId?: string, + ) { const userId = req.user.id; - const result = await this.appointmentsService.cancelPending(id, userId); + if (req.user.role === UserRole.ADMIN && !reason?.trim()) { + throw new BadRequestException( + 'Motivo é obrigatório para cancelamento administrativo.', + ); + } + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); + + const result = await this.appointmentsService.cancelPending( + id, + userId, + context, + reason, + ); return result; } diff --git a/backend/src/features/appointments/appointments.service.spec.ts b/backend/src/features/appointments/appointments.service.spec.ts index 4f756420..3b6bdf8f 100644 --- a/backend/src/features/appointments/appointments.service.spec.ts +++ b/backend/src/features/appointments/appointments.service.spec.ts @@ -1,5 +1,6 @@ import { AppointmentSchedulingMethod, + CalendlySyncStatus, Prisma, ProcessStatus, ProductCurrency, @@ -11,6 +12,7 @@ import { validate } from 'class-validator'; import { CreateAppointmentDto } from './dto/create-appointment.dto'; import { CreatePendingAppointmentDto } from './dto/create-pending-appointment.dto'; import { CreatePlatformAppointmentDto } from './dto/create-platform-appointment.dto'; +import { GetAppointmentsQueryDto } from './dto/get-appointments-query.dto'; import { AppointmentsService } from './appointments.service'; import { BadRequestException, @@ -60,9 +62,115 @@ describe('CreateAppointmentDto — seleção de produto', () => { true, ); }); + + it('validates an optional pending datetime as ISO 8601', async () => { + const dto = Object.assign(new CreatePendingAppointmentDto(), base, { + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: 'not-a-date', + }); + expect( + (await validate(dto)).some( + (error) => error.property === 'appointment_datetime', + ), + ).toBe(true); + }); + + it.each([ + '2099-01-01', + '2099-01-01T10:00:00', + '2099-01-01T10:00:00.000', + '2099-02-30T10:00:00Z', + '2099-01-01T10:00:00+25:00', + ])( + 'rejects a pending datetime without a valid time and timezone: %s', + async (datetime) => { + const dto = Object.assign(new CreatePendingAppointmentDto(), base, { + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: datetime, + }); + expect( + (await validate(dto)).some( + (error) => error.property === 'appointment_datetime', + ), + ).toBe(true); + }, + ); + + it.each([ + '2099-01-01T10:00:00.000Z', + '2099-01-01T07:00:00-03:00', + '2099-01-01T15:30:00+05:30', + '2099-01-01T07:00:00-0300', + ])('accepts an explicit pending datetime timezone: %s', async (datetime) => { + const dto = Object.assign(new CreatePendingAppointmentDto(), base, { + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: datetime, + }); + expect(await validate(dto)).toEqual([]); + }); +}); + +describe('GetAppointmentsQueryDto — limite de paginação', () => { + it('rejeita limit maior que 100', async () => { + const dto = Object.assign(new GetAppointmentsQueryDto(), { limit: 101 }); + + const errors = await validate(dto); + + expect(errors).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + property: 'limit', + constraints: expect.objectContaining({ max: expect.any(String) }), + }), + ]), + ); + }); +}); + +describe('AppointmentsService — processo removido', () => { + it('exclui agendamentos vinculados da lista, contagem e resumo', async () => { + const prisma = { + appointment: { + count: jest.fn().mockResolvedValue(0), + findMany: jest.fn().mockResolvedValue([]), + groupBy: jest.fn().mockResolvedValue([]), + }, + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + await service.getAppointments( + {} as GetAppointmentsQueryDto, + 'specialist-1', + UserRole.SPECIALIST, + ); + + const expectedWhere = { + OR: [ + { process: { is: null } }, + { process: { is: { removed_at: null } } }, + ], + AND: [ + { + OR: [ + { specialist_id: 'specialist-1' }, + { client_id: 'specialist-1' }, + ], + }, + ], + }; + expect(prisma.appointment.count).toHaveBeenCalledWith({ + where: expectedWhere, + }); + expect(prisma.appointment.findMany).toHaveBeenCalledWith( + expect.objectContaining({ where: expectedWhere }), + ); + expect(prisma.appointment.groupBy).toHaveBeenCalledWith( + expect.objectContaining({ where: expectedWhere }), + ); + }); }); -describe('AppointmentsService.create — associação e atomicidade', () => { +describe('AppointmentsService.createPending — associação e atomicidade', () => { const client = { id: 'client-1', name: 'Cliente', @@ -91,16 +199,22 @@ describe('AppointmentsService.create — associação e atomicidade', () => { product_type: ProductType.CAR, product_id: activeProduct.id, appointment_datetime: '2099-01-01T10:00:00.000Z', - } as CreateAppointmentDto; + scheduling_method: AppointmentSchedulingMethod.EMAIL, + } as CreatePendingAppointmentDto; function harness(options: { transactionalProduct?: typeof activeProduct; processFailure?: Error; + historyFailure?: Error; + calendlyUrl?: string | null; + connectionActive?: boolean; + existingProcess?: any; }) { const storedAppointments: any[] = []; + const storedProcesses: any[] = []; const appointmentCreate = jest.fn(async ({ data }) => { const appointment = { - id: 'appointment-1', + id: `appointment-${storedAppointments.length + 1}`, ...data, created_at: new Date(), updated_at: new Date(), @@ -108,13 +222,30 @@ describe('AppointmentsService.create — associação e atomicidade', () => { storedAppointments.push(appointment); return appointment; }); - const processCreate = jest.fn(async () => { + const processCreate = jest.fn(async ({ data }) => { if (options.processFailure) throw options.processFailure; - return { id: 'process-1' }; + const process = { + id: `process-${storedProcesses.length + 1}`, + removed_at: null, + ...data, + }; + storedProcesses.push(process); + return process; }); - const historyCreate = jest.fn().mockResolvedValue({}); + const historyCreate = jest.fn(async () => { + if (options.historyFailure) throw options.historyFailure; + return {}; + }); + const selectedSpecialist = { + ...specialist, + calendly_url: options.calendlyUrl ?? null, + calendly_connection: + options.connectionActive === undefined + ? null + : { is_active: options.connectionActive }, + }; const userFindUnique = jest.fn(async ({ where }) => - where.id === client.id ? client : specialist, + where.id === client.id ? client : selectedSpecialist, ); const rootProductFindUnique = jest.fn().mockResolvedValue(activeProduct); const rootAppointmentCreate = jest.fn(); @@ -134,7 +265,7 @@ describe('AppointmentsService.create — associação e atomicidade', () => { create: appointmentCreate, }, process: { - findFirst: jest.fn().mockResolvedValue(null), + findFirst: jest.fn().mockResolvedValue(options.existingProcess ?? null), create: processCreate, }, processStatusHistory: { create: historyCreate }, @@ -151,10 +282,12 @@ describe('AppointmentsService.create — associação e atomicidade', () => { process: { create: rootProcessCreate }, $transaction: jest.fn(async (callback) => { const before = storedAppointments.length; + const beforeProcesses = storedProcesses.length; try { return await callback(tx); } catch (error) { storedAppointments.splice(before); + storedProcesses.splice(beforeProcesses); throw error; } }), @@ -175,6 +308,7 @@ describe('AppointmentsService.create — associação e atomicidade', () => { rootAppointmentCreate, rootProcessCreate, storedAppointments, + storedProcesses, }; } @@ -196,7 +330,7 @@ describe('AppointmentsService.create — associação e atomicidade', () => { ); await expect( - service.create(dto as any, client.id, UserRole.CUSTOMER), + service.createPending(dto, client.id, UserRole.CUSTOMER), ).rejects.toThrow(expectedError); expect(prisma.$transaction).toHaveBeenCalledTimes(1); expect(tx.car.findUnique).toHaveBeenCalled(); @@ -218,7 +352,7 @@ describe('AppointmentsService.create — associação e atomicidade', () => { }); await expect( - service.create(dto as any, client.id, UserRole.CUSTOMER), + service.createPending(dto, client.id, UserRole.CUSTOMER), ).rejects.toBe(processFailure); expect(prisma.$transaction).toHaveBeenCalledTimes(1); expect(storedAppointments).toHaveLength(0); @@ -227,13 +361,13 @@ describe('AppointmentsService.create — associação e atomicidade', () => { }); it.each([UserRole.SPECIALIST, UserRole.CONSULTANT, UserRole.ADMIN])( - 'rejects direct scheduling by %s', + 'rejects pending requests by %s', async (role) => { const { service, appointmentCreate } = harness({}); - await expect( - (service.create as any)(dto, client.id, role), - ).rejects.toThrow(ForbiddenException); + await expect(service.createPending(dto, client.id, role)).rejects.toThrow( + ForbiddenException, + ); expect(appointmentCreate).not.toHaveBeenCalled(); }, ); @@ -242,24 +376,34 @@ describe('AppointmentsService.create — associação e atomicidade', () => { const { service, appointmentCreate } = harness({}); await expect( - (service.create as any)(dto, 'another-client', UserRole.CUSTOMER), + service.createPending(dto, 'another-client', UserRole.CUSTOMER), ).rejects.toThrow(ForbiddenException); expect(appointmentCreate).not.toHaveBeenCalled(); }); - it('stores direct scheduling as SCHEDULED and PLATFORM', async () => { + it('stores the proposed date as PENDING/EMAIL and returns the process ID', async () => { const { service, appointmentCreate, historyCreate } = harness({}); - await (service.create as any)(dto, client.id, UserRole.CUSTOMER); + const result = await service.createPending( + dto, + client.id, + UserRole.CUSTOMER, + ); expect(appointmentCreate).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ - status: StatusAgendamento.SCHEDULED, - scheduling_method: AppointmentSchedulingMethod.PLATFORM, + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date(dto.appointment_datetime!), }), }), ); + expect(result).toMatchObject({ + id: 'appointment-1', + process_id: 'process-1', + specialist_contact_email: specialist.email, + }); expect(historyCreate).toHaveBeenCalledWith({ data: expect.objectContaining({ processId: 'process-1', @@ -269,30 +413,116 @@ describe('AppointmentsService.create — associação e atomicidade', () => { }); }); - it('serializa a verificação e a inserção do horário por especialista', async () => { + it.each([false, true])( + 'checks the new request after rejection regardless of record order (reverse=%s)', + async (reverse) => { + const { service, prisma, tx, storedAppointments, storedProcesses } = + harness({}); + const matches = (row: any, where: any) => + Object.entries(where).every(([key, value]) => + value !== null && typeof value === 'object' && 'in' in value + ? (value.in as unknown[]).includes(row[key]) + : row[key] === value, + ); + tx.process.findFirst.mockImplementation( + async ({ where }) => + storedProcesses.find((row) => matches(row, where)) ?? null, + ); + prisma.appointment.findFirst.mockImplementation(async ({ where }) => { + const { process: processFilter, ...appointmentFilter } = where; + const rows = reverse + ? [...storedAppointments].reverse() + : storedAppointments; + for (const appointment of rows) { + const process = storedProcesses.find( + (row) => row.appointment_id === appointment.id, + ); + if ( + matches(appointment, appointmentFilter) && + process && + matches(process, processFilter.is) + ) { + return { ...appointment, process }; + } + } + return null; + }); + + await service.createPending(dto, client.id, UserRole.CUSTOMER); + // Rejecting a process preserves the original PENDING appointment. + storedProcesses[0].status = ProcessStatus.REJECTED; + const replacement = await service.createPending( + dto, + client.id, + UserRole.CUSTOMER, + ); + + expect( + await service.findExistingAppointment( + client.id, + specialist.id, + ProductType.CAR, + activeProduct.id, + ), + ).toEqual({ + exists: true, + appointment_id: replacement.id, + process_id: replacement.process_id, + appointment_status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date(dto.appointment_datetime!), + }); + + storedProcesses[1].status = ProcessStatus.REJECTED; + expect( + await service.findExistingAppointment( + client.id, + specialist.id, + ProductType.CAR, + activeProduct.id, + ), + ).toEqual({ exists: false }); + }, + ); + + it.each([ + '2099-01-01T07:00:00-03:00', + '2099-01-01T15:30:00+05:30', + '2099-01-01T07:00:00-0300', + ])( + 'persists the exact instant of a product EMAIL proposal with offset %s', + async (datetime) => { + const { service } = harness({}); + await expect( + service.createPending( + { ...dto, appointment_datetime: datetime }, + client.id, + UserRole.CUSTOMER, + ), + ).resolves.toMatchObject({ + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + status: StatusAgendamento.PENDING, + }); + }, + ); + + it('does not lock or check schedule availability for an EMAIL proposal', async () => { const { service, tx } = harness({}); - await service.create(dto as any, client.id, UserRole.CUSTOMER); + await service.createPending(dto, client.id, UserRole.CUSTOMER); - expect(tx.$queryRaw).toHaveBeenCalledWith( - expect.anything(), + expect(tx.$queryRaw.mock.calls.map((call) => call[1])).not.toContain( 'appointment-schedule:specialist-1', ); - expect(tx.$queryRaw.mock.invocationCallOrder[0]).toBeLessThan( - tx.appointment.findFirst.mock.invocationCallOrder[0], - ); + expect(tx.appointment.findFirst).not.toHaveBeenCalled(); }); - it('rejects platform scheduling when no datetime is supplied', async () => { + it('requires a date for an EMAIL product request', async () => { const { service, tx, appointmentCreate } = harness({}); const withoutDate = { ...dto, appointment_datetime: undefined }; await expect( - (service.create as any)( - withoutDate as CreateAppointmentDto, - client.id, - UserRole.CUSTOMER, - ), + service.createPending(withoutDate, client.id, UserRole.CUSTOMER), ).rejects.toThrow(BadRequestException); expect(tx.appointment.findFirst).not.toHaveBeenCalled(); @@ -302,164 +532,561 @@ describe('AppointmentsService.create — associação e atomicidade', () => { it('serializa e repete a deduplicação do processo antes de criá-lo', async () => { const { service, tx } = harness({}); - await service.create(dto as any, client.id, UserRole.CUSTOMER); + await service.createPending(dto, client.id, UserRole.CUSTOMER); expect(tx.$queryRaw).toHaveBeenCalledWith( expect.anything(), 'process-dedup:client-1:specialist-1:CAR:product-1', ); - expect(tx.process.findFirst).toHaveBeenCalledWith({ - where: expect.objectContaining({ car_id: 'product-1' }), - }); + expect(tx.process.findFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ car_id: 'product-1' }), + }), + ); expect(tx.process.findFirst.mock.invocationCallOrder[0]).toBeLessThan( tx.process.create.mock.invocationCallOrder[0], ); }); -}); -describe('AppointmentsService.createPending — integridade das partes', () => { - it('rejeita usuário que não seja CUSTOMER antes de consultar o banco', async () => { - const prisma = { - user: { findUnique: jest.fn() }, - } as any; - const service = new AppointmentsService(prisma, {} as any, {} as any); + it.each([ + 'not-a-date', + '2099-01-01', + '2099-01-01T10:00:00', + '2099-01-01T10:00:00.000', + '2099-02-30T10:00:00Z', + '2099-01-01T10:00:00+25:00', + '2000-01-01T00:00:00.000Z', + '2026-10-14T12:00:00.000Z', + '2026-10-14T09:00:00-03:00', + ])( + 'rejects an invalid, ambiguous, past or current product EMAIL date %s before writes', + async (datetime) => { + jest.useFakeTimers().setSystemTime(new Date('2026-10-14T12:00:00.000Z')); + try { + const { + service, + prisma, + appointmentCreate, + processCreate, + historyCreate, + } = harness({}); + await expect( + service.createPending( + { ...dto, appointment_datetime: datetime }, + client.id, + UserRole.CUSTOMER, + ), + ).rejects.toThrow(BadRequestException); + expect(prisma.user.findUnique).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + expect(appointmentCreate).not.toHaveBeenCalled(); + expect(processCreate).not.toHaveBeenCalled(); + expect(historyCreate).not.toHaveBeenCalled(); + } finally { + jest.useRealTimers(); + } + }, + ); + it('rolls back appointment and process when history insertion fails', async () => { + const historyFailure = new Error('history insert failed'); + const { service, storedAppointments, storedProcesses } = harness({ + historyFailure, + }); await expect( - service.createPending( - { - client_id: 'specialist-1', - specialist_id: 'other-specialist-1', - scheduling_method: AppointmentSchedulingMethod.EMAIL, - } as CreatePendingAppointmentDto, - 'specialist-1', - UserRole.SPECIALIST, - ), - ).rejects.toThrow(ForbiddenException); - expect(prisma.user.findUnique).not.toHaveBeenCalled(); + service.createPending(dto, client.id, UserRole.CUSTOMER), + ).rejects.toBe(historyFailure); + expect(storedAppointments).toHaveLength(0); + expect(storedProcesses).toHaveLength(0); }); - it('rejeita horário pré-preenchido em uma solicitação por e-mail', async () => { - const prisma = { - user: { findUnique: jest.fn() }, - } as any; - const service = new AppointmentsService(prisma, {} as any, {} as any); + it.each([ + [null, false, false], + ['https://calendly.com/specialist/meeting', false, false], + [null, true, false], + ['http://calendly.com/specialist/meeting', true, false], + ['https://calendly.com.evil.test/meeting', true, false], + ['https://calendly.com/specialist/meeting', true, true], + ])( + 'enforces reciprocal method capability for URL %s and connection %s', + async (calendlyUrl, connectionActive, available) => { + for (const method of [ + AppointmentSchedulingMethod.EMAIL, + AppointmentSchedulingMethod.CALENDLY, + ]) { + const { service, appointmentCreate } = harness({ + calendlyUrl, + connectionActive, + }); + const input = { + ...dto, + scheduling_method: method, + appointment_datetime: + method === AppointmentSchedulingMethod.EMAIL + ? dto.appointment_datetime + : undefined, + }; + const creation = service.createPending( + input, + client.id, + UserRole.CUSTOMER, + ); + if ((method === AppointmentSchedulingMethod.CALENDLY) === available) { + await expect(creation).resolves.toMatchObject({ + status: StatusAgendamento.PENDING, + scheduling_method: method, + process_id: 'process-1', + }); + } else { + const error = await creation.catch((caught) => caught); + expect(error).toBeInstanceOf(ConflictException); + expect(error.getResponse()).toEqual({ + success: false, + error: { + code: + method === AppointmentSchedulingMethod.CALENDLY + ? 'CALENDLY_UNAVAILABLE' + : 'EMAIL_FLOW_UNAVAILABLE', + message: expect.any(String), + }, + }); + expect(appointmentCreate).not.toHaveBeenCalled(); + } + } + }, + ); + it('preserves optional date EMAIL consultancy even with Calendly available', async () => { + const { service, appointmentCreate } = harness({ + calendlyUrl: 'https://calendly.com/specialist/meeting', + connectionActive: true, + }); await expect( service.createPending( { - client_id: 'client-1', - specialist_id: 'specialist-1', + client_id: client.id, + specialist_id: specialist.id, scheduling_method: AppointmentSchedulingMethod.EMAIL, - appointment_datetime: '2099-01-01T10:00:00.000Z', - } as CreatePendingAppointmentDto, - 'client-1', + }, + client.id, UserRole.CUSTOMER, ), - ).rejects.toThrow(BadRequestException); - expect(prisma.user.findUnique).not.toHaveBeenCalled(); - }); - - it('não permite que CUSTOMER se informe como especialista', async () => { - const customer = { - id: '22222222-2222-4222-8222-222222222222', - name: 'Cliente', - role: UserRole.CUSTOMER, - speciality: null, - }; - const prisma = { - user: { findUnique: jest.fn().mockResolvedValue(customer) }, - appointment: { findFirst: jest.fn().mockResolvedValue(null) }, - $transaction: jest.fn(async (callback: any) => - callback({ - user: { findUnique: jest.fn().mockResolvedValue(customer) }, - car: { findUnique: jest.fn() }, - boat: { findUnique: jest.fn() }, - aircraft: { findUnique: jest.fn() }, + ).resolves.toMatchObject({ + process_id: 'process-1', + appointment_datetime: null, + specialist_contact_email: specialist.email, + }); + expect(appointmentCreate).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: null, }), - ), - } as any; - const service = new AppointmentsService(prisma, {} as any, {} as any); - - await expect( - service.createPending( - { - client_id: customer.id, - specialist_id: customer.id, - } as CreateAppointmentDto, - customer.id, - UserRole.CUSTOMER, - ), - ).rejects.toThrow(BadRequestException); + }), + ); }); - it('preserva o bloqueio preliminar de agendamento com produto', async () => { - const client = { - id: 'client-1', - name: 'Client', - role: UserRole.CUSTOMER, - }; - const specialist = { - id: 'specialist-1', - name: 'Specialist', - role: UserRole.SPECIALIST, - speciality: ProductType.CAR, - }; - const existing = { - id: 'existing-product-appointment', - status: StatusAgendamento.PENDING, - }; - const prisma = { - user: { - findUnique: jest - .fn() - .mockResolvedValueOnce(client) - .mockResolvedValueOnce(specialist), - }, - appointment: { findFirst: jest.fn().mockResolvedValue(existing) }, - $transaction: jest.fn(), - } as any; - const service = new AppointmentsService(prisma, {} as any, {} as any); - + it('persists an optional future consultancy EMAIL date exactly under the schedule lock', async () => { + const { service, tx } = harness({}); + const datetime = '2099-01-01T07:00:00-03:00'; await expect( service.createPending( { client_id: client.id, specialist_id: specialist.id, - product_type: ProductType.CAR, - product_id: 'product-1', + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: datetime, }, client.id, UserRole.CUSTOMER, ), - ).rejects.toThrow(ConflictException); - - expect(prisma.$transaction).not.toHaveBeenCalled(); + ).resolves.toMatchObject({ + appointment_datetime: new Date(datetime), + status: StatusAgendamento.PENDING, + process_id: 'process-1', + }); + expect(tx.$queryRaw).toHaveBeenCalledWith( + expect.anything(), + 'appointment-schedule:specialist-1', + ); + expect(tx.$queryRaw.mock.calls.map((call) => call[1])).toEqual([ + 'appointment-schedule:specialist-1', + 'process-dedup:client-1:specialist-1:CONSULTANCY:none', + ]); + expect(tx.appointment.findFirst).toHaveBeenCalledTimes(2); }); it.each([ - [undefined, AppointmentSchedulingMethod.CALENDLY], - [AppointmentSchedulingMethod.EMAIL, AppointmentSchedulingMethod.EMAIL], + [ + 'appointment concluído', + { + id: 'completed-appointment', + client_id: client.id, + status: StatusAgendamento.COMPLETED, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date('2098-01-01T10:00:00.000Z'), + }, + ], + ['processo legado sem appointment', null], ])( - 'permite consultoria com processo existente e persiste a origem %s como %s', - async (inputMethod, expectedMethod) => { - const client = { - id: 'client-1', - name: 'Client', - role: UserRole.CUSTOMER, - }; - const specialist = { - id: 'specialist-1', - name: 'Specialist', - role: UserRole.SPECIALIST, - speciality: ProductType.CAR, - }; - const appointmentFindFirst = jest.fn().mockResolvedValue(null); - const processFindFirst = jest.fn().mockResolvedValue({ - id: 'active-process-1', - status: ProcessStatus.SCHEDULING, + 'rejeita nova consultoria diante de processo ativo com %s', + async (_label, appointment) => { + const { service, appointmentCreate } = harness({ + existingProcess: { + id: 'active-consultancy', + client_id: client.id, + appointment, + }, }); - const tx = { - $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + + await expect( + service.createPending( + { + client_id: client.id, + specialist_id: specialist.id, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + }, + client.id, + UserRole.CUSTOMER, + ), + ).rejects.toThrow(ConflictException); + expect(appointmentCreate).not.toHaveBeenCalled(); + }, + ); + + it.each([ + 'not-a-date', + '01/01/2099', + '2099-01-01', + '2099-01-01T10:00:00', + '2099-01-01T10:00:00.000', + '2000-01-01T00:00:00.000Z', + '2026-10-14T12:00:00.000Z', + ])( + 'rejects invalid, non-ISO, past or current optional consultancy date %s before writes', + async (datetime) => { + jest.useFakeTimers().setSystemTime(new Date('2026-10-14T12:00:00.000Z')); + try { + const { service, appointmentCreate, processCreate } = harness({}); + await expect( + service.createPending( + { + client_id: client.id, + specialist_id: specialist.id, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: datetime, + }, + client.id, + UserRole.CUSTOMER, + ), + ).rejects.toThrow(BadRequestException); + expect(appointmentCreate).not.toHaveBeenCalled(); + expect(processCreate).not.toHaveBeenCalled(); + } finally { + jest.useRealTimers(); + } + }, + ); + + it('returns ACTIVE_PROCESS_EXISTS with the owned proposal after acquiring the dedup lock', async () => { + const proposedDate = new Date(dto.appointment_datetime!); + const { service, prisma, tx, appointmentCreate } = harness({ + existingProcess: { + id: 'process-existing', + client_id: client.id, + specialist: { email: specialist.email }, + appointment: { + id: 'appointment-existing', + client_id: client.id, + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: proposedDate, + }, + }, + }); + const error = await service + .createPending(dto, client.id, UserRole.CUSTOMER) + .catch((caught) => caught); + expect(error).toBeInstanceOf(ConflictException); + expect(error.getResponse().error.details.existing_request).toEqual({ + process_id: 'process-existing', + appointment_id: 'appointment-existing', + appointment_status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: proposedDate, + specialist_contact_email: specialist.email, + }); + expect(prisma.appointment.findFirst).not.toHaveBeenCalled(); + expect(tx.$queryRaw.mock.invocationCallOrder[1]).toBeLessThan( + tx.process.findFirst.mock.invocationCallOrder[0], + ); + expect(appointmentCreate).not.toHaveBeenCalled(); + }); + + it.each([ + UserRole.CUSTOMER, + UserRole.SPECIALIST, + UserRole.ADMIN, + UserRole.CONSULTANT, + ])( + 'rejects the direct PLATFORM bypass for %s before any database access', + async (role) => { + const { service, prisma, tx, appointmentCreate } = harness({}); + const error = await service + .create(dto as any, client.id, role) + .catch((caught) => caught); + expect(error).toBeInstanceOf(ForbiddenException); + expect(error.getResponse()).toEqual({ + success: false, + error: { code: 403, message: expect.any(String) }, + }); + expect(prisma.user.findUnique).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + expect(tx.$queryRaw).not.toHaveBeenCalled(); + expect(appointmentCreate).not.toHaveBeenCalled(); + }, + ); +}); + +describe('AppointmentsService.findExistingAppointment — own minimal projection', () => { + const ownedAppointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + product_type: ProductType.CAR, + product_id: 'car-1', + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + process: { id: 'process-1', client_id: 'client-1' }, + client: { + id: 'client-1', + name: 'Private Client', + email: 'private@example.com', + }, + specialist: { + id: 'specialist-1', + name: 'Specialist', + email: 'specialist@example.com', + }, + notes: 'private-notes', + created_at: new Date(), + updated_at: new Date(), + }; + function harness(appointment: any) { + const prisma = { + appointment: { findFirst: jest.fn().mockResolvedValue(appointment) }, + car: { findUnique: jest.fn().mockResolvedValue({ id: 'car-1' }) }, + } as any; + return { + prisma, + service: new AppointmentsService(prisma, {} as any, {} as any), + }; + } + it.each([ + ownedAppointment, + { + ...ownedAppointment, + scheduling_method: null, + appointment_datetime: null, + }, + ])( + 'returns only the owned discriminator and supports legacy date/method nulls', + async (appointment) => { + const { prisma, service } = harness(appointment); + expect( + await service.findExistingAppointment( + 'client-1', + 'specialist-1', + ProductType.CAR, + 'car-1', + ), + ).toEqual({ + exists: true, + appointment_id: appointment.id, + process_id: 'process-1', + appointment_status: appointment.status, + scheduling_method: appointment.scheduling_method, + appointment_datetime: appointment.appointment_datetime, + ...(appointment.scheduling_method === AppointmentSchedulingMethod.EMAIL + ? { specialist_contact_email: 'specialist@example.com' } + : {}), + }); + 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, + ], + }, + }, + }, + }), + 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 } }, + }, + }); + expect(prisma.car.findUnique).not.toHaveBeenCalled(); + }, + ); + it('não expõe contato do especialista para pedido CALENDLY', async () => { + const { service } = harness({ + ...ownedAppointment, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + }); + + const result = await service.findExistingAppointment( + 'client-1', + 'specialist-1', + ProductType.CAR, + 'car-1', + ); + + expect(result).not.toHaveProperty('specialist_contact_email'); + }); + it.each([ + null, + { ...ownedAppointment, client_id: 'another-client' }, + { ...ownedAppointment, process: null }, + { + ...ownedAppointment, + process: { id: 'private-process', client_id: 'another-client' }, + }, + ])( + 'fails closed for missing or unowned appointment/process %o', + async (appointment) => { + const { service } = harness(appointment); + expect( + await service.findExistingAppointment( + 'client-1', + 'specialist-1', + ProductType.CAR, + 'car-1', + ), + ).toEqual({ exists: false }); + }, + ); +}); + +describe('AppointmentsService.createPending — integridade das partes', () => { + it('rejeita usuário que não seja CUSTOMER antes de consultar o banco', async () => { + const prisma = { + user: { findUnique: jest.fn() }, + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + await expect( + service.createPending( + { + client_id: 'specialist-1', + specialist_id: 'other-specialist-1', + scheduling_method: AppointmentSchedulingMethod.EMAIL, + } as CreatePendingAppointmentDto, + 'specialist-1', + UserRole.SPECIALIST, + ), + ).rejects.toThrow(ForbiddenException); + expect(prisma.user.findUnique).not.toHaveBeenCalled(); + }); + + it('rejeita horário enviado pelo cliente para Calendly', async () => { + const prisma = { + user: { findUnique: jest.fn() }, + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + await expect( + service.createPending( + { + client_id: 'client-1', + specialist_id: 'specialist-1', + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + appointment_datetime: '2099-01-01T10:00:00.000Z', + } as CreatePendingAppointmentDto, + 'client-1', + UserRole.CUSTOMER, + ), + ).rejects.toThrow(BadRequestException); + expect(prisma.user.findUnique).not.toHaveBeenCalled(); + }); + + it('não permite que CUSTOMER se informe como especialista', async () => { + const customer = { + id: '22222222-2222-4222-8222-222222222222', + name: 'Cliente', + role: UserRole.CUSTOMER, + speciality: null, + }; + const prisma = { + user: { findUnique: jest.fn().mockResolvedValue(customer) }, + appointment: { findFirst: jest.fn().mockResolvedValue(null) }, + $transaction: jest.fn(async (callback: any) => + callback({ + user: { findUnique: jest.fn().mockResolvedValue(customer) }, + car: { findUnique: jest.fn() }, + boat: { findUnique: jest.fn() }, + aircraft: { findUnique: jest.fn() }, + }), + ), + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + await expect( + service.createPending( + { + client_id: customer.id, + specialist_id: customer.id, + } as CreateAppointmentDto, + customer.id, + UserRole.CUSTOMER, + ), + ).rejects.toThrow(BadRequestException); + }); + + it.each([undefined, AppointmentSchedulingMethod.EMAIL])( + 'bloqueia consultoria com processo ativo para a origem %s', + async (inputMethod) => { + const client = { + id: 'client-1', + name: 'Client', + role: UserRole.CUSTOMER, + }; + const specialist = { + id: 'specialist-1', + name: 'Specialist', + role: UserRole.SPECIALIST, + speciality: ProductType.CAR, + calendly_url: 'https://calendly.com/specialist/meeting', + calendly_connection: { is_active: true }, + }; + const appointmentFindFirst = jest.fn().mockResolvedValue(null); + const processFindFirst = jest.fn().mockResolvedValue({ + id: 'active-process-1', + status: ProcessStatus.SCHEDULING, + }); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), user: { findUnique: jest.fn().mockResolvedValue(specialist) }, car: { findUnique: jest.fn() }, boat: { findUnique: jest.fn() }, @@ -492,34 +1119,18 @@ describe('AppointmentsService.createPending — integridade das partes', () => { client.id, UserRole.CUSTOMER, ), - ).rejects.toThrow('stop after checks'); + ).rejects.toThrow(ConflictException); expect(tx.$queryRaw).toHaveBeenCalledWith( expect.anything(), 'process-dedup:client-1:specialist-1:CONSULTANCY:none', ); - expect(processFindFirst).not.toHaveBeenCalled(); - expect(appointmentFindFirst).toHaveBeenCalledWith({ - where: expect.objectContaining({ - client_id: client.id, - specialist_id: specialist.id, - product_type: null, - product_id: null, - status: { - in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], - }, - }), - }); + expect(processFindFirst).toHaveBeenCalled(); + expect(appointmentFindFirst).not.toHaveBeenCalled(); expect(tx.$queryRaw.mock.invocationCallOrder[0]).toBeLessThan( - appointmentFindFirst.mock.invocationCallOrder[0], - ); - expect(tx.appointment.create).toHaveBeenCalledWith( - expect.objectContaining({ - data: expect.objectContaining({ - scheduling_method: expectedMethod, - }), - }), + processFindFirst.mock.invocationCallOrder[0], ); + expect(tx.appointment.create).not.toHaveBeenCalled(); }, ); @@ -582,56 +1193,186 @@ describe('AppointmentsService.createPending — integridade das partes', () => { }); describe('AppointmentsService.updateStatus — snapshot da negociação', () => { - it('rejeita a transição quando perde a reivindicação concorrente do appointment', async () => { - const appointment = { - id: 'appointment-1', - client_id: 'client-1', - specialist_id: 'specialist-1', - product_type: null, - product_id: null, - status: StatusAgendamento.SCHEDULED, - appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), - notes: null, - updated_at: new Date('2099-01-01T00:00:00.000Z'), - client: { id: 'client-1' }, - specialist: { id: 'specialist-1' }, - process: null, - }; - const appointmentUpdate = jest.fn().mockResolvedValue({ - ...appointment, - status: StatusAgendamento.COMPLETED, - }); - const tx = { - $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), - appointment: { - findUnique: jest.fn().mockResolvedValue(appointment), - update: appointmentUpdate, - updateMany: jest.fn().mockResolvedValue({ count: 0 }), - }, - }; - const prisma = { - appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, - $transaction: jest.fn(async (callback: any) => callback(tx)), - } as any; - const service = new AppointmentsService(prisma, {} as any, {} as any); + it.each([ProcessStatus.NEGOTIATION, ProcessStatus.DOCUMENTATION])( + 'rejeita cancelamento quando o Process já avançou para %s antes de iniciar a transação', + async (processStatus) => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.SCHEDULED, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + process: { id: 'process-1', status: processStatus }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(), + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); - await expect( - service.updateStatus( - appointment.id, - { status: StatusAgendamento.COMPLETED }, - appointment.specialist_id, - UserRole.SPECIALIST, - ), - ).rejects.toThrow(ConflictException); - expect(tx.appointment.updateMany).toHaveBeenCalledTimes(1); - expect(appointmentUpdate).not.toHaveBeenCalled(); - }); + await expect( + service.updateStatus( + appointment.id, + { status: StatusAgendamento.CANCELLED }, + appointment.client_id, + UserRole.CUSTOMER, + ), + ).rejects.toThrow( + 'Não é possível cancelar uma reunião cujo processo já avançou', + ); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }, + ); - it('impede o cliente de concluir o agendamento e avançar a negociação', async () => { - const appointment = { - id: 'appointment-1', - client_id: 'client-1', - specialist_id: 'specialist-1', + it.each([StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED])( + 'cancela %s e remove o Process SCHEDULING na mesma transação', + async (currentStatus) => { + const client = { + id: 'client-1', + name: 'Cliente', + surname: 'Teste', + email: 'cliente@example.com', + }; + const specialist = { + id: 'specialist-1', + name: 'Especialista', + surname: 'Teste', + email: 'especialista@example.com', + speciality: ProductType.CAR, + }; + const process = { + id: 'process-1', + status: ProcessStatus.SCHEDULING, + }; + const appointment = { + id: 'appointment-1', + client_id: client.id, + specialist_id: specialist.id, + product_type: null, + product_id: null, + status: currentStatus, + notes: null, + appointment_datetime: + currentStatus === StatusAgendamento.SCHEDULED + ? new Date('2099-01-01T10:00:00.000Z') + : null, + created_at: new Date('2026-01-01T00:00:00.000Z'), + updated_at: new Date('2026-01-01T00:00:00.000Z'), + client, + specialist, + process, + }; + const updatedAppointment = { + ...appointment, + status: StatusAgendamento.CANCELLED, + process: null, + }; + const deleteHistory = jest.fn().mockResolvedValue({ count: 1 }); + const deleteProcess = jest.fn().mockResolvedValue({ count: 1 }); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + findUniqueOrThrow: jest.fn().mockResolvedValue(updatedAppointment), + }, + process: { deleteMany: deleteProcess }, + processStatusHistory: { deleteMany: deleteHistory }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + const result = await service.updateStatus( + appointment.id, + { status: StatusAgendamento.CANCELLED }, + appointment.client_id, + UserRole.CUSTOMER, + ); + + expect(tx.appointment.updateMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ + id: appointment.id, + status: currentStatus, + updated_at: appointment.updated_at, + }), + data: expect.objectContaining({ + status: StatusAgendamento.CANCELLED, + }), + }), + ); + expect(deleteHistory).toHaveBeenCalledWith({ + where: { processId: process.id }, + }); + expect(deleteProcess).toHaveBeenCalledWith({ + where: { + id: process.id, + status: ProcessStatus.SCHEDULING, + }, + }); + expect(deleteHistory.mock.invocationCallOrder[0]).toBeLessThan( + deleteProcess.mock.invocationCallOrder[0], + ); + expect(result.status).toBe(StatusAgendamento.CANCELLED); + }, + ); + + it('rejeita a transição quando perde a reivindicação concorrente do appointment', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + product_type: null, + product_id: null, + status: StatusAgendamento.SCHEDULED, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + notes: null, + updated_at: new Date('2099-01-01T00:00:00.000Z'), + client: { id: 'client-1' }, + specialist: { id: 'specialist-1' }, + process: { + id: 'process-1', + meeting_session: { ended_at: new Date('2099-01-01T11:00:00.000Z') }, + }, + }; + const appointmentUpdate = jest.fn().mockResolvedValue({ + ...appointment, + status: StatusAgendamento.COMPLETED, + }); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + update: appointmentUpdate, + updateMany: jest.fn().mockResolvedValue({ count: 0 }), + }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(async (callback: any) => callback(tx)), + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + await expect( + service.updateStatus( + appointment.id, + { status: StatusAgendamento.COMPLETED }, + appointment.specialist_id, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(ConflictException); + expect(tx.appointment.updateMany).toHaveBeenCalledTimes(1); + expect(appointmentUpdate).not.toHaveBeenCalled(); + }); + + it('impede o cliente de concluir o agendamento e avançar a negociação', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', status: StatusAgendamento.SCHEDULED, appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), process: { id: 'process-1', status: ProcessStatus.SCHEDULING }, @@ -655,6 +1396,36 @@ describe('AppointmentsService.updateStatus — snapshot da negociação', () => expect(prisma.$transaction).not.toHaveBeenCalled(); }); + it('impede a rota genérica de concluir sem reunião encerrada', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.SCHEDULED, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + process: { + id: 'process-1', + status: ProcessStatus.SCHEDULING, + meeting_session: null, + }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(), + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + await expect( + service.updateStatus( + appointment.id, + { status: StatusAgendamento.COMPLETED }, + appointment.specialist_id, + UserRole.SPECIALIST, + ), + ).rejects.toThrow('Conclua a reunião pelo fluxo de conversa'); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + it('impede que a rota genérica confirme ou reabra um agendamento', async () => { const appointment = { id: 'appointment-1', @@ -706,6 +1477,7 @@ describe('AppointmentsService.updateStatus — snapshot da negociação', () => }; const process = { id: 'process-1', + meeting_session: { ended_at: new Date('2026-01-01T11:00:00.000Z') }, status: ProcessStatus.SCHEDULING, notes: null, product_type: ProductType.CAR, @@ -852,6 +1624,7 @@ describe('AppointmentsService.updateStatus — snapshot da negociação', () => }; const process = { id: 'process-1', + meeting_session: { ended_at: new Date('2026-01-01T11:00:00.000Z') }, status: ProcessStatus.SCHEDULING, notes: null, product_type: ProductType.CAR, @@ -996,7 +1769,7 @@ describe('AppointmentsService.confirmPending — snapshot da negociação', () = expect(prisma.$transaction).not.toHaveBeenCalled(); }); - it('confirma consultoria mesmo quando existe processo ativo anterior', async () => { + it('rejeita consultoria quando existe outro processo ativo e exclui somente o processo associado', async () => { const client = { id: 'client-1', name: 'Cliente', @@ -1082,21 +1855,20 @@ describe('AppointmentsService.confirmPending — snapshot da negociação', () = await expect( service.confirmPending(appointment.id, specialist.id), - ).resolves.toMatchObject({ id: appointment.id }); + ).rejects.toThrow(ConflictException); - expect(processFindFirst).not.toHaveBeenCalled(); - expect(appointmentFindFirst).toHaveBeenCalledWith({ - where: { - id: { not: appointment.id }, - client_id: client.id, - specialist_id: specialist.id, - product_type: null, - product_id: null, - status: { - in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], - }, - }, - }); + expect(processFindFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ + id: { not: currentProcess.id }, + client_id: client.id, + specialist_id: specialist.id, + product_type: null, + status: { in: expect.arrayContaining([ProcessStatus.SCHEDULING]) }, + }), + }), + ); + expect(appointmentFindFirst).not.toHaveBeenCalled(); }); it.each([ @@ -1210,65 +1982,560 @@ describe('AppointmentsService.confirmPending — snapshot da negociação', () = } as any; const service = new AppointmentsService(prisma, notifications, {} as any); - await service.confirmPending(appointment.id, specialist.id); + await service.confirmPending(appointment.id, specialist.id); + + expect(prisma.$transaction).toHaveBeenCalledTimes(1); + expect(tx.$queryRaw).toHaveBeenCalledTimes(4); + expect(tx.$queryRaw.mock.calls[0][1]).toBe( + 'appointment-schedule:specialist-1', + ); + expect(tx.$queryRaw.mock.calls[1][1]).toBe('product-money:CAR:product-1'); + expect(tx.$queryRaw.mock.calls[2][1]).toBe( + 'process-dedup:client-1:specialist-1:CAR:product-1', + ); + expect(tx.$queryRaw.mock.calls[3][1]).toBe('product-money:CAR:product-1'); + expect(processUpdateMany).toHaveBeenCalledWith({ + where: { + id: schedulingProcess.id, + status: ProcessStatus.SCHEDULING, + updated_at: schedulingProcess.updated_at, + }, + data: expect.objectContaining({ + status: ProcessStatus.NEGOTIATION, + negotiation_currency: currency, + negotiation_product_value: product.valor, + }), + }); + expect(processUpdate).not.toHaveBeenCalled(); + expect(processUpdateMany.mock.invocationCallOrder[0]).toBeLessThan( + tx.processStatusHistory.create.mock.invocationCallOrder.at(-1)!, + ); + expect(processCreate).toHaveBeenCalledTimes(hasExistingProcess ? 0 : 1); + }, + ); +}); + +describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () => { + it('rejeita e não persiste URIs Calendly não confiáveis mesmo com horário informado', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(), + } as any; + const calendlyIntegrationService = { + resolveScheduledStartTime: jest.fn(), + } as any; + const service = new AppointmentsService( + prisma, + {} as any, + calendlyIntegrationService, + ); + + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: 'https://evil.test/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + scheduled_start_time: '2099-01-01T10:00:00.000Z', + }), + ).rejects.toThrow(BadRequestException); + expect( + calendlyIntegrationService.resolveScheduledStartTime, + ).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + + it('rejeita evento e convidado que não pertencem ao mesmo agendamento', async () => { + const prisma = { + appointment: { findUnique: jest.fn() }, + $transaction: jest.fn(), + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + await expect( + service.registerCalendlyScheduled('appointment-1', 'client-1', { + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-2/invitees/invitee-1', + scheduled_start_time: '2099-01-01T10:00:00.000Z', + }), + ).rejects.toThrow('URIs do Calendly pertencem a eventos diferentes'); + expect(prisma.appointment.findUnique).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + + it.each([ + AppointmentSchedulingMethod.EMAIL, + AppointmentSchedulingMethod.PLATFORM, + ])('rejeita sincronização Calendly para origem %s', async (method) => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.PENDING, + scheduling_method: method, + specialist_rescheduled_at: null, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(), + } as any; + const service = new AppointmentsService(prisma, {} as any, {} as any); + + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + scheduled_start_time: '2099-01-01T10:00:00.000Z', + } as any), + ).rejects.toThrow(BadRequestException); + expect(prisma.appointment.findUnique).toHaveBeenCalledTimes(1); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + + it('considera idempotente a mesma URI oficial após canonicalização', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.SCHEDULED, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: + 'https://calendly.com/api/v2/scheduled_events/event-1', + calendly_invitee_uri: + 'https://calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', + calendly_sync_status: 'SYNCED', + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + }; + const prisma = { + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + $transaction: jest.fn(), + } as any; + const calendlyIntegrationService = { + resolveScheduledStartTime: jest.fn(), + } as any; + const service = new AppointmentsService( + prisma, + {} as any, + calendlyIntegrationService, + ); + + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }), + ).resolves.toEqual({ + appointment_id: appointment.id, + calendly_sync_status: appointment.calendly_sync_status, + appointment_datetime: appointment.appointment_datetime, + }); + expect( + calendlyIntegrationService.resolveScheduledStartTime, + ).not.toHaveBeenCalled(); + expect(prisma.appointment.updateMany).toHaveBeenCalledWith({ + where: { + id: appointment.id, + calendly_event_uri: appointment.calendly_event_uri, + calendly_invitee_uri: appointment.calendly_invitee_uri, + }, + data: { + calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }, + }); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + + it('não deixa invitee injetado envenenar evento confiável sem convidado e aceita o genuíno depois', async () => { + const trustedDate = new Date('2099-01-01T10:00:00.000Z'); + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.SCHEDULED, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/group-event', + calendly_invitee_uri: null, + calendly_sync_status: 'SYNCED', + appointment_datetime: trustedDate, + }; + let stored = { ...appointment }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn(async () => ({ ...stored })), + findFirst: jest.fn().mockResolvedValue(null), + update: jest.fn(async ({ data }) => { + stored = { ...stored, ...data }; + return { ...stored }; + }), + }, + }; + const prisma = { + appointment: { + findUnique: jest.fn(async () => ({ ...stored })), + updateMany: jest.fn(), + }, + $transaction: jest.fn(async (callback: any) => callback(tx)), + } as any; + const resolveScheduledStartTime = jest + .fn() + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(trustedDate); + const service = new AppointmentsService( + prisma, + {} as any, + { + resolveScheduledStartTime, + } as any, + ); + + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: appointment.calendly_event_uri, + invitee_uri: + 'https://api.calendly.com/scheduled_events/group-event/invitees/poison', + }), + ).resolves.toMatchObject({ + calendly_sync_status: 'SYNCED', + appointment_datetime: trustedDate, + }); + expect(stored.calendly_invitee_uri).toBeNull(); + expect(prisma.appointment.updateMany).not.toHaveBeenCalled(); + expect(tx.appointment.update).not.toHaveBeenCalled(); + + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: appointment.calendly_event_uri, + invitee_uri: + 'https://api.calendly.com/scheduled_events/group-event/invitees/genuine', + }), + ).resolves.toMatchObject({ + calendly_sync_status: 'SYNCED', + appointment_datetime: trustedDate, + }); + expect(resolveScheduledStartTime).toHaveBeenCalledTimes(2); + expect(stored.calendly_invitee_uri).toBe( + 'https://api.calendly.com/scheduled_events/group-event/invitees/genuine', + ); + }); + + it('não persiste URIs controladas pelo cliente quando a API não confirma o horário', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: null, + calendly_invitee_uri: null, + calendly_sync_status: CalendlySyncStatus.PENDING, + appointment_datetime: null, + }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + findFirst: jest.fn(), + update: jest.fn().mockImplementation(({ data }) => ({ + ...appointment, + ...data, + })), + }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(async (callback: any) => callback(tx)), + } as any; + const resolveScheduledStartTime = jest.fn().mockResolvedValue(null); + const service = new AppointmentsService( + prisma, + {} as any, + { + resolveScheduledStartTime, + } as any, + ); + + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: 'https://api.calendly.com/scheduled_events/event-poison', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-poison/invitees/invitee-poison', + }), + ).resolves.toMatchObject({ + calendly_sync_status: CalendlySyncStatus.PENDING, + appointment_datetime: null, + }); + expect(resolveScheduledStartTime).toHaveBeenCalledTimes(1); + expect(tx.appointment.update).not.toHaveBeenCalled(); + expect(tx.appointment.findFirst).not.toHaveBeenCalled(); + }); + + it('não ressuscita como SYNCED um agendamento cancelado pelo webhook enquanto consultava a API', async () => { + const resolvedDate = new Date('2099-01-03T14:00:00.000Z'); + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + calendly_sync_status: CalendlySyncStatus.PENDING, + appointment_datetime: null, + }; + let stored = { ...appointment }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn(async () => ({ ...stored })), + findFirst: jest.fn().mockResolvedValue(null), + update: jest.fn().mockImplementation(({ data }) => ({ + ...stored, + ...data, + })), + }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(async (callback: any) => callback(tx)), + } as any; + const resolveScheduledStartTime = jest.fn(async () => { + stored = { + ...stored, + calendly_sync_status: CalendlySyncStatus.FAILED, + }; + return resolvedDate; + }); + const service = new AppointmentsService( + prisma, + {} as any, + { + resolveScheduledStartTime, + } as any, + ); + + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: appointment.calendly_event_uri, + invitee_uri: appointment.calendly_invitee_uri, + }), + ).resolves.toMatchObject({ + calendly_sync_status: CalendlySyncStatus.FAILED, + appointment_datetime: null, + }); + expect(tx.appointment.update).not.toHaveBeenCalled(); + expect(tx.appointment.findFirst).not.toHaveBeenCalled(); + }); + + it('reconsulta o Calendly ao repetir a mesma associação ainda PENDING e promove para SYNCED', async () => { + const resolvedDate = new Date('2099-01-03T14:00:00.000Z'); + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + calendly_sync_status: 'PENDING', + appointment_datetime: null, + }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + findFirst: jest.fn().mockResolvedValue(null), + update: jest.fn().mockImplementation(({ data }) => ({ + ...appointment, + ...data, + })), + }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(async (callback: any) => callback(tx)), + } as any; + const resolveScheduledStartTime = jest.fn().mockResolvedValue(resolvedDate); + const service = new AppointmentsService( + prisma, + {} as any, + { + resolveScheduledStartTime, + } as any, + ); + + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: appointment.calendly_event_uri, + invitee_uri: appointment.calendly_invitee_uri, + }), + ).resolves.toEqual({ + appointment_id: appointment.id, + calendly_sync_status: 'SYNCED', + appointment_datetime: resolvedDate, + }); + expect(resolveScheduledStartTime).toHaveBeenCalledTimes(1); + expect(tx.appointment.findFirst).toHaveBeenCalledTimes(1); + expect(tx.appointment.update).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + calendly_sync_status: 'SYNCED', + appointment_datetime: resolvedDate, + }), + }), + ); + }); + + it('rejeita o mesmo evento quando já está associado a outro convidado', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.SCHEDULED, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: + 'https://calendly.com/api/v2/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-old', + }; + const prisma = { + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + updateMany: jest.fn(), + }, + $transaction: jest.fn(), + } as any; + const calendlyIntegrationService = { + resolveScheduledStartTime: jest.fn(), + } as any; + const service = new AppointmentsService( + prisma, + {} as any, + calendlyIntegrationService, + ); + + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-new', + }), + ).rejects.toThrow(ConflictException); + expect(prisma.appointment.updateMany).not.toHaveBeenCalled(); + expect( + calendlyIntegrationService.resolveScheduledStartTime, + ).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); - expect(prisma.$transaction).toHaveBeenCalledTimes(1); - expect(tx.$queryRaw).toHaveBeenCalledTimes(4); - expect(tx.$queryRaw.mock.calls[0][1]).toBe('product-money:CAR:product-1'); - expect(tx.$queryRaw.mock.calls[1][1]).toBe( - 'process-dedup:client-1:specialist-1:CAR:product-1', - ); - expect(tx.$queryRaw.mock.calls[2][1]).toBe( - 'appointment-schedule:specialist-1', - ); - expect(tx.$queryRaw.mock.calls[3][1]).toBe('product-money:CAR:product-1'); - expect(processUpdateMany).toHaveBeenCalledWith({ - where: { - id: schedulingProcess.id, - status: ProcessStatus.SCHEDULING, - updated_at: schedulingProcess.updated_at, - }, - data: expect.objectContaining({ - status: ProcessStatus.NEGOTIATION, - negotiation_currency: currency, - negotiation_product_value: product.valor, - }), - }); - expect(processUpdate).not.toHaveBeenCalled(); - expect(processUpdateMany.mock.invocationCallOrder[0]).toBeLessThan( - tx.processStatusHistory.create.mock.invocationCallOrder.at(-1)!, - ); - expect(processCreate).toHaveBeenCalledTimes(hasExistingProcess ? 0 : 1); - }, - ); -}); + it('revalida sob lock e rejeita outro convidado gravado concorrentemente', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.SCHEDULED, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: null, + calendly_invitee_uri: null, + }; + const lockedAppointment = { + ...appointment, + calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-old', + }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(lockedAppointment), + update: jest.fn(), + }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(async (callback: (client: any) => unknown) => + callback(tx), + ), + } as any; + const calendlyIntegrationService = { + resolveScheduledStartTime: jest.fn(), + } as any; + const service = new AppointmentsService( + prisma, + {} as any, + calendlyIntegrationService, + ); -describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () => { - it.each([ - AppointmentSchedulingMethod.EMAIL, - AppointmentSchedulingMethod.PLATFORM, - ])('rejeita sincronização Calendly para origem %s', async (method) => { + await expect( + service.registerCalendlyScheduled(appointment.id, appointment.client_id, { + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-new', + scheduled_start_time: '2099-01-01T10:00:00.000Z', + }), + ).rejects.toThrow(ConflictException); + expect(tx.$queryRaw).toHaveBeenCalledTimes(1); + expect(tx.appointment.update).not.toHaveBeenCalled(); + }); + + it('não ignora falha de integridade detectada na resposta do Calendly', async () => { const appointment = { id: 'appointment-1', client_id: 'client-1', specialist_id: 'specialist-1', status: StatusAgendamento.PENDING, - scheduling_method: method, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, specialist_rescheduled_at: null, + calendly_event_uri: null, }; const prisma = { appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, $transaction: jest.fn(), } as any; - const service = new AppointmentsService(prisma, {} as any, {} as any); + const integrityError = new BadRequestException( + 'URIs do Calendly pertencem a eventos diferentes', + ); + const calendlyIntegrationService = { + resolveScheduledStartTime: jest.fn().mockRejectedValue(integrityError), + } as any; + const service = new AppointmentsService( + prisma, + {} as any, + calendlyIntegrationService, + ); await expect( service.registerCalendlyScheduled(appointment.id, appointment.client_id, { - event_uri: 'https://calendly.test/events/1', - invitee_uri: 'https://calendly.test/invitees/1', - scheduled_start_time: '2099-01-01T10:00:00.000Z', - } as any), - ).rejects.toThrow(BadRequestException); + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }), + ).rejects.toBe(integrityError); expect(prisma.$transaction).not.toHaveBeenCalled(); }); @@ -1289,15 +2556,16 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = await expect( service.registerCalendlyScheduled(appointment.id, appointment.client_id, { - event_uri: 'https://calendly.test/events/2', - invitee_uri: 'https://calendly.test/invitees/2', + event_uri: 'https://api.calendly.com/scheduled_events/event-2', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-2/invitees/invitee-2', scheduled_start_time: '2099-01-02T10:00:00.000Z', } as any), ).rejects.toThrow(ConflictException); expect(prisma.$transaction).not.toHaveBeenCalled(); }); - it('serializes and rechecks the resolved time in the write transaction', async () => { + it('normalizes, serializes and rechecks the resolved time in the write transaction', async () => { const appointment = { id: 'appointment-1', client_id: 'client-1', @@ -1326,27 +2594,188 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = }, $transaction: jest.fn(async (callback: any) => callback(tx)), } as any; - const service = new AppointmentsService(prisma, {} as any, {} as any); + const calendlyIntegrationService = { + resolveScheduledStartTime: jest + .fn() + .mockResolvedValue(new Date('2099-01-02T11:00:00.000Z')), + } as any; + const service = new AppointmentsService( + prisma, + {} as any, + calendlyIntegrationService, + ); await service.registerCalendlyScheduled( appointment.id, appointment.client_id, { - event_uri: 'https://calendly.test/events/1', - invitee_uri: 'https://calendly.test/invitees/1', + event_uri: 'https://calendly.com/api/v2/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', scheduled_start_time: '2099-01-01T10:00:00.000Z', } as any, ); + expect( + calendlyIntegrationService.resolveScheduledStartTime, + ).toHaveBeenCalledWith( + appointment.specialist_id, + 'https://api.calendly.com/scheduled_events/event-1', + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + appointment.client_id, + ); expect(tx.$queryRaw).toHaveBeenCalledWith( expect.anything(), 'appointment-schedule:specialist-1', ); expect(tx.appointment.findFirst).toHaveBeenCalled(); expect(prisma.appointment.update).not.toHaveBeenCalled(); - expect(tx.appointment.update).toHaveBeenCalledTimes(1); + expect(tx.appointment.update).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + appointment_datetime: new Date('2099-01-02T11:00:00.000Z'), + }), + }), + ); }); + it.each([ + ['retorna null', null], + ['falha', new Error('Calendly indisponível')], + ])( + 'mantém PENDING e não ocupa agenda quando a API canônica %s', + async (_label, apiResult) => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: null, + calendly_invitee_uri: null, + calendly_sync_status: 'PENDING', + appointment_datetime: null, + }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + findFirst: jest.fn(), + update: jest.fn().mockImplementation(({ data }) => ({ + ...appointment, + ...data, + })), + }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(async (callback: any) => callback(tx)), + } as any; + const resolveScheduledStartTime = + apiResult instanceof Error + ? jest.fn().mockRejectedValue(apiResult) + : jest.fn().mockResolvedValue(apiResult); + const service = new AppointmentsService( + prisma, + {} as any, + { + resolveScheduledStartTime, + } as any, + ); + + await expect( + service.registerCalendlyScheduled( + appointment.id, + appointment.client_id, + { + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + scheduled_start_time: '2099-01-01T10:00:00.000Z', + } as any, + ), + ).resolves.toEqual({ + appointment_id: appointment.id, + calendly_sync_status: 'PENDING', + appointment_datetime: null, + }); + expect(resolveScheduledStartTime).toHaveBeenCalledTimes(1); + expect(tx.appointment.findFirst).not.toHaveBeenCalled(); + expect(tx.appointment.update).not.toHaveBeenCalled(); + }, + ); + + it.each([ + ['retorna null', null], + ['falha', new Error('Calendly indisponível')], + ])( + 'preserva associação e horário confiáveis quando novas URIs chegam e a API %s', + async (_label, apiResult) => { + const trustedDate = new Date('2099-01-01T10:00:00.000Z'); + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.SCHEDULED, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/trusted-event', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/trusted-event/invitees/trusted-invitee', + calendly_sync_status: 'SYNCED', + appointment_datetime: trustedDate, + }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + update: jest.fn(), + }, + }; + const prisma = { + appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, + $transaction: jest.fn(async (callback: any) => callback(tx)), + } as any; + const resolveScheduledStartTime = + apiResult instanceof Error + ? jest.fn().mockRejectedValue(apiResult) + : jest.fn().mockResolvedValue(apiResult); + const service = new AppointmentsService( + prisma, + {} as any, + { + resolveScheduledStartTime, + } as any, + ); + + await expect( + service.registerCalendlyScheduled( + appointment.id, + appointment.client_id, + { + event_uri: + 'https://api.calendly.com/scheduled_events/unverified-event', + invitee_uri: + 'https://api.calendly.com/scheduled_events/unverified-event/invitees/unverified-invitee', + }, + ), + ).resolves.toEqual({ + appointment_id: appointment.id, + calendly_sync_status: 'SYNCED', + appointment_datetime: trustedDate, + }); + expect(resolveScheduledStartTime).toHaveBeenCalledTimes(1); + expect(prisma.$transaction).toHaveBeenCalledTimes(1); + expect(tx.appointment.update).not.toHaveBeenCalled(); + }, + ); + it('rejects a reschedule that overlaps an already SCHEDULED appointment', async () => { const appointment = { id: 'appointment-1', @@ -1372,12 +2801,21 @@ describe('AppointmentsService.registerCalendlyScheduled — schedule lock', () = appointment: { findUnique: jest.fn().mockResolvedValue(appointment) }, $transaction: jest.fn(async (callback: any) => callback(tx)), } as any; - const service = new AppointmentsService(prisma, {} as any, {} as any); + const service = new AppointmentsService( + prisma, + {} as any, + { + resolveScheduledStartTime: jest + .fn() + .mockResolvedValue(new Date('2099-01-01T10:00:00.000Z')), + } as any, + ); await expect( service.registerCalendlyScheduled(appointment.id, appointment.client_id, { - event_uri: 'https://calendly.test/events/1', - invitee_uri: 'https://calendly.test/invitees/1', + event_uri: 'https://api.calendly.com/scheduled_events/event-1', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', scheduled_start_time: '2099-01-01T10:00:00.000Z', } as any), ).rejects.toThrow(ConflictException); @@ -1551,3 +2989,162 @@ describe('AppointmentsService.reschedule — alteração definitiva', () => { }); }); }); + +describe('AppointmentsService — sugestões compartilham ocupação da agenda', () => { + const requested = new Date('2099-01-01T10:00:00Z'); + it.each([ + [ + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + 'PENDING', + 11, + ], + [ + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.CALENDLY, + 'PENDING', + 11, + ], + [ + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.CALENDLY, + 'SYNCED', + 13, + ], + [StatusAgendamento.PENDING, null, 'PENDING', 13], + [ + StatusAgendamento.SCHEDULED, + AppointmentSchedulingMethod.EMAIL, + 'PENDING', + 13, + ], + ])( + 'suggestions respect %s/%s/%s including the one-hour boundary', + async (status, method, sync, firstHour) => { + const record: Record = { + specialist_id: 'specialist-1', + status, + scheduling_method: method, + calendly_sync_status: sync, + appointment_datetime: new Date('2099-01-01T11:00:00Z'), + }; + const findFirst = jest.fn(async ({ where }) => { + const branches = where.OR ?? [{ status: where.status }]; + const occupied = branches.some((branch: any) => + Object.entries(branch).every(([key, value]) => record[key] === value), + ); + const inWindow = + record.appointment_datetime >= where.appointment_datetime.gte && + record.appointment_datetime <= where.appointment_datetime.lte; + return occupied && inWindow ? { id: 'occupied' } : null; + }); + const service = new AppointmentsService( + { appointment: { findFirst } } as any, + {} as any, + {} as any, + ); + expect( + await (service as any).suggestAlternativeTimes( + 'specialist-1', + requested, + ), + ).toEqual( + [0, 1, 2].map( + (offset) => `2099-01-01T${Number(firstHour) + offset}:00:00.000Z`, + ), + ); + expect(findFirst).toHaveBeenCalledWith( + expect.objectContaining({ + select: { id: true }, + where: expect.objectContaining({ OR: expect.any(Array) }), + }), + ); + }, + ); +}); + +describe('AppointmentsService.cancelPending — serialização canônica', () => { + it('adquire o lock da agenda e revalida appointment/process dentro da transação', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.PENDING, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + client: { + id: 'client-1', + name: 'Cliente', + surname: 'Teste', + email: 'cliente@example.com', + }, + specialist: { + id: 'specialist-1', + name: 'Especialista', + surname: 'Teste', + email: 'especialista@example.com', + }, + process: { + id: 'process-1', + status: ProcessStatus.SCHEDULING, + updated_at: new Date('2026-01-01T00:00:00.000Z'), + }, + }; + const historyDelete = jest.fn().mockResolvedValue({ count: 1 }); + const processClaim = jest.fn().mockResolvedValue({ count: 1 }); + const processDelete = jest.fn().mockResolvedValue(appointment.process); + const appointmentDelete = jest.fn().mockResolvedValue(appointment); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + delete: appointmentDelete, + }, + process: { updateMany: processClaim, delete: processDelete }, + processStatusHistory: { deleteMany: historyDelete }, + }; + const prisma = { + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + }, + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const notifications = { + sendAppointmentCancelledEmail: jest.fn().mockResolvedValue(undefined), + }; + const service = new AppointmentsService( + prisma, + notifications as any, + {} as any, + ); + + await service.cancelPending(appointment.id, appointment.client_id); + + expect(tx.$queryRaw).toHaveBeenCalledWith( + expect.anything(), + 'appointment-schedule:specialist-1', + ); + expect(tx.appointment.findUnique).toHaveBeenCalledWith( + expect.objectContaining({ where: { id: appointment.id } }), + ); + expect(historyDelete).toHaveBeenCalledWith({ + where: { processId: appointment.process.id }, + }); + expect(processClaim).toHaveBeenCalledWith({ + where: { + id: appointment.process.id, + status: ProcessStatus.SCHEDULING, + updated_at: appointment.process.updated_at, + }, + data: { updated_at: expect.any(Date) }, + }); + expect(processClaim.mock.invocationCallOrder[0]).toBeLessThan( + historyDelete.mock.invocationCallOrder[0], + ); + expect(processDelete).toHaveBeenCalledWith({ + where: { id: appointment.process.id }, + }); + expect(appointmentDelete).toHaveBeenCalledWith({ + where: { id: appointment.id }, + }); + }); +}); diff --git a/backend/src/features/appointments/appointments.service.ts b/backend/src/features/appointments/appointments.service.ts index 0d262292..620f408e 100644 --- a/backend/src/features/appointments/appointments.service.ts +++ b/backend/src/features/appointments/appointments.service.ts @@ -5,6 +5,7 @@ import { NotFoundException, ForbiddenException, Logger, + Optional, } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { @@ -13,6 +14,7 @@ import { CreatePendingAppointmentDto, CreatePlatformAppointmentDto, GetAppointmentsQueryDto, + PENDING_APPOINTMENT_DATETIME_PATTERN, UpdateAppointmentStatusDto, } from './dto'; import { @@ -20,6 +22,7 @@ import { ClientResponseDto, SpecialistResponseDto, ProductResponseDto, + ExistingAppointmentCheck, } from './entities/appointment.response'; import { AppointmentSchedulingMethod, @@ -34,21 +37,29 @@ import { ProcessStatus, } from '@prisma/client'; import { plainToInstance } from 'class-transformer'; +import { isISO8601 } from 'class-validator'; +import { isCalendlySchedulingAvailable } from 'src/shared/utils/calendly-scheduling-capability'; import { parseDate, isFutureDate } from 'src/shared/utils/date.utils'; import { NotificationService } from 'src/features/notifications/notification.service'; import { CalendlyIntegrationService } from './calendly-integration.service'; +import { parseCalendlyResourceUri } from './dto/calendly-scheduled.dto'; import { buildNegotiationSnapshotUpdate } from 'src/features/processes/negotiation-snapshot'; import { lockNegotiationProductMoney } from 'src/features/products/product-monetary-lock'; import { validateSpecialistProductAssociation } from 'src/features/products/product-association-validator'; import { + ACTIVE_PROCESS_STATUSES, acquireActiveProcessDedupLock, + assertNoActiveProcess, lockAndAssertNoActiveProcess, } from 'src/features/processes/process-dedup-lock'; import { acquireSpecialistScheduleLock, assertSpecialistScheduleAvailable, + buildOccupiedScheduleWhere, lockAndAssertSpecialistScheduleAvailable, } from './appointment-schedule-lock'; +import { ActorContext } from 'src/shared/actor-context/actor-context.service'; +import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service'; /** * AppointmentsService @@ -79,251 +90,42 @@ export class AppointmentsService { private prisma: PrismaService, private notificationService: NotificationService, private calendlyIntegrationService: CalendlyIntegrationService, + @Optional() + private readonly delegatedAudit?: DelegatedActionAuditService, ) {} - /** - * Cria novo agendamento - * - * Fluxo: - * 1. Validar que cliente e especialista existem - * 2. Validar que appointment_datetime é futuro - * 3. Verificar conflitos de horário - * 4. Validar que produto existe e pertence ao especialista - * 5. Criar Appointment - * 6. Auto-criar Process em status SCHEDULING - * 7. Retornar AppointmentResponseEntity - * - * @param dto Dados do agendamento - * @param userId ID do usuário autenticado (JWT) - * @returns Appointment criado com dados completos - * @throws BadRequestException Se dados inválidos - * @throws ConflictException Se conflito de horário - * @throws NotFoundException Se usuário ou produto não encontrado - */ - async create( - dto: CreatePlatformAppointmentDto, - userId: string, - userRole: UserRole, - ): Promise { - if (userRole !== UserRole.CUSTOMER || dto.client_id !== userId) { - throw new ForbiddenException({ - success: false, - error: { - code: 403, - message: 'Apenas o próprio cliente pode criar este agendamento', - }, - }); - } - - this.logger.log( - `[create] Criando agendamento para cliente ${dto.client_id} com especialista ${dto.specialist_id}`, - ); - - const appointmentDateTime = parseDate(dto.appointment_datetime); - if (!appointmentDateTime || !isFutureDate(appointmentDateTime)) { - this.logger.warn('[create] Data/hora do agendamento é inválida'); - throw new BadRequestException({ - success: false, - error: { - code: 400, - message: 'Data/hora do agendamento deve ser futura', - details: { - appointment_datetime: [ - 'appointment_datetime deve ser uma data ISO 8601 futura', - ], - }, - }, - }); - } - - // Validação 2: Verificar que cliente existe - this.logger.debug( - `[create] Validando existência do cliente ${dto.client_id}`, - ); - const client = await this.prisma.user.findUnique({ - where: { id: dto.client_id }, - }); - if (!client) { - this.logger.error(`[create] Cliente ${dto.client_id} não encontrado`); - throw new NotFoundException({ - success: false, - error: { - code: 404, - message: 'Cliente não encontrado', - details: { - client_id: dto.client_id, - }, - }, - }); - } - - // Validação 3: Verificar que especialista existe e tem role SPECIALIST - const specialist = await this.prisma.user.findUnique({ - where: { id: dto.specialist_id }, - }); - if (!specialist) { - throw new NotFoundException({ - success: false, - error: { - code: 404, - message: 'Especialista não encontrado', - details: { - specialist_id: dto.specialist_id, - }, - }, - }); - } - - if ( - specialist.role !== UserRole.SPECIALIST && - specialist.role !== UserRole.CONSULTANT - ) { - throw new BadRequestException({ - success: false, - error: { - code: 400, - message: 'Usuário não é especialista', - details: { - specialist_id: dto.specialist_id, - role: specialist.role, - }, - }, - }); - } - - // Validação 4: Validar que especialidade do especialista corresponde ao product_type - if (specialist.speciality && specialist.speciality !== dto.product_type) { - throw new BadRequestException({ - success: false, - error: { - code: 400, - message: 'Especialista não trabalha com este tipo de produto', - details: { - specialist_speciality: specialist.speciality, - requested_product_type: dto.product_type, - }, - }, - }); - } - - // Validação 5: Verificar que cliente e especialista são diferentes - if (dto.client_id === dto.specialist_id) { - throw new BadRequestException({ - success: false, - error: { - code: 400, - message: 'Cliente e especialista não podem ser a mesma pessoa', - details: { - client_id: dto.client_id, - specialist_id: dto.specialist_id, - }, - }, - }); + private assertRepresentedSpecialist( + context: ActorContext | undefined, + specialistId: string, + ) { + if (context && context.specialistId !== specialistId) { + throw new ForbiddenException( + 'O agendamento não pertence ao especialista representado.', + ); } + } - const { appointment, process, product } = await this.prisma.$transaction( - async (tx) => { - // Validação 6: produto ativo, do tipo correto e pertencente ao especialista. - const product = (await validateSpecialistProductAssociation(tx, { - specialistId: dto.specialist_id, - productType: dto.product_type, - productId: dto.product_id, - })) as Car | Boat | Aircraft; - - await lockAndAssertNoActiveProcess(tx, { - clientId: dto.client_id, - specialistId: dto.specialist_id, - productType: dto.product_type, - productId: dto.product_id, - }); - await lockAndAssertSpecialistScheduleAvailable( - tx, - dto.specialist_id, - appointmentDateTime, - ); - - // Criar Appointment - const appointment = await tx.appointment.create({ - data: { - client_id: dto.client_id, - specialist_id: dto.specialist_id, - product_type: dto.product_type, - product_id: dto.product_id, - appointment_datetime: appointmentDateTime, - status: StatusAgendamento.SCHEDULED, - scheduling_method: AppointmentSchedulingMethod.PLATFORM, - notes: dto.notes, - }, - include: { - client: true, - specialist: true, - }, - }); - - // Auto-criar Process vinculado a este Appointment - // Process começa em status SCHEDULING (agendamento confirmado) - const process = await tx.process.create({ - data: { - client_id: dto.client_id, - specialist_id: dto.specialist_id, - product_type: dto.product_type, - appointment_id: appointment.id, - [dto.product_type === ProductType.CAR - ? 'car_id' - : dto.product_type === ProductType.BOAT - ? 'boat_id' - : 'aircraft_id']: dto.product_id, - status: 'SCHEDULING', // ProcessStatus enum - notes: `Criado via agendamento interno. Cliente agendou em ${appointment.appointment_datetime?.toISOString()}`, - }, - }); - - await tx.processStatusHistory.create({ - data: { - processId: process.id, - status: ProcessStatus.SCHEDULING, - changed_by: userId, - changed_at: new Date(), - }, - }); - - return { appointment, process, product }; + /** Bloqueia a criação direta sem confirmação do especialista. */ + async create( + _dto: CreatePlatformAppointmentDto, + _userId: string, + _userRole: UserRole, + ): Promise { + throw new ForbiddenException({ + success: false, + error: { + code: 403, + message: + 'Use o pedido pendente por e-mail ou Calendly para solicitar a reunião', }, - ); - - // Fire-and-forget: Notificar especialista sobre novo agendamento - const productDetails = product - ? `${(product as any).marca || ''} ${(product as any).modelo || ''}`.trim() - : `Produto ${dto.product_type}`; - - setImmediate(() => { - this.notificationService - .sendAppointmentCreatedEmail({ - specialistEmail: specialist.email, - specialistName: - `${specialist.name} ${specialist.surname || ''}`.trim(), - clientName: `${client.name} ${client.surname || ''}`.trim(), - appointmentDate: appointment.appointment_datetime || new Date(), - productDetails, - processId: process.id, - }) - .catch((err) => { - this.logger.error('Notification failed (non-critical)', { - method: 'create', - appointmentId: appointment.id, - error: err.message, - }); - }); }); - - // Montar resposta com dados completos - return this.mapToResponseEntity(appointment, client, specialist, product); } async reschedule( appointmentId: string, appointmentDatetime: string, userId: string, + context?: ActorContext, ): Promise { const nextDate = parseDate(appointmentDatetime); if (!nextDate || !isFutureDate(nextDate)) { @@ -343,7 +145,8 @@ export class AppointmentsService { if (!appointment) { throw new NotFoundException('Agendamento não encontrado'); } - if (appointment.specialist_id !== userId) { + const representedSpecialistId = context?.specialistId ?? userId; + if (appointment.specialist_id !== representedSpecialistId) { throw new ForbiddenException( 'Apenas o especialista responsável pode alterar o horário', ); @@ -359,7 +162,11 @@ export class AppointmentsService { if (!lockedAppointment) { throw new NotFoundException('Agendamento não encontrado'); } - if (lockedAppointment.specialist_id !== userId) { + if (lockedAppointment.process?.removed_at) { + throw new NotFoundException('Agendamento não encontrado'); + } + this.assertRepresentedSpecialist(context, lockedAppointment.specialist_id); + if (lockedAppointment.specialist_id !== representedSpecialistId) { throw new ForbiddenException( 'Apenas o especialista responsável pode alterar o horário', ); @@ -409,6 +216,22 @@ export class AppointmentsService { throw this.buildRescheduleAlreadyUsedError(appointmentId); } + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'APPOINTMENT_RESCHEDULE', + resourceType: 'APPOINTMENT', + resourceId: appointmentId, + metadata: { + from: lockedAppointment.appointment_datetime, + to: nextDate, + }, + }, + tx, + ); + } + return tx.appointment.findUniqueOrThrow({ where: { id: appointmentId }, include: { client: true, specialist: true, process: true }, @@ -477,6 +300,7 @@ export class AppointmentsService { * Respeita permissões por role: * - CUSTOMER: vê apenas seus próprios agendamentos * - SPECIALIST/CONSULTANT: vê como especialista + seus clientes + * - OFFICE: vê clientes vinculados à própria empresa * - ADMIN: vê todos * * @param query Query parameters (paginação, filtros, ordenação) @@ -512,20 +336,79 @@ export class AppointmentsService { const limit = query.limit || 20; const skip = (page - 1) * limit; - // Construir filtro WHERE conforme permissões - const where: any = {}; + // Construir filtro WHERE conforme permissões. ADMIN é o único papel com + // visão global; qualquer papel sem regra explícita deve falhar fechado. + const where: any = { + OR: [ + { process: { is: null } }, + { process: { is: { removed_at: null } } }, + ], + }; - // Aplicar filtros de role - if (userRole === UserRole.CUSTOMER) { - where.client_id = userId; // Customer vê apenas seus agendamentos como cliente - } else if ( - userRole === UserRole.SPECIALIST || - userRole === UserRole.CONSULTANT - ) { - // Specialist vê como especialista OU como cliente - where.OR = [{ specialist_id: userId }, { client_id: userId }]; + switch (userRole) { + case UserRole.ADMIN: + break; + + case UserRole.CUSTOMER: + where.client_id = userId; + break; + + case UserRole.SPECIALIST: + case UserRole.CONSULTANT: + where.AND = [ + { OR: [{ specialist_id: userId }, { client_id: userId }] }, + ]; + break; + + case UserRole.OFFICE: { + const office = await this.prisma.user.findUnique({ + where: { id: userId }, + select: { company_id: true }, + }); + if (!office?.company_id) { + this.logger.error( + `[getAppointments] OFFICE user=${userId} sem company_id — config inválida`, + ); + throw new ForbiddenException({ + success: false, + error: { + code: 403, + message: 'Escritório sem empresa vinculada', + details: { user_id: userId }, + }, + }); + } + + // Mantém a mesma definição de cliente do escritório aplicada por + // OfficeService.listClients e ProcessesService: vínculo direto com a + // empresa ou indireto por um consultor pertencente a ela. + where.AND = [ + { + client: { + role: UserRole.CUSTOMER, + OR: [ + { consultant: { company_id: office.company_id } }, + { company_id: office.company_id }, + ], + }, + }, + ]; + break; + } + + default: + this.logger.warn( + `[getAppointments] acesso negado role=${userRole} user=${userId}`, + ); + throw new ForbiddenException({ + success: false, + error: { + code: 403, + message: 'Acesso negado', + details: { user_id: userId }, + }, + }); } - // ADMIN vê todos (sem filtro de user_id) // Aplicar filtros de query if (query.status) { @@ -668,10 +551,11 @@ export class AppointmentsService { include: { client: true, specialist: true, + process: { select: { removed_at: true } }, }, }); - if (!appointment) { + if (!appointment || appointment.process?.removed_at) { throw new NotFoundException({ success: false, error: { @@ -734,11 +618,15 @@ export class AppointmentsService { dto: UpdateAppointmentStatusDto, userId: string, userRole: UserRole, + context?: ActorContext, ): Promise { const assertTransitionAllowed = (current: any): void => { + this.assertRepresentedSpecialist(context, current.specialist_id); + const representedSpecialistId = context?.specialistId ?? userId; const isParticipant = - current.client_id === userId || current.specialist_id === userId; - if (!isParticipant && userRole !== UserRole.ADMIN) { + current.client_id === userId || + current.specialist_id === representedSpecialistId; + if (!isParticipant) { throw new ForbiddenException({ success: false, error: { @@ -772,6 +660,11 @@ export class AppointmentsService { 'Apenas uma reunião agendada pode ser concluída', ); } + if (!current.process?.meeting_session?.ended_at) { + throw new BadRequestException( + 'Conclua a reunião pelo fluxo de conversa antes de encerrar o agendamento.', + ); + } } if ( @@ -783,6 +676,15 @@ export class AppointmentsService { 'Apenas agendamentos pendentes ou agendados podem ser cancelados', ); } + if ( + dto.status === StatusAgendamento.CANCELLED && + current.process && + current.process.status !== ProcessStatus.SCHEDULING + ) { + throw new BadRequestException( + 'Não é possível cancelar uma reunião cujo processo já avançou', + ); + } }; const appointment = await this.prisma.appointment.findUnique({ @@ -790,11 +692,11 @@ export class AppointmentsService { include: { client: true, specialist: true, - process: true, + process: { include: { meeting_session: true } }, }, }); - if (!appointment) { + if (!appointment || appointment.process?.removed_at) { throw new NotFoundException({ success: false, error: { @@ -814,10 +716,10 @@ export class AppointmentsService { include: { client: true, specialist: true, - process: true, + process: { include: { meeting_session: true } }, }, }); - if (!lockedAppointment) { + if (!lockedAppointment || lockedAppointment.process?.removed_at) { throw new NotFoundException({ success: false, error: { @@ -853,6 +755,52 @@ export class AppointmentsService { }); } + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'APPOINTMENT_STATUS_UPDATE', + resourceType: 'APPOINTMENT', + resourceId: id, + metadata: { + from: lockedAppointment.status, + to: dto.status, + reason: dto.notes ?? null, + }, + }, + tx, + ); + } + + // Cancellation must release the active scheduling process atomically. + // Keeping a SCHEDULING process linked to a CANCELLED appointment makes + // the product deduplication gate reject every subsequent request. + if ( + dto.status === StatusAgendamento.CANCELLED && + lockedAppointment.process + ) { + await tx.processStatusHistory.deleteMany({ + where: { processId: lockedAppointment.process.id }, + }); + const processClaim = await tx.process.deleteMany({ + where: { + id: lockedAppointment.process.id, + status: ProcessStatus.SCHEDULING, + }, + }); + if (processClaim.count !== 1) { + throw new ConflictException({ + success: false, + error: { + code: 'APPOINTMENT_CANCELLATION_CONFLICT', + message: + 'O processo foi alterado enquanto o agendamento era cancelado', + details: { appointment_id: id }, + }, + }); + } + } + const updatedAppointment = await tx.appointment.findUniqueOrThrow({ where: { id }, include: { @@ -990,19 +938,9 @@ export class AppointmentsService { // Avançar 1 hora checkTime = new Date(checkTime.getTime() + 60 * 60 * 1000); - // Verificar se este horário está livre - const conflictStart = new Date(checkTime.getTime() - 60 * 60 * 1000); - const conflictEnd = new Date(checkTime.getTime() + 60 * 60 * 1000); - const conflict = await this.prisma.appointment.findFirst({ - where: { - specialist_id: specialistId, - appointment_datetime: { - gte: conflictStart, - lte: conflictEnd, - }, - status: StatusAgendamento.SCHEDULED, - }, + where: buildOccupiedScheduleWhere(specialistId, checkTime), + select: { id: true }, }); if (!conflict) { @@ -1146,6 +1084,10 @@ export class AppointmentsService { product_type: productType, product_id: productId, status: 'SCHEDULED', + OR: [ + { process: { is: null } }, + { process: { is: { removed_at: null } } }, + ], }, include: { client: true, @@ -1203,8 +1145,7 @@ export class AppointmentsService { } /** - * Cria um agendamento PENDING - * Usado quando cliente clica no link do Calendly e retorna à plataforma + * Cria um agendamento PENDING por EMAIL ou CALENDLY e seu processo associado. * * Dois fluxos suportados: * 1. Com produto: product_type e product_id fornecidos - fluxo padrão @@ -1212,37 +1153,14 @@ export class AppointmentsService { * * @param dto Dados do agendamento (product_type e product_id opcionais) * @param userId ID do cliente autenticado - * @returns Appointment em status PENDING + * @returns Appointment em status PENDING e o process_id criado atomicamente */ async createPending( dto: CreatePendingAppointmentDto, userId: string, userRole: UserRole, - ): Promise { - this.logger.log( - `[createPending] Criando agendamento PENDING para cliente ${dto.client_id}`, - ); - - const schedulingMethod = - dto.scheduling_method ?? AppointmentSchedulingMethod.CALENDLY; - - if ( - schedulingMethod === AppointmentSchedulingMethod.EMAIL && - dto.appointment_datetime - ) { - throw new BadRequestException( - 'Solicitações por e-mail devem ter o horário definido pelo especialista', - ); - } - - // Validar que quem está criando é o próprio cliente - this.logger.log( - `[createPending] Validando permissão: userId=${userId} vs client_id=${dto.client_id}`, - ); + ): Promise { if (userRole !== UserRole.CUSTOMER || dto.client_id !== userId) { - this.logger.error( - `[createPending] ERRO: Cliente tentando criar agendamento para outro usuário`, - ); throw new ForbiddenException({ success: false, error: { @@ -1251,88 +1169,124 @@ export class AppointmentsService { }, }); } - this.logger.log(`[createPending] ✓ Permissão validada`); - // Validar cliente existe - this.logger.log(`[createPending] Buscando cliente ${dto.client_id}...`); - const client = await this.prisma.user.findUnique({ - where: { id: dto.client_id }, - }); - if (!client) { - this.logger.error( - `[createPending] ERRO: Cliente ${dto.client_id} não encontrado`, + const schedulingMethod = + dto.scheduling_method ?? AppointmentSchedulingMethod.CALENDLY; + if ( + schedulingMethod !== AppointmentSchedulingMethod.EMAIL && + schedulingMethod !== AppointmentSchedulingMethod.CALENDLY + ) { + throw new BadRequestException( + 'scheduling_method deve ser EMAIL ou CALENDLY', ); - throw new NotFoundException({ - success: false, - error: { code: 404, message: 'Cliente não encontrado' }, - }); } - this.logger.log(`[createPending] ✓ Cliente encontrado: ${client.name}`); - - // Validar especialista existe - this.logger.log( - `[createPending] Buscando especialista ${dto.specialist_id}...`, - ); - const specialist = await this.prisma.user.findUnique({ - where: { id: dto.specialist_id }, - }); - if (!specialist) { - this.logger.error( - `[createPending] ERRO: Especialista ${dto.specialist_id} não encontrado`, + if ((dto.product_type != null) !== (dto.product_id != null)) { + throw new BadRequestException( + 'product_type e product_id devem ser informados juntos.', + ); + } + const isConsultancy = dto.product_id == null; + const hasDate = + dto.appointment_datetime !== undefined && + dto.appointment_datetime !== null; + if ( + schedulingMethod === AppointmentSchedulingMethod.CALENDLY && + dto.appointment_datetime !== undefined + ) { + throw new BadRequestException( + 'A data do Calendly deve ser definida pela sincronização, não pelo cliente', + ); + } + const pendingDateTime = hasDate + ? parseDate(dto.appointment_datetime) + : null; + if ( + hasDate && + (typeof dto.appointment_datetime !== 'string' || + !PENDING_APPOINTMENT_DATETIME_PATTERN.test(dto.appointment_datetime) || + !isISO8601(dto.appointment_datetime, { strict: true }) || + !pendingDateTime || + !isFutureDate(pendingDateTime)) + ) { + throw new BadRequestException( + 'Data/hora do agendamento deve ser ISO 8601 futura válida com Z ou offset explícito', + ); + } + if ( + !isConsultancy && + schedulingMethod === AppointmentSchedulingMethod.EMAIL && + !pendingDateTime + ) { + throw new BadRequestException( + 'Data/hora proposta é obrigatória para solicitações por e-mail com produto', ); - throw new NotFoundException({ - success: false, - error: { code: 404, message: 'Especialista não encontrado' }, - }); + } + + const client = await this.prisma.user.findUnique({ where: { id: userId } }); + if (!client) throw new NotFoundException('Cliente não encontrado'); + const specialist = await this.prisma.user.findUnique({ + where: { id: dto.specialist_id }, + include: { calendly_connection: { select: { is_active: true } } }, + }); + if (!specialist) throw new NotFoundException('Especialista não encontrado'); + if (specialist.role !== UserRole.SPECIALIST) { + throw new BadRequestException('Usuário informado não é especialista'); } this.logger.log( `[createPending] ✓ Especialista encontrado: ${specialist.name}`, ); - // Determinar se é consultoria (sem produto) ou fluxo padrão (com produto) - const isConsultancy = !dto.product_type || !dto.product_id; - this.logger.log( - `[createPending] Modo: ${isConsultancy ? 'CONSULTORIA' : 'COM PRODUTO'}`, - ); + const calendlyAvailable = isCalendlySchedulingAvailable({ + calendlyUrl: specialist.calendly_url, + connectionActive: specialist.calendly_connection?.is_active ?? false, + }); + if ( + schedulingMethod === AppointmentSchedulingMethod.CALENDLY && + !calendlyAvailable + ) { + throw new ConflictException({ + success: false, + error: { + code: 'CALENDLY_UNAVAILABLE', + message: 'Calendly indisponível. Solicite a reunião por e-mail.', + }, + }); + } + if ( + !isConsultancy && + schedulingMethod === AppointmentSchedulingMethod.EMAIL && + calendlyAvailable + ) { + throw new ConflictException({ + success: false, + error: { + code: 'EMAIL_FLOW_UNAVAILABLE', + message: + 'Este especialista utiliza Calendly. Solicite a reunião pelo calendário.', + }, + }); + } - // Verificar se já existe agendamento PENDING ou SCHEDULED - this.logger.log(`[createPending] Verificando agendamento duplicado...`); - const existingWhere: any = { - client_id: dto.client_id, + const consultancyAppointmentWhere = { + client_id: userId, specialist_id: dto.specialist_id, + product_type: null, + product_id: null, status: { in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], }, }; + const assertNoDuplicateAppointment = ( + existing: { id: string; status: StatusAgendamento } | null, + ): void => { + if (!existing) return; - if (isConsultancy) { - // Para consultoria, verificar se já existe agendamento sem produto - existingWhere.product_type = null; - existingWhere.product_id = null; - } else { - // Para fluxo normal, verificar por produto específico - existingWhere.product_type = dto.product_type; - existingWhere.product_id = dto.product_id; - } - - const assertNoDuplicateAppointment = (existing: any): void => { - if (!existing) { - this.logger.log( - `[createPending] ✓ Nenhum agendamento duplicado encontrado`, - ); - return; - } - - this.logger.error( - `[createPending] ERRO: Agendamento duplicado encontrado: ${existing.id}`, - ); throw new ConflictException({ success: false, error: { code: 409, - message: isConsultancy - ? 'Já existe um agendamento de consultoria pendente com este especialista' - : 'Já existe um agendamento pendente ou confirmado para este produto', + message: + 'Já existe um agendamento de consultoria pendente com este especialista', details: { existing_id: existing.id, existing_status: existing.status, @@ -1341,190 +1295,104 @@ export class AppointmentsService { }); }; - const existing = await this.prisma.appointment.findFirst({ - where: existingWhere, - }); - assertNoDuplicateAppointment(existing); - - // Validar produto apenas se fornecido (não é consultoria) - let product: any = null; - if (!isConsultancy) { - this.logger.log( - `[createPending] Buscando produto ${dto.product_type}/${dto.product_id}...`, - ); - product = await this.getProductByType(dto.product_type!, dto.product_id!); - if (!product) { - this.logger.error( - `[createPending] ERRO: Produto ${dto.product_type}/${dto.product_id} não encontrado`, - ); - throw new NotFoundException({ - success: false, - error: { code: 404, message: 'Produto não encontrado' }, - }); - } - this.logger.log(`[createPending] ✓ Produto encontrado`); - } else { - this.logger.log( - `[createPending] Consultoria - pulando validação de produto`, - ); - } - - // Criar appointment em status PENDING e Process em transação + // Metadata only: automatic expiration is not implemented. const pendingExpiresAt = new Date(); - pendingExpiresAt.setDate(pendingExpiresAt.getDate() + 7); // Expira em 7 dias - - this.logger.log( - `[createPending] Iniciando transação para criar appointment e process`, - ); - - let appointment: any; - let process: any; + pendingExpiresAt.setDate(pendingExpiresAt.getDate() + 7); - try { - this.logger.log(`[createPending] Entrando na transação do Prisma...`); - [appointment, process] = await this.prisma.$transaction(async (tx) => { - this.logger.log(`[createPending] Dentro da transação - iniciando`); + const { appointment, process, product } = await this.prisma.$transaction( + async (tx) => { + // Ordem global dos advisory locks: agenda → produto → deduplicação. + // Consultoria datada não tem lock de produto, portanto agenda → dedup. + if (isConsultancy && pendingDateTime) { + await lockAndAssertSpecialistScheduleAvailable( + tx, + dto.specialist_id, + pendingDateTime, + ); + } - await validateSpecialistProductAssociation(tx, { + const product = await validateSpecialistProductAssociation(tx, { specialistId: dto.specialist_id, productType: dto.product_type, productId: dto.product_id, }); const processScope = { - clientId: dto.client_id, + clientId: userId, specialistId: dto.specialist_id, - productType: isConsultancy ? null : dto.product_type, - productId: isConsultancy ? null : dto.product_id, + productType: dto.product_type, + productId: dto.product_id, }; - if (isConsultancy) { await acquireActiveProcessDedupLock(tx, processScope); + await assertNoActiveProcess(tx, processScope, undefined, { + authenticatedClientId: userId, + }); const existingAfterLock = await tx.appointment.findFirst({ - where: existingWhere, + where: consultancyAppointmentWhere, }); assertNoDuplicateAppointment(existingAfterLock); } else { - await lockAndAssertNoActiveProcess(tx, processScope); - } - - const pendingDateTime = dto.appointment_datetime - ? parseDate(String(dto.appointment_datetime)) - : null; - if (dto.appointment_datetime && !pendingDateTime) { - throw new BadRequestException('Data/hora do agendamento é inválida'); - } - if (pendingDateTime) { - await lockAndAssertSpecialistScheduleAvailable( - tx, - dto.specialist_id, - pendingDateTime, - ); - } - - // Criar appointment - const appointmentData: any = { - client_id: dto.client_id, - specialist_id: dto.specialist_id, - appointment_datetime: pendingDateTime, - status: StatusAgendamento.PENDING, - scheduling_method: schedulingMethod, - notes: - dto.notes || - (isConsultancy - ? 'Consultoria: cliente acessou link do Calendly' - : 'Cliente acessou link do Calendly'), - user_clicked_at: new Date(), - pending_expires_at: pendingExpiresAt, - }; - - // Adicionar produto se não for consultoria - if (!isConsultancy) { - appointmentData.product_type = dto.product_type; - appointmentData.product_id = dto.product_id; + await lockAndAssertNoActiveProcess(tx, processScope, undefined, { + authenticatedClientId: userId, + }); } - this.logger.log( - `[createPending] Criando appointment ${isConsultancy ? '(consultoria)' : `para produto ${dto.product_type}/${dto.product_id}`}`, - ); - const createdAppointment = await tx.appointment.create({ - data: appointmentData, - include: { - client: true, - specialist: true, + const appointment = await tx.appointment.create({ + data: { + client_id: userId, + specialist_id: dto.specialist_id, + product_type: dto.product_type ?? null, + product_id: dto.product_id ?? null, + appointment_datetime: pendingDateTime, + status: StatusAgendamento.PENDING, + scheduling_method: schedulingMethod, + notes: + dto.notes || + (schedulingMethod === AppointmentSchedulingMethod.EMAIL + ? 'Cliente solicitou reunião por e-mail' + : 'Cliente acessou link do Calendly'), + user_clicked_at: new Date(), + pending_expires_at: pendingExpiresAt, }, }); - this.logger.log( - `[createPending] Appointment criado: ${createdAppointment.id}`, - ); - - // Criar Process em status SCHEDULING - const processData: any = { - client_id: dto.client_id, - specialist_id: dto.specialist_id, - appointment_id: createdAppointment.id, - status: 'SCHEDULING', - notes: isConsultancy - ? `Consultoria criada via agendamento PENDING (${new Date().toISOString()})` - : `Criado via agendamento PENDING (${new Date().toISOString()})`, - }; - - // Adicionar produto apenas se não for consultoria - if (!isConsultancy) { - const productField = - dto.product_type === ProductType.CAR - ? 'car_id' - : dto.product_type === ProductType.BOAT - ? 'boat_id' - : 'aircraft_id'; - - this.logger.log( - `[createPending] Criando process com campo ${productField}=${dto.product_id}`, - ); - processData.product_type = dto.product_type; - processData[productField] = dto.product_id; - } else { - this.logger.log( - `[createPending] Criando process de consultoria (sem produto)`, - ); - } - - const createdProcess = await tx.process.create({ - data: processData, + const productField = + dto.product_type === ProductType.CAR + ? 'car_id' + : dto.product_type === ProductType.BOAT + ? 'boat_id' + : 'aircraft_id'; + const process = await tx.process.create({ + data: { + client_id: userId, + specialist_id: dto.specialist_id, + appointment_id: appointment.id, + status: ProcessStatus.SCHEDULING, + product_type: dto.product_type ?? null, + ...(isConsultancy ? {} : { [productField]: dto.product_id }), + notes: `Criado via agendamento PENDING (${new Date().toISOString()})`, + }, }); - this.logger.log( - `[createPending] Process criado: ${createdProcess.id} com status ${createdProcess.status}`, - ); - - // Criar histórico await tx.processStatusHistory.create({ data: { - processId: createdProcess.id, - status: 'SCHEDULING', - changed_by: dto.client_id, + processId: process.id, + status: ProcessStatus.SCHEDULING, + changed_by: userId, changed_at: new Date(), }, }); - this.logger.log( - `[createPending] Histórico de status criado para process ${createdProcess.id}`, - ); - - return [createdAppointment, createdProcess]; - }); - - this.logger.log( - `[createPending] Transação concluída com sucesso! Appointment: ${appointment.id}, Process: ${process.id}`, - ); - - return this.mapToResponseEntity(appointment, client, specialist, product); - } catch (error) { - this.logger.error(`[createPending] ERRO CRÍTICO na transação:`); - this.logger.error( - `[createPending] Tipo do erro: ${error?.constructor?.name}`, - ); - this.logger.error(`[createPending] Mensagem: ${error?.message}`); - throw error; - } + return { appointment, process, product }; + }, + ); + return Object.assign( + this.mapToResponseEntity(appointment, client, specialist, product), + { + process_id: process.id, + ...(schedulingMethod === AppointmentSchedulingMethod.EMAIL + ? { specialist_contact_email: specialist.email } + : {}), + }, + ); } /** @@ -1552,6 +1420,10 @@ export class AppointmentsService { where: { specialist_id: specialistId, status: StatusAgendamento.PENDING, + OR: [ + { process: { is: null } }, + { process: { is: { removed_at: null } } }, + ], }, include: { client: true, specialist: true }, orderBy: { created_at: 'desc' }, @@ -1562,6 +1434,10 @@ export class AppointmentsService { where: { specialist_id: specialistId, status: StatusAgendamento.PENDING, + OR: [ + { process: { is: null } }, + { process: { is: { removed_at: null } } }, + ], }, }), ]); @@ -1607,6 +1483,7 @@ export class AppointmentsService { appointmentId: string, userId: string, appointmentDatetime?: string | Date, + context?: ActorContext, ): Promise { this.logger.log( `[confirmPending] Confirmando agendamento ${appointmentId} por ${userId}`, @@ -1617,7 +1494,7 @@ export class AppointmentsService { include: { client: true, specialist: true, process: true }, }); - if (!appointment) { + if (!appointment || appointment.process?.removed_at) { throw new NotFoundException({ success: false, error: { code: 404, message: 'Agendamento não encontrado' }, @@ -1625,7 +1502,8 @@ export class AppointmentsService { } // Apenas especialista pode confirmar - if (appointment.specialist_id !== userId) { + const representedSpecialistId = context?.specialistId ?? userId; + if (appointment.specialist_id !== representedSpecialistId) { throw new ForbiddenException({ success: false, error: { @@ -1667,6 +1545,11 @@ export class AppointmentsService { // Atualizar para SCHEDULED e atualizar Process para NEGOTIATION em transação const [updated, process] = await this.prisma.$transaction(async (tx) => { + // Ordem global dos advisory locks: agenda → produto → deduplicação. + // updateStatus já usa agenda → produto; manter a mesma ordem elimina o + // ciclo em que cada transação aguardava o lock retido pela outra. + await acquireSpecialistScheduleLock(tx, appointment.specialist_id); + await validateSpecialistProductAssociation(tx, { specialistId: appointment.specialist_id, productType: appointment.product_type, @@ -1684,6 +1567,7 @@ export class AppointmentsService { if (isConsultancy) { await acquireActiveProcessDedupLock(tx, processScope); + await assertNoActiveProcess(tx, processScope, appointment.process?.id); const existingAppointment = await tx.appointment.findFirst({ where: { id: { not: appointmentId }, @@ -1717,19 +1601,18 @@ export class AppointmentsService { appointment.process?.id, ); } - await acquireSpecialistScheduleLock(tx, appointment.specialist_id); - const lockedAppointment = await tx.appointment.findUnique({ where: { id: appointmentId }, include: { client: true, specialist: true, process: true }, }); - if (!lockedAppointment) { + if (!lockedAppointment || lockedAppointment.process?.removed_at) { throw new NotFoundException({ success: false, error: { code: 404, message: 'Agendamento não encontrado' }, }); } - if (lockedAppointment.specialist_id !== userId) { + this.assertRepresentedSpecialist(context, lockedAppointment.specialist_id); + if (lockedAppointment.specialist_id !== representedSpecialistId) { throw new ForbiddenException({ success: false, error: { @@ -1879,6 +1762,19 @@ export class AppointmentsService { }, }); + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'APPOINTMENT_CONFIRM', + resourceType: 'APPOINTMENT', + resourceId: appointmentId, + metadata: { processId: updatedProcess.id, confirmedDateTime }, + }, + tx, + ); + } + return [updatedApt, updatedProcess]; }); @@ -1941,17 +1837,19 @@ export class AppointmentsService { async cancelPending( appointmentId: string, userId: string, + context?: ActorContext, + reason?: string, ): Promise<{ success: boolean; message: string }> { this.logger.log( `[cancelPending] Cancelando agendamento ${appointmentId} por ${userId}`, ); - const appointment = await this.prisma.appointment.findUnique({ + const candidate = await this.prisma.appointment.findUnique({ where: { id: appointmentId }, - include: { client: true, specialist: true, process: true }, + select: { id: true, client_id: true, specialist_id: true }, }); - if (!appointment) { + if (!candidate) { throw new NotFoundException({ success: false, error: { code: 404, message: 'Agendamento não encontrado' }, @@ -1959,8 +1857,9 @@ export class AppointmentsService { } // Apenas cliente ou especialista podem cancelar - const isClient = appointment.client_id === userId; - const isSpecialist = appointment.specialist_id === userId; + const isClient = candidate.client_id === userId; + const representedSpecialistId = context?.specialistId ?? userId; + const isSpecialist = candidate.specialist_id === representedSpecialistId; if (!isClient && !isSpecialist) { throw new ForbiddenException({ success: false, @@ -1971,33 +1870,90 @@ export class AppointmentsService { }); } - // Só pode cancelar PENDING - if (appointment.status !== StatusAgendamento.PENDING) { - throw new BadRequestException({ - success: false, - error: { - code: 400, - message: - 'Apenas agendamentos PENDING podem ser cancelados por esta rota', - details: { current_status: appointment.status }, - }, + // Serializar com confirmação/reagendamento e revalidar o estado sob lock. + const appointment = await this.prisma.$transaction(async (tx) => { + await acquireSpecialistScheduleLock(tx, candidate.specialist_id); + const lockedAppointment = await tx.appointment.findUnique({ + where: { id: appointmentId }, + include: { client: true, specialist: true, process: true }, }); - } + if (!lockedAppointment || lockedAppointment.process?.removed_at) { + throw new NotFoundException({ + success: false, + error: { code: 404, message: 'Agendamento não encontrado' }, + }); + } + if ( + lockedAppointment.client_id !== userId && + lockedAppointment.specialist_id !== representedSpecialistId + ) { + throw new ForbiddenException({ + success: false, + error: { + code: 403, + message: 'Sem permissão para cancelar este agendamento', + }, + }); + } + this.assertRepresentedSpecialist(context, lockedAppointment.specialist_id); + if (lockedAppointment.status !== StatusAgendamento.PENDING) { + throw new BadRequestException({ + success: false, + error: { + code: 400, + message: + 'Apenas agendamentos PENDING podem ser cancelados por esta rota', + details: { current_status: lockedAppointment.status }, + }, + }); + } - // Deletar appointment e process em transação - await this.prisma.$transaction(async (tx) => { // Se existe process, deletar histórico e process primeiro - if (appointment.process) { + if (lockedAppointment.process) { + if (lockedAppointment.process.status !== ProcessStatus.SCHEDULING) { + throw new BadRequestException( + 'Não é possível cancelar uma reunião cujo processo já avançou', + ); + } + const processClaim = await tx.process.updateMany({ + where: { + id: lockedAppointment.process.id, + status: ProcessStatus.SCHEDULING, + updated_at: lockedAppointment.process.updated_at, + }, + data: { updated_at: new Date() }, + }); + if (processClaim.count !== 1) { + throw new ConflictException( + 'O processo foi alterado enquanto o agendamento era cancelado', + ); + } await tx.processStatusHistory.deleteMany({ - where: { processId: appointment.process.id }, + where: { processId: lockedAppointment.process.id }, }); await tx.process.delete({ - where: { id: appointment.process.id }, + where: { id: lockedAppointment.process.id }, }); this.logger.log( - `[cancelPending] Process ${appointment.process.id} deletado`, + `[cancelPending] Process ${lockedAppointment.process.id} deletado`, + ); + } + + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'APPOINTMENT_CANCEL', + resourceType: 'APPOINTMENT', + resourceId: appointmentId, + metadata: { + processId: lockedAppointment.process?.id ?? null, + reason: reason ?? null, + }, + }, + tx, ); } @@ -2007,6 +1963,8 @@ export class AppointmentsService { }); this.logger.log(`[cancelPending] Appointment ${appointmentId} deletado`); + + return lockedAppointment; }); // Fire-and-forget: notificar a outra parte sobre o cancelamento @@ -2053,14 +2011,20 @@ export class AppointmentsService { * @param specialistId ID do especialista (UUID) * @param productType Tipo de produto (CAR, BOAT, AIRCRAFT) * @param productId UUID do produto - * @returns Appointment se encontrado, caso contrário null + * @returns Discriminante e snapshot mínimo do pedido pertencente ao cliente */ async findExistingAppointment( clientId: string, specialistId: string, productType: ProductType, productId: string, - ): Promise { + ): Promise { + const productField = + productType === ProductType.CAR + ? 'car_id' + : productType === ProductType.BOAT + ? 'boat_id' + : 'aircraft_id'; const appointment = await this.prisma.appointment.findFirst({ where: { client_id: clientId, @@ -2070,24 +2034,49 @@ export class AppointmentsService { 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, + }, + }, + }, + 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 } }, }, - include: { client: true, specialist: true }, }); - if (!appointment) { - return null; + if ( + !appointment || + appointment.client_id !== clientId || + !appointment.process || + appointment.process.client_id !== clientId + ) { + return { exists: false }; } - - const product = await this.getProductByType( - appointment.product_type, - appointment.product_id, - ); - return this.mapToResponseEntity( - appointment, - appointment.client, - appointment.specialist, - product, - ); + const specialistContactEmail = appointment.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 + ? { specialist_contact_email: specialistContactEmail } + : {}), + }; } async registerCalendlyScheduled( @@ -2099,11 +2088,28 @@ export class AppointmentsService { calendly_sync_status: CalendlySyncStatus; appointment_datetime: Date | null; }> { + const eventReference = parseCalendlyResourceUri(dto.event_uri, 'event'); + const inviteeReference = parseCalendlyResourceUri( + dto.invitee_uri, + 'invitee', + ); + if (!eventReference || !inviteeReference) { + throw new BadRequestException('URIs do Calendly inválidas'); + } + if (eventReference.eventId !== inviteeReference.eventId) { + throw new BadRequestException( + 'URIs do Calendly pertencem a eventos diferentes', + ); + } + const eventUri = eventReference.canonicalUri; + const inviteeUri = inviteeReference.canonicalUri; + const appointment = await this.prisma.appointment.findUnique({ where: { id: appointmentId }, + include: { process: { select: { removed_at: true } } }, }); - if (!appointment) { + if (!appointment || appointment.process?.removed_at) { throw new NotFoundException({ success: false, error: { @@ -2153,10 +2159,7 @@ export class AppointmentsService { throw this.buildRescheduleAlreadyUsedError(appointmentId); } - if ( - appointment.calendly_event_uri && - appointment.calendly_event_uri === dto.event_uri - ) { + if (appointment.calendly_sync_status === CalendlySyncStatus.FAILED) { return { appointment_id: appointment.id, calendly_sync_status: appointment.calendly_sync_status, @@ -2164,41 +2167,76 @@ export class AppointmentsService { }; } - let scheduledStartTime = dto.scheduled_start_time - ? parseDate(dto.scheduled_start_time) - : null; - - if (dto.scheduled_start_time && !scheduledStartTime) { - throw new BadRequestException({ - success: false, - error: { - code: 400, - message: 'scheduled_start_time inválido', - }, - }); + if ( + appointment.calendly_event_uri && + parseCalendlyResourceUri(appointment.calendly_event_uri, 'event') + ?.canonicalUri === eventUri + ) { + const storedInviteeReference = appointment.calendly_invitee_uri + ? parseCalendlyResourceUri(appointment.calendly_invitee_uri, 'invitee') + : null; + if ( + appointment.calendly_invitee_uri && + storedInviteeReference?.canonicalUri !== inviteeUri + ) { + throw new ConflictException( + 'O evento do Calendly já está associado a outro convidado', + ); + } + if (storedInviteeReference?.canonicalUri === inviteeUri) { + let canonicalized = true; + if ( + appointment.calendly_event_uri !== eventUri || + appointment.calendly_invitee_uri !== inviteeUri + ) { + const repair = await this.prisma.appointment.updateMany({ + where: { + id: appointment.id, + calendly_event_uri: appointment.calendly_event_uri, + calendly_invitee_uri: appointment.calendly_invitee_uri, + }, + data: { + calendly_event_uri: eventUri, + calendly_invitee_uri: inviteeUri, + }, + }); + canonicalized = repair.count === 1; + } + if (canonicalized && this.hasTrustedCalendlySchedule(appointment)) { + return { + appointment_id: appointment.id, + calendly_sync_status: appointment.calendly_sync_status, + appointment_datetime: appointment.appointment_datetime, + }; + } + } } - if (!scheduledStartTime) { - try { - scheduledStartTime = - await this.calendlyIntegrationService.resolveScheduledStartTime( - appointment.specialist_id, - dto.event_uri, - dto.invitee_uri, - ); - } catch (error: any) { - this.logger.warn( - `[registerCalendlyScheduled] Falha ao buscar horário no Calendly API: ${error?.message}`, + let scheduledStartTime: Date | null = null; + try { + scheduledStartTime = + await this.calendlyIntegrationService.resolveScheduledStartTime( + appointment.specialist_id, + eventUri, + inviteeUri, + appointment.client_id, ); + } catch (error: any) { + if (error instanceof BadRequestException) { + throw error; } + this.logger.warn( + `[registerCalendlyScheduled] Falha ao buscar horário no Calendly API: ${error?.message}`, + ); } const updated = await this.prisma.$transaction(async (tx) => { await acquireSpecialistScheduleLock(tx, appointment.specialist_id); const lockedAppointment = await tx.appointment.findUnique({ where: { id: appointmentId }, + include: { process: { select: { removed_at: true } } }, }); - if (!lockedAppointment) { + if (!lockedAppointment || lockedAppointment.process?.removed_at) { throw new NotFoundException({ success: false, error: { code: 404, message: 'Agendamento não encontrado' }, @@ -2239,12 +2277,34 @@ export class AppointmentsService { if (lockedAppointment.specialist_rescheduled_at) { throw this.buildRescheduleAlreadyUsedError(appointmentId); } - if (lockedAppointment.calendly_event_uri === dto.event_uri) { + if ( + lockedAppointment.calendly_sync_status === CalendlySyncStatus.FAILED + ) { + return lockedAppointment; + } + if ( + lockedAppointment.calendly_event_uri && + parseCalendlyResourceUri(lockedAppointment.calendly_event_uri, 'event') + ?.canonicalUri === eventUri + ) { + if ( + lockedAppointment.calendly_invitee_uri && + parseCalendlyResourceUri( + lockedAppointment.calendly_invitee_uri, + 'invitee', + )?.canonicalUri !== inviteeUri + ) { + throw new ConflictException( + 'O evento do Calendly já está associado a outro convidado', + ); + } + } + + if (!scheduledStartTime) { return lockedAppointment; } - const targetDateTime = - scheduledStartTime || lockedAppointment.appointment_datetime; + const targetDateTime = scheduledStartTime; if (targetDateTime && !isFutureDate(targetDateTime)) { throw new BadRequestException( 'O horário sincronizado do Calendly deve ser futuro', @@ -2262,8 +2322,8 @@ export class AppointmentsService { return tx.appointment.update({ where: { id: lockedAppointment.id }, data: { - calendly_event_uri: dto.event_uri, - calendly_invitee_uri: dto.invitee_uri, + calendly_event_uri: eventUri, + calendly_invitee_uri: inviteeUri, calendly_scheduled_at: dto.client_observed_at ? new Date(dto.client_observed_at) : new Date(), @@ -2281,6 +2341,18 @@ export class AppointmentsService { }; } + private hasTrustedCalendlySchedule(appointment: { + status: StatusAgendamento; + calendly_sync_status?: CalendlySyncStatus | null; + appointment_datetime?: Date | null; + }): boolean { + return ( + appointment.status === StatusAgendamento.SCHEDULED || + (appointment.calendly_sync_status === CalendlySyncStatus.SYNCED && + Boolean(appointment.appointment_datetime)) + ); + } + async getCalendlySyncStatus( appointmentId: string, userId: string, @@ -2302,10 +2374,11 @@ export class AppointmentsService { appointment_datetime: true, calendly_sync_status: true, calendly_last_sync_at: true, + process: { select: { removed_at: true } }, }, }); - if (!appointment) { + if (!appointment || appointment.process?.removed_at) { throw new NotFoundException({ success: false, error: { diff --git a/backend/src/features/appointments/calendly-integration.service.spec.ts b/backend/src/features/appointments/calendly-integration.service.spec.ts index 19706dc7..b20bb0e3 100644 --- a/backend/src/features/appointments/calendly-integration.service.spec.ts +++ b/backend/src/features/appointments/calendly-integration.service.spec.ts @@ -1,7 +1,843 @@ -import { AppointmentSchedulingMethod } from '@prisma/client'; +import { + BadRequestException, + ConflictException, + ForbiddenException, + InternalServerErrorException, +} from '@nestjs/common'; +import { + AppointmentSchedulingMethod, + CalendlySyncStatus, + StatusAgendamento, +} from '@prisma/client'; import { CalendlyIntegrationService } from './calendly-integration.service'; +import axios from 'axios'; +import { createHmac } from 'crypto'; + +jest.mock('axios'); + +describe('CalendlyIntegrationService connection lifecycle', () => { + const originalEnv = { ...process.env }; + beforeEach(() => { + jest.resetAllMocks(); + process.env.CALENDLY_OAUTH_CLIENT_ID = 'client-id'; + process.env.CALENDLY_OAUTH_CLIENT_SECRET = 'client-secret'; + process.env.CALENDLY_OAUTH_REDIRECT_URI = 'https://app.test/callback'; + process.env.CALENDLY_TOKEN_ENCRYPTION_KEY = + '12345678901234567890123456789012'; + delete process.env.CALENDLY_WEBHOOK_CALLBACK_URL; + delete process.env.CALENDLY_WEBHOOK_SIGNING_KEY; + }); + afterAll(() => { + process.env = originalEnv; + }); + + function makeCallbackService(scheduling_url: string | undefined) { + const prisma = { + calendlyOauthState: { + findUnique: jest.fn().mockResolvedValue({ + id: 'state-1', + user_id: 'specialist-1', + used_at: null, + expires_at: new Date(Date.now() + 60000), + user: { id: 'specialist-1', role: 'SPECIALIST' }, + }), + update: jest.fn().mockResolvedValue({}), + }, + calendlyConnection: { + upsert: jest.fn().mockResolvedValue({ user_id: 'specialist-1' }), + }, + user: { update: jest.fn().mockResolvedValue({}) }, + }; + jest.mocked(axios.post).mockResolvedValue({ + data: { + access_token: 'access', + refresh_token: 'refresh', + expires_in: 3600, + }, + }); + jest.mocked(axios.get).mockResolvedValue({ + data: { + resource: { + uri: 'https://api.calendly.com/users/1', + current_organization: 'https://api.calendly.com/organizations/1', + scheduling_url, + }, + }, + }); + return { prisma, service: new CalendlyIntegrationService(prisma as any) }; + } + + it('expõe degradação da subscription sem desconectar o OAuth', async () => { + const prisma = { + calendlyConnection: { + findUnique: jest.fn().mockResolvedValue({ + is_active: true, + calendly_user_uri: 'https://api.calendly.com/users/1', + expires_at: null, + last_error: 'webhook_subscription_failed', + }), + }, + }; + + await expect( + new CalendlyIntegrationService(prisma as any).getOAuthStatus( + 'specialist-1', + ), + ).resolves.toEqual({ + connected: true, + calendly_user_uri: 'https://api.calendly.com/users/1', + expires_at: null, + is_active: true, + last_error: 'webhook_subscription_failed', + }); + }); + + it('persiste scheduling_url validada no callback OAuth', async () => { + const { prisma, service } = makeCallbackService( + 'https://calendly.com/ana/reuniao', + ); + expect(await service.handleOAuthCallback('code', 'state')).toBe( + 'specialist-1', + ); + expect(prisma.user.update).toHaveBeenCalledWith({ + where: { id: 'specialist-1' }, + data: { + calendly_url: 'https://calendly.com/ana/reuniao', + calendly_user_uri: 'https://api.calendly.com/users/1', + calendly_organization_uri: 'https://api.calendly.com/organizations/1', + }, + }); + expect(prisma.calendlyConnection.upsert).toHaveBeenCalledWith( + expect.objectContaining({ + create: expect.objectContaining({ is_active: true }), + update: expect.objectContaining({ is_active: true }), + }), + ); + }); + + it.each([ + undefined, + 'http://calendly.com/ana', + 'https://evilcalendly.com/ana', + 'https://calendly.com.evil.test/ana', + 'https://calendly.com@evil.test/ana', + 'not-a-url', + ])('rejeita scheduling_url inválida antes de persistir: %s', async (url) => { + const { prisma, service } = makeCallbackService(url); + await expect(service.handleOAuthCallback('code', 'state')).rejects.toThrow( + 'Calendly não retornou URL de agendamento válida', + ); + expect(prisma.calendlyConnection.upsert).not.toHaveBeenCalled(); + expect(prisma.user.update).not.toHaveBeenCalled(); + expect(prisma.calendlyOauthState.update).not.toHaveBeenCalled(); + }); + + it('mantém a conexão OAuth explícita sem gravar subscription quando sua criação falha', async () => { + process.env.CALENDLY_WEBHOOK_CALLBACK_URL = + 'https://api.example.test/appointments/calendly/webhook'; + process.env.CALENDLY_WEBHOOK_SIGNING_KEY = 'local-oauth-signing-key'; + const { prisma, service } = makeCallbackService( + 'https://calendly.com/ana/reuniao', + ); + const connection = { + id: 'connection-1', + user_id: 'specialist-1', + access_token_encrypted: (service as any).encryptToken('access'), + calendly_user_uri: 'https://api.calendly.com/users/1', + calendly_organization_uri: 'https://api.calendly.com/organizations/1', + }; + prisma.calendlyConnection.upsert.mockResolvedValue(connection); + Object.assign(prisma.calendlyConnection, { + findUnique: jest.fn().mockResolvedValue(connection), + update: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }); + jest + .mocked(axios.post) + .mockResolvedValueOnce({ + data: { + access_token: 'access', + refresh_token: 'refresh', + expires_in: 3600, + }, + }) + .mockRejectedValueOnce(new Error('subscription unavailable')); + + await expect(service.handleOAuthCallback('code', 'state')).resolves.toBe( + 'specialist-1', + ); + expect(prisma.user.update).toHaveBeenCalledTimes(1); + expect(prisma.calendlyOauthState.update).toHaveBeenCalledTimes(1); + expect((prisma.calendlyConnection as any).update).not.toHaveBeenCalled(); + expect((prisma.calendlyConnection as any).updateMany).toHaveBeenCalledWith({ + where: { + id: connection.id, + access_token_encrypted: connection.access_token_encrypted, + is_active: true, + }, + data: { last_error: 'webhook_subscription_failed' }, + }); + }); + + it('desativa e limpa URL e URIs em uma transação', async () => { + const tx = { + calendlyConnection: { + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + user: { update: jest.fn().mockResolvedValue({}) }, + }; + const prisma = { + $transaction: jest.fn(async (callback: any) => + typeof callback === 'function' ? callback(tx) : Promise.all(callback), + ), + calendlyConnection: { + findUnique: jest.fn().mockResolvedValue({ id: 'connection-1' }), + update: jest.fn().mockResolvedValue({}), + }, + user: { update: jest.fn().mockResolvedValue({}) }, + }; + await new CalendlyIntegrationService(prisma as any).disconnect( + 'specialist-1', + ); + expect(prisma.$transaction).toHaveBeenCalledTimes(1); + expect(tx.calendlyConnection.updateMany).toHaveBeenCalledWith({ + where: { user_id: 'specialist-1' }, + data: { is_active: false, last_sync_at: expect.any(Date) }, + }); + expect(tx.user.update).toHaveBeenCalledWith({ + where: { id: 'specialist-1' }, + data: { + calendly_url: null, + calendly_user_uri: null, + calendly_organization_uri: null, + }, + }); + }); + + function makeRefreshService() { + const prisma = { + calendlyConnection: { + findUnique: jest.fn(), + update: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + user: { + findUnique: jest.fn(), + }, + }; + const service = new CalendlyIntegrationService(prisma as any); + const connection = { + id: 'connection-1', + user_id: 'specialist-1', + is_active: true, + calendly_user_uri: 'https://api.calendly.com/users/1', + expires_at: new Date(0), + access_token_encrypted: (service as any).encryptToken('expired-access'), + refresh_token_encrypted: (service as any).encryptToken('valid-refresh'), + }; + prisma.calendlyConnection.findUnique.mockResolvedValue(connection); + prisma.calendlyConnection.update.mockImplementation(({ data }) => + Promise.resolve({ ...connection, ...data }), + ); + return { service, prisma, connection }; + } + + it.each([ + 'https://evil/scheduled_events/event-1', + 'https://evil.test/scheduled_events/event-1', + 'https://calendly.com.evil/scheduled_events/event-1', + 'https://api.calendly.com.evil.test/scheduled_events/event-1', + 'http://api.calendly.com/scheduled_events/event-1', + 'https://user@api.calendly.com/scheduled_events/event-1', + 'https://api.calendly.com:444/scheduled_events/event-1', + 'https://127.0.0.1/scheduled_events/event-1', + ])( + 'não envia o Bearer token para event_uri não confiável: %s', + async (uri) => { + const { service } = makeRefreshService(); + + await expect( + service.resolveScheduledStartTime('specialist-1', uri), + ).rejects.toThrow('event_uri do Calendly inválida'); + expect(axios.get).not.toHaveBeenCalled(); + }, + ); + + it('não segue redirect ao buscar recurso autenticado do Calendly', async () => { + const { service } = makeRefreshService(); + jest.mocked(axios.get).mockRejectedValueOnce({ + response: { + status: 302, + headers: { location: 'http://127.0.0.1/internal' }, + }, + }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/event-1', + ), + ).rejects.toBeDefined(); + expect(axios.get).toHaveBeenCalledTimes(1); + expect(axios.get).toHaveBeenCalledWith( + 'https://api.calendly.com/scheduled_events/event-1', + expect.objectContaining({ maxRedirects: 0 }), + ); + }); + + it.each([ + 'https://calendly.com/api/v2/scheduled_events/event-1', + 'https://api.calendly.com/api/v2/scheduled_events/event-1', + ])( + 'normaliza URI oficial antes da requisição autenticada: %s', + async (uri) => { + const { service } = makeRefreshService(); + jest.mocked(axios.get).mockResolvedValueOnce({ + data: { + resource: { + start_time: '2099-01-01T10:00:00.000Z', + event_memberships: [{ user: 'https://api.calendly.com/users/1' }], + }, + }, + }); + + await expect( + service.resolveScheduledStartTime('specialist-1', uri), + ).resolves.toEqual(new Date('2099-01-01T10:00:00.000Z')); + expect(axios.get).toHaveBeenCalledWith( + 'https://api.calendly.com/scheduled_events/event-1', + expect.objectContaining({ maxRedirects: 0 }), + ); + }, + ); + + it('rejeita evento divergente retornado pelo convidado mesmo quando há horário', async () => { + const { service } = makeRefreshService(); + jest.mocked(axios.get).mockResolvedValueOnce({ + data: { + resource: { + event: 'https://api.calendly.com/scheduled_events/event-2', + start_time: '2099-01-01T10:00:00.000Z', + }, + }, + }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://calendly.com/api/v2/scheduled_events/event-1', + 'https://calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', + ), + ).rejects.toThrow('URIs do Calendly pertencem a eventos diferentes'); + expect(axios.get).toHaveBeenCalledTimes(1); + }); + + it('aceita evento equivalente retornado pelo convidado e mantém fetch canônico', async () => { + const { service } = makeRefreshService(); + jest + .mocked(axios.get) + .mockResolvedValueOnce({ + data: { + resource: { + event: 'https://api.calendly.com/api/v2/scheduled_events/event-1', + start_time: '2099-01-01T10:00:00.000Z', + }, + }, + }) + .mockResolvedValueOnce({ + data: { + resource: { + start_time: '2099-01-01T10:00:00.000Z', + event_memberships: [{ user: 'https://api.calendly.com/users/1' }], + }, + }, + }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://calendly.com/api/v2/scheduled_events/event-1', + 'https://calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', + ), + ).resolves.toEqual(new Date('2099-01-01T10:00:00.000Z')); + expect(axios.get).toHaveBeenCalledWith( + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + expect.objectContaining({ maxRedirects: 0 }), + ); + }); + + it('rejeita invitee autoritativo cujo email pertence a outro cliente', async () => { + const { service, prisma } = makeRefreshService(); + prisma.user.findUnique.mockResolvedValue({ email: 'cliente@example.com' }); + jest.mocked(axios.get).mockResolvedValueOnce({ + data: { + resource: { + email: 'outra-pessoa@example.com', + event: 'https://api.calendly.com/scheduled_events/event-1', + start_time: '2099-01-01T10:00:00.000Z', + }, + }, + }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/event-1', + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + 'client-1', + ), + ).rejects.toThrow('não pertence ao cliente do agendamento'); + expect(prisma.calendlyConnection.update).not.toHaveBeenCalled(); + }); + + it('aceita email autoritativo equivalente ignorando espaços e caixa', async () => { + const { service, prisma } = makeRefreshService(); + prisma.user.findUnique.mockResolvedValue({ + email: ' Cliente@Example.com ', + }); + jest + .mocked(axios.get) + .mockResolvedValueOnce({ + data: { + resource: { + email: 'cliente@example.COM', + event: 'https://api.calendly.com/scheduled_events/event-1', + start_time: '2099-01-01T10:00:00.000Z', + }, + }, + }) + .mockResolvedValueOnce({ + data: { + resource: { + start_time: '2099-01-01T10:00:00.000Z', + event_memberships: [{ user: 'https://api.calendly.com/users/1' }], + }, + }, + }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/event-1', + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + 'client-1', + ), + ).resolves.toEqual(new Date('2099-01-01T10:00:00.000Z')); + }); + + it('rejeita horário do invitee quando o evento não pertence ao usuário Calendly conectado', async () => { + const { service, prisma } = makeRefreshService(); + prisma.user.findUnique.mockResolvedValue({ email: 'cliente@example.com' }); + jest + .mocked(axios.get) + .mockResolvedValueOnce({ + data: { + resource: { + email: 'cliente@example.com', + event: 'https://api.calendly.com/scheduled_events/event-1', + start_time: '2099-01-01T10:00:00.000Z', + }, + }, + }) + .mockResolvedValueOnce({ + data: { + resource: { + start_time: '2099-01-01T10:00:00.000Z', + event_memberships: [ + { user: 'https://api.calendly.com/users/another-user' }, + ], + }, + }, + }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/event-1', + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + 'client-1', + ), + ).rejects.toThrow('Evento do Calendly não pertence ao especialista'); + expect(axios.get).toHaveBeenCalledTimes(2); + expect(prisma.calendlyConnection.update).not.toHaveBeenCalled(); + }); + + it.each([ + undefined, + null, + {}, + { resource: null }, + { resource: { start_time: '2099-01-01T10:00:00.000Z' } }, + { + resource: { + start_time: '2099-01-01T10:00:00.000Z', + event_memberships: {}, + }, + }, + ])( + 'falha fechado para shape de evento Calendly inválido: %p', + async (data) => { + const { service, prisma } = makeRefreshService(); + jest.mocked(axios.get).mockResolvedValueOnce({ data }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/event-1', + ), + ).rejects.toBeInstanceOf(BadRequestException); + expect(prisma.calendlyConnection.update).not.toHaveBeenCalled(); + }, + ); + + it('usa o horário autoritativo do evento após validar a membership', async () => { + const { service } = makeRefreshService(); + jest + .mocked(axios.get) + .mockResolvedValueOnce({ + data: { + resource: { + event: 'https://api.calendly.com/scheduled_events/event-1', + start_time: '2099-01-01T09:00:00.000Z', + }, + }, + }) + .mockResolvedValueOnce({ + data: { + resource: { + start_time: '2099-01-01T10:00:00.000Z', + event_memberships: [{ user: 'https://api.calendly.com/users/1' }], + }, + }, + }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/event-1', + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + ), + ).resolves.toEqual(new Date('2099-01-01T10:00:00.000Z')); + expect(axios.get).toHaveBeenCalledTimes(2); + }); + + it('rejeita URI de evento não confiável retornada pelo recurso de convidado', async () => { + const { service } = makeRefreshService(); + jest.mocked(axios.get).mockResolvedValueOnce({ + data: { resource: { event: 'http://127.0.0.1/internal' } }, + }); + + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + null, + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + ), + ).rejects.toThrow('event_uri do Calendly inválida'); + expect(axios.get).toHaveBeenCalledTimes(1); + }); + + it('mantém conexão ativa quando token expirado é renovado com sucesso', async () => { + const { service, prisma } = makeRefreshService(); + jest + .mocked(axios.get) + .mockRejectedValueOnce({ response: { status: 401 } }) + .mockResolvedValueOnce({ + data: { + resource: { + start_time: '2099-01-01T10:00:00.000Z', + event_memberships: [{ user: 'https://api.calendly.com/users/1' }], + }, + }, + }); + jest.mocked(axios.post).mockResolvedValue({ + data: { + access_token: 'renewed-access', + refresh_token: 'renewed-refresh', + expires_in: 3600, + }, + }); + expect( + await service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/1', + ), + ).toEqual(new Date('2099-01-01T10:00:00.000Z')); + expect( + prisma.calendlyConnection.update.mock.calls.every( + ([input]) => input.data.is_active !== false, + ), + ).toBe(true); + expect(axios.get).toHaveBeenLastCalledWith( + 'https://api.calendly.com/scheduled_events/1', + expect.objectContaining({ + headers: { Authorization: 'Bearer renewed-access' }, + }), + ); + }); + + it('persiste desativação e erro após invalid_grant definitivo', async () => { + const { service, prisma, connection } = makeRefreshService(); + const error = { + response: { status: 400, data: { error: 'invalid_grant' } }, + }; + jest.mocked(axios.get).mockRejectedValue({ response: { status: 401 } }); + jest.mocked(axios.post).mockRejectedValue(error); + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/1', + ), + ).rejects.toBe(error); + expect(prisma.calendlyConnection.updateMany).toHaveBeenCalledWith({ + where: { + id: 'connection-1', + refresh_token_encrypted: connection.refresh_token_encrypted, + is_active: true, + }, + data: { is_active: false, last_error: 'invalid_grant' }, + }); + }); + + it('preserva reconexão enquanto refresh antigo está pendente com invalid_grant', async () => { + const { service, prisma } = makeCallbackService( + 'https://calendly.com/ana/reuniao', + ); + const storedConnection = { + id: 'connection-1', + user_id: 'specialist-1', + is_active: true, + last_error: null as string | null, + calendly_user_uri: 'https://api.calendly.com/users/1', + access_token_encrypted: (service as any).encryptToken('old-access'), + refresh_token_encrypted: (service as any).encryptToken('old-refresh'), + }; + const connectionClient = { + ...prisma.calendlyConnection, + findUnique: jest.fn(async () => ({ ...storedConnection })), + update: jest.fn(async ({ data }) => { + Object.assign(storedConnection, data); + return { ...storedConnection }; + }), + updateMany: jest.fn(async ({ where, data }) => { + const matches = Object.entries(where).every( + ([key, value]) => + storedConnection[key as keyof typeof storedConnection] === value, + ); + if (matches) Object.assign(storedConnection, data); + return { count: matches ? 1 : 0 }; + }), + }; + prisma.calendlyConnection = connectionClient; + connectionClient.upsert.mockImplementation(async ({ update }) => { + Object.assign(storedConnection, update); + return { ...storedConnection }; + }); + + let rejectRefresh!: (error: unknown) => void; + let markRefreshStarted!: () => void; + const refreshStarted = new Promise((resolve) => { + markRefreshStarted = resolve; + }); + jest.mocked(axios.get).mockRejectedValueOnce({ response: { status: 401 } }); + jest.mocked(axios.post).mockImplementationOnce( + () => + new Promise((_, reject) => { + rejectRefresh = reject; + markRefreshStarted(); + }), + ); + const error = { + response: { status: 400, data: { error: 'invalid_grant' } }, + }; + const refreshResult = expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/1', + ), + ).rejects.toBe(error); + await refreshStarted; + await service.handleOAuthCallback('new-code', 'new-state'); + const reconnectedTokens = { + access_token_encrypted: storedConnection.access_token_encrypted, + refresh_token_encrypted: storedConnection.refresh_token_encrypted, + }; + expect( + (service as any).decryptToken(reconnectedTokens.access_token_encrypted), + ).toBe('access'); + expect( + (service as any).decryptToken(reconnectedTokens.refresh_token_encrypted), + ).toBe('refresh'); + + rejectRefresh(error); + await refreshResult; + expect(storedConnection).toEqual( + expect.objectContaining({ + ...reconnectedTokens, + is_active: true, + last_error: null, + }), + ); + }); + + it('preserva conexão ativa após falha transitória de refresh', async () => { + const { service, prisma } = makeRefreshService(); + jest.mocked(axios.get).mockRejectedValue({ response: { status: 401 } }); + jest.mocked(axios.post).mockRejectedValue({ response: { status: 503 } }); + await expect( + service.resolveScheduledStartTime( + 'specialist-1', + 'https://api.calendly.com/scheduled_events/1', + ), + ).rejects.toBeDefined(); + expect(prisma.calendlyConnection.update).not.toHaveBeenCalled(); + expect(prisma.calendlyConnection.updateMany).not.toHaveBeenCalled(); + }); +}); + +describe('CalendlyIntegrationService webhook authentication', () => { + const originalEnv = { ...process.env }; + const signingKey = 'calendly-test-signing-key'; + const nowSeconds = 1_800_000_000; + const rawBody = '{"event":"invitee.created"}'; + + function makeService() { + const prisma = { + calendlyConnection: { + findUnique: jest.fn(), + update: jest.fn(), + }, + }; + const service = new CalendlyIntegrationService(prisma as any); + jest.spyOn(service as any, 'now').mockReturnValue(nowSeconds * 1000); + return { prisma, service }; + } + + function signature(timestamp: string) { + const digest = createHmac('sha256', signingKey) + .update(`${timestamp}.${rawBody}`) + .digest('hex'); + return `t=${timestamp},v1=${digest}`; + } + + beforeEach(() => { + jest.clearAllMocks(); + process.env.CALENDLY_WEBHOOK_SIGNING_KEY = signingKey; + process.env.CALENDLY_WEBHOOK_CALLBACK_URL = + 'https://api.example.test/appointments/calendly/webhook'; + process.env.CALENDLY_TOKEN_ENCRYPTION_KEY = + '12345678901234567890123456789012'; + }); + + afterAll(() => { + process.env = originalEnv; + }); + + it('falha fechado quando a chave de assinatura não está configurada', () => { + delete process.env.CALENDLY_WEBHOOK_SIGNING_KEY; + const { service } = makeService(); + + expect(() => + (service as any).validateWebhookSignature( + rawBody, + signature(String(nowSeconds)), + ), + ).toThrow(InternalServerErrorException); + }); + + it.each([ + ['não numérico', 'not-a-timestamp'], + ['fracionário', `${nowSeconds}.5`], + ['antigo', String(nowSeconds - 301)], + ['futuro', String(nowSeconds + 301)], + ])('rejeita timestamp %s na assinatura', (_label, timestamp) => { + const { service } = makeService(); + + expect(() => + (service as any).validateWebhookSignature(rawBody, signature(timestamp)), + ).toThrow(ForbiddenException); + }); + + it('aceita retry idêntico dentro da janela válida para permitir retentativa do Calendly', () => { + const { service } = makeService(); + const header = signature(String(nowSeconds)); + + expect(() => + (service as any).validateWebhookSignature(rawBody, header), + ).not.toThrow(); + expect(() => + (service as any).validateWebhookSignature(rawBody, header), + ).not.toThrow(); + }); + + it('não cria assinatura de webhook sem signing key', async () => { + delete process.env.CALENDLY_WEBHOOK_SIGNING_KEY; + const { prisma, service } = makeService(); + + await expect( + (service as any).ensureWebhookSubscription('specialist-1'), + ).rejects.toThrow(InternalServerErrorException); + expect(prisma.calendlyConnection.findUnique).not.toHaveBeenCalled(); + expect(axios.post).not.toHaveBeenCalled(); + }); + + it('não envia a chave local na criação de subscription OAuth nem mascara falhas', async () => { + const { prisma, service } = makeService(); + const connection = { + id: 'connection-1', + user_id: 'specialist-1', + calendly_user_uri: 'https://api.calendly.com/users/user-1', + calendly_organization_uri: 'https://api.calendly.com/organizations/org-1', + access_token_encrypted: (service as any).encryptToken('access-token'), + }; + prisma.calendlyConnection.findUnique.mockResolvedValue(connection); + jest + .mocked(axios.post) + .mockRejectedValueOnce({ response: { status: 422 } }); + + await expect( + (service as any).ensureWebhookSubscription('specialist-1'), + ).rejects.toBeDefined(); + expect(axios.post).toHaveBeenCalledTimes(1); + expect(axios.post).toHaveBeenCalledWith( + 'https://api.calendly.com/webhook_subscriptions', + expect.not.objectContaining({ signing_key: expect.anything() }), + expect.any(Object), + ); + expect(prisma.calendlyConnection.update).not.toHaveBeenCalled(); + }); +}); describe('CalendlyIntegrationService webhook schedule integrity', () => { + it('rejeita payload.uri e payload.invitee divergentes', async () => { + const prisma = { + appointment: { findMany: jest.fn() }, + $transaction: jest.fn(), + }; + const service = new CalendlyIntegrationService(prisma as any); + jest + .spyOn(service as any, 'validateWebhookSignature') + .mockReturnValue(undefined); + + await expect( + service.processWebhook( + { + event: 'invitee.created', + payload: { + event: 'https://api.calendly.com/scheduled_events/event-1', + uri: 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-official', + invitee: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-legacy', + }, + }, + undefined, + undefined, + ), + ).rejects.toThrow('URIs de convidado do Calendly são inconsistentes'); + expect(prisma.appointment.findMany).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + it.each([ AppointmentSchedulingMethod.EMAIL, AppointmentSchedulingMethod.PLATFORM, @@ -9,13 +845,13 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { const appointment = { id: 'appointment-1', specialist_id: 'specialist-1', - calendly_event_uri: 'https://calendly.test/events/1', + calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1', scheduling_method: method, specialist_rescheduled_at: null, }; const prisma = { appointment: { - findFirst: jest.fn().mockResolvedValue(appointment), + findMany: jest.fn().mockResolvedValue([appointment]), update: jest.fn(), }, $transaction: jest.fn(), @@ -46,12 +882,12 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { const appointment = { id: 'appointment-1', specialist_id: 'specialist-1', - calendly_event_uri: 'https://calendly.test/events/1', + calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1', scheduling_method: AppointmentSchedulingMethod.CALENDLY, specialist_rescheduled_at: new Date('2026-01-01T00:00:00.000Z'), }; const prisma = { - appointment: { findFirst: jest.fn().mockResolvedValue(appointment) }, + appointment: { findMany: jest.fn().mockResolvedValue([appointment]) }, $transaction: jest.fn(), }; const service = new CalendlyIntegrationService(prisma as any); @@ -75,15 +911,54 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { expect(prisma.$transaction).not.toHaveBeenCalled(); }); + it('ignora webhook de agendamento cujo processo foi removido', async () => { + const prisma = { + appointment: { + findMany: jest.fn().mockResolvedValue([ + { + id: 'appointment-1', + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/event-1', + process: { removed_at: new Date() }, + }, + ]), + }, + $transaction: jest.fn(), + }; + const service = new CalendlyIntegrationService(prisma as any); + jest + .spyOn(service as any, 'validateWebhookSignature') + .mockReturnValue(undefined); + + const result = await service.processWebhook( + { + event: 'invitee.created', + payload: { + event: 'https://api.calendly.com/scheduled_events/event-1', + scheduled_event: { start_time: '2099-01-01T10:00:00.000Z' }, + }, + }, + undefined, + undefined, + ); + + expect(result.processed).toBe(false); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + it('serializes and rechecks an invitee.created time before writing it', async () => { const appointment = { id: 'appointment-1', client_id: 'client-1', specialist_id: 'specialist-1', - calendly_event_uri: 'https://calendly.test/events/1', - calendly_invitee_uri: null, + calendly_event_uri: + 'https://calendly.com/api/v2/scheduled_events/event-1', + calendly_invitee_uri: + 'https://calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', calendly_sync_status: 'PENDING', appointment_datetime: null, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, }; const tx = { $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), @@ -95,7 +970,8 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { }; const prisma = { appointment: { - findFirst: jest.fn().mockResolvedValue(appointment), + findMany: jest.fn().mockResolvedValue([appointment]), + findFirst: jest.fn(), update: jest.fn().mockResolvedValue(appointment), }, $transaction: jest.fn(async (callback: (client: any) => unknown) => @@ -111,21 +987,36 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { { event: 'invitee.created', payload: { - event: appointment.calendly_event_uri, - invitee: 'https://calendly.test/invitees/1', + event: 'https://calendly.com/api/v2/scheduled_events/event-1', + uri: 'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', scheduled_event: { start_time: '2099-01-01T10:00:00.000Z', }, }, - }, + } as any, undefined, undefined, ); expect(prisma.$transaction).toHaveBeenCalledTimes(1); + expect(prisma.appointment.findMany).toHaveBeenCalledWith({ + where: { + calendly_invitee_uri: { + in: expect.arrayContaining([ + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + 'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', + 'https://calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', + ]), + }, + }, + take: 2, + include: { process: { select: { removed_at: true } } }, + }); + expect(prisma.appointment.findFirst).not.toHaveBeenCalled(); expect(tx.$queryRaw).toHaveBeenCalledTimes(1); expect(tx.appointment.findUnique).toHaveBeenCalledWith({ where: { id: appointment.id }, + include: { process: { select: { removed_at: true } } }, }); expect(tx.appointment.findFirst).toHaveBeenCalledWith( expect.objectContaining({ @@ -135,7 +1026,430 @@ describe('CalendlyIntegrationService webhook schedule integrity', () => { }), }), ); - expect(tx.appointment.update).toHaveBeenCalledTimes(1); + expect(tx.appointment.update).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }), + }), + ); expect(prisma.appointment.update).not.toHaveBeenCalled(); }); + + it('não ressuscita sync cancelado quando invitee.created chega depois ou é repetido', async () => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status: StatusAgendamento.PENDING, + calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + calendly_sync_status: CalendlySyncStatus.PENDING, + appointment_datetime: null, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn(async () => ({ ...appointment })), + findFirst: jest.fn().mockResolvedValue(null), + update: jest.fn(async ({ data }) => Object.assign(appointment, data)), + updateMany: jest.fn(async ({ data }) => { + Object.assign(appointment, data); + return { count: 1 }; + }), + }, + }; + const prisma = { + appointment: { + findMany: jest.fn(async () => [{ ...appointment }]), + }, + $transaction: jest.fn(async (callback: (client: any) => unknown) => + callback(tx), + ), + }; + const service = new CalendlyIntegrationService(prisma as any); + jest + .spyOn(service as any, 'validateWebhookSignature') + .mockReturnValue(undefined); + const payload = { + event: appointment.calendly_event_uri, + uri: appointment.calendly_invitee_uri, + scheduled_event: { start_time: '2099-01-01T10:00:00.000Z' }, + }; + + await expect( + service.processWebhook( + { event: 'invitee.canceled', payload }, + undefined, + undefined, + ), + ).resolves.toMatchObject({ processed: true }); + expect(appointment.calendly_sync_status).toBe(CalendlySyncStatus.FAILED); + + for (let replay = 0; replay < 2; replay += 1) { + await expect( + service.processWebhook( + { event: 'invitee.created', payload }, + undefined, + undefined, + ), + ).resolves.toEqual({ + processed: false, + message: 'Webhook ignorado para preservar a associação atual', + }); + } + expect(tx.appointment.update).not.toHaveBeenCalled(); + expect(appointment.calendly_sync_status).toBe(CalendlySyncStatus.FAILED); + }); + + it.each([ + [StatusAgendamento.COMPLETED, 'invitee.created'], + [StatusAgendamento.CANCELLED, 'invitee.created'], + [StatusAgendamento.COMPLETED, 'invitee.canceled'], + [StatusAgendamento.CANCELLED, 'invitee.canceled'], + ] as const)( + 'não muta appointment terminal %s com %s', + async (status, eventType) => { + const appointment = { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'specialist-1', + status, + calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + calendly_sync_status: CalendlySyncStatus.PENDING, + appointment_datetime: new Date('2099-01-01T09:00:00.000Z'), + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + findFirst: jest.fn(), + update: jest.fn(), + updateMany: jest.fn(), + }, + }; + const prisma = { + appointment: { findMany: jest.fn().mockResolvedValue([appointment]) }, + $transaction: jest.fn(async (callback: (client: any) => unknown) => + callback(tx), + ), + }; + const service = new CalendlyIntegrationService(prisma as any); + jest + .spyOn(service as any, 'validateWebhookSignature') + .mockReturnValue(undefined); + + await expect( + service.processWebhook( + { + event: eventType, + payload: { + event: appointment.calendly_event_uri, + uri: appointment.calendly_invitee_uri, + scheduled_event: { start_time: '2099-01-01T10:00:00.000Z' }, + }, + }, + undefined, + undefined, + ), + ).resolves.toMatchObject({ processed: false }); + expect(tx.appointment.findFirst).not.toHaveBeenCalled(); + expect(tx.appointment.update).not.toHaveBeenCalled(); + expect(tx.appointment.updateMany).not.toHaveBeenCalled(); + }, + ); + + it('encontra e canonicaliza registro legado ao cancelar pelo webhook', async () => { + const appointment = { + id: 'appointment-1', + specialist_id: 'specialist-1', + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: + 'https://calendly.com/api/v2/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/api/v2/scheduled_events/event-1/invitees/invitee-1', + }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + }; + const prisma = { + appointment: { + findMany: jest.fn().mockResolvedValue([appointment]), + }, + $transaction: jest.fn(async (callback: (client: any) => unknown) => + callback(tx), + ), + }; + const service = new CalendlyIntegrationService(prisma as any); + jest + .spyOn(service as any, 'validateWebhookSignature') + .mockReturnValue(undefined); + + await expect( + service.processWebhook( + { + event: 'invitee.canceled', + payload: { + event: 'https://api.calendly.com/scheduled_events/event-1', + uri: 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }, + } as any, + undefined, + undefined, + ), + ).resolves.toEqual({ + processed: true, + message: 'Webhook de cancelamento processado', + }); + expect(prisma.appointment.findMany).toHaveBeenCalledWith({ + where: { + calendly_invitee_uri: { + in: expect.arrayContaining([ + appointment.calendly_invitee_uri, + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + ]), + }, + }, + take: 2, + include: { process: { select: { removed_at: true } } }, + }); + expect(tx.$queryRaw).toHaveBeenCalledTimes(1); + expect(tx.appointment.updateMany).toHaveBeenCalledWith({ + where: { + id: appointment.id, + calendly_event_uri: appointment.calendly_event_uri, + calendly_invitee_uri: appointment.calendly_invitee_uri, + }, + data: { + calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + calendly_last_sync_at: expect.any(Date), + calendly_sync_status: 'FAILED', + }, + }); + }); + + it('falha fechado quando fallback por evento encontra dois convidados do mesmo grupo', async () => { + const appointments = [ + { + id: 'appointment-1', + specialist_id: 'specialist-1', + calendly_event_uri: + 'https://api.calendly.com/scheduled_events/group-event', + }, + { + id: 'appointment-2', + specialist_id: 'specialist-1', + calendly_event_uri: + 'https://calendly.com/api/v2/scheduled_events/group-event', + }, + ]; + const prisma = { + appointment: { findMany: jest.fn().mockResolvedValue(appointments) }, + $transaction: jest.fn(), + }; + const service = new CalendlyIntegrationService(prisma as any); + jest + .spyOn(service as any, 'validateWebhookSignature') + .mockReturnValue(undefined); + + await expect( + service.processWebhook( + { + event: 'invitee.created', + payload: { + event: 'https://api.calendly.com/scheduled_events/group-event', + }, + }, + undefined, + undefined, + ), + ).rejects.toThrow(ConflictException); + expect(prisma.appointment.findMany).toHaveBeenCalledWith({ + where: { + calendly_event_uri: { + in: expect.arrayContaining([ + 'https://api.calendly.com/scheduled_events/group-event', + 'https://calendly.com/api/v2/scheduled_events/group-event', + ]), + }, + }, + take: 2, + include: { process: { select: { removed_at: true } } }, + }); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + + it('não deixa webhook created antigo sobrescrever uma nova associação', async () => { + const snapshot = { + id: 'appointment-1', + specialist_id: 'specialist-1', + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-old', + }; + const locked = { + ...snapshot, + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-new', + }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(locked), + findFirst: jest.fn(), + update: jest.fn(), + }, + }; + const prisma = { + appointment: { findMany: jest.fn().mockResolvedValue([snapshot]) }, + $transaction: jest.fn(async (callback: (client: any) => unknown) => + callback(tx), + ), + }; + const service = new CalendlyIntegrationService(prisma as any); + jest + .spyOn(service as any, 'validateWebhookSignature') + .mockReturnValue(undefined); + + await expect( + service.processWebhook( + { + event: 'invitee.created', + payload: { + event: 'https://api.calendly.com/scheduled_events/event-1', + uri: snapshot.calendly_invitee_uri, + scheduled_event: { start_time: '2099-01-01T10:00:00.000Z' }, + }, + } as any, + undefined, + undefined, + ), + ).resolves.toEqual({ + processed: false, + message: 'Webhook ignorado para preservar a associação atual', + }); + expect(tx.$queryRaw).toHaveBeenCalledTimes(1); + expect(tx.appointment.findFirst).not.toHaveBeenCalled(); + expect(tx.appointment.update).not.toHaveBeenCalled(); + }); + + it('serializa cancelamento e não confirma processamento quando perde o CAS', async () => { + const appointment = { + id: 'appointment-1', + specialist_id: 'specialist-1', + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-1', + }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(appointment), + updateMany: jest.fn().mockResolvedValue({ count: 0 }), + }, + }; + const prisma = { + appointment: { findMany: jest.fn().mockResolvedValue([appointment]) }, + $transaction: jest.fn(async (callback: (client: any) => unknown) => + callback(tx), + ), + }; + const service = new CalendlyIntegrationService(prisma as any); + jest + .spyOn(service as any, 'validateWebhookSignature') + .mockReturnValue(undefined); + + await expect( + service.processWebhook( + { + event: 'invitee.canceled', + payload: { + event: appointment.calendly_event_uri, + uri: appointment.calendly_invitee_uri, + }, + } as any, + undefined, + undefined, + ), + ).resolves.toEqual({ + processed: false, + message: 'Webhook ignorado para preservar a associação atual', + }); + expect(tx.$queryRaw).toHaveBeenCalledTimes(1); + expect(tx.appointment.updateMany).toHaveBeenCalledTimes(1); + }); + + it('não deixa webhook canceled antigo cancelar uma nova associação', async () => { + const snapshot = { + id: 'appointment-1', + specialist_id: 'specialist-1', + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + specialist_rescheduled_at: null, + calendly_event_uri: 'https://api.calendly.com/scheduled_events/event-1', + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-old', + }; + const locked = { + ...snapshot, + calendly_invitee_uri: + 'https://api.calendly.com/scheduled_events/event-1/invitees/invitee-new', + }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + appointment: { + findUnique: jest.fn().mockResolvedValue(locked), + updateMany: jest.fn(), + }, + }; + const prisma = { + appointment: { findMany: jest.fn().mockResolvedValue([snapshot]) }, + $transaction: jest.fn(async (callback: (client: any) => unknown) => + callback(tx), + ), + }; + const service = new CalendlyIntegrationService(prisma as any); + jest + .spyOn(service as any, 'validateWebhookSignature') + .mockReturnValue(undefined); + + await expect( + service.processWebhook( + { + event: 'invitee.canceled', + payload: { + event: snapshot.calendly_event_uri, + uri: snapshot.calendly_invitee_uri, + }, + } as any, + undefined, + undefined, + ), + ).resolves.toEqual({ + processed: false, + message: 'Webhook ignorado para preservar a associação atual', + }); + expect(tx.$queryRaw).toHaveBeenCalledTimes(1); + expect(tx.appointment.updateMany).not.toHaveBeenCalled(); + }); }); diff --git a/backend/src/features/appointments/calendly-integration.service.ts b/backend/src/features/appointments/calendly-integration.service.ts index b48e54db..e3f9b3ee 100644 --- a/backend/src/features/appointments/calendly-integration.service.ts +++ b/backend/src/features/appointments/calendly-integration.service.ts @@ -1,5 +1,6 @@ import { BadRequestException, + ConflictException, ForbiddenException, Injectable, InternalServerErrorException, @@ -9,7 +10,7 @@ import { import { AppointmentSchedulingMethod, CalendlySyncStatus, - Prisma, + StatusAgendamento, UserRole, } from '@prisma/client'; import axios from 'axios'; @@ -22,10 +23,17 @@ import { } from 'crypto'; import { PrismaService } from 'src/prisma/prisma.service'; import { parseDate } from 'src/shared/utils/date.utils'; +import { isCalendlySchedulingAvailable } from 'src/shared/utils/calendly-scheduling-capability'; import { acquireSpecialistScheduleLock, assertSpecialistScheduleAvailable, } from './appointment-schedule-lock'; +import { + CalendlyResourceKind, + CalendlyResourceReference, + getCalendlyResourceUriVariants, + parseCalendlyResourceUri, +} from './dto/calendly-scheduled.dto'; interface CalendlyTokenResponse { access_token: string; @@ -39,6 +47,7 @@ interface CalendlyUserMeResponse { resource: { uri: string; current_organization?: string; + scheduling_url?: string; }; } @@ -46,6 +55,7 @@ interface CalendlyWebhookPayload { event?: string; payload?: { event?: string; + uri?: string; invitee?: string | { uri?: string }; scheduled_event?: { uri?: string; @@ -117,6 +127,7 @@ export class CalendlyIntegrationService { calendly_user_uri: string | null; expires_at: Date | null; is_active: boolean; + last_error: string | null; }> { const connection = await this.prisma.calendlyConnection.findUnique({ where: { user_id: userId }, @@ -124,6 +135,7 @@ export class CalendlyIntegrationService { is_active: true, calendly_user_uri: true, expires_at: true, + last_error: true, }, }); @@ -133,6 +145,7 @@ export class CalendlyIntegrationService { calendly_user_uri: null, expires_at: null, is_active: false, + last_error: null, }; } @@ -141,6 +154,7 @@ export class CalendlyIntegrationService { calendly_user_uri: connection.calendly_user_uri, expires_at: connection.expires_at, is_active: connection.is_active, + last_error: connection.last_error, }; } @@ -183,6 +197,18 @@ export class CalendlyIntegrationService { ); } + const schedulingUrl = me.resource.scheduling_url ?? null; + if ( + !isCalendlySchedulingAvailable({ + calendlyUrl: schedulingUrl, + connectionActive: true, + }) + ) { + throw new BadRequestException( + 'Calendly não retornou URL de agendamento válida', + ); + } + const expiresAt = token.expires_in ? new Date(Date.now() + token.expires_in * 1000) : null; @@ -222,6 +248,7 @@ export class CalendlyIntegrationService { await this.prisma.user.update({ where: { id: stateRecord.user_id }, data: { + calendly_url: schedulingUrl, calendly_user_uri: me.resource.uri, calendly_organization_uri: me.resource.current_organization || null, }, @@ -238,47 +265,63 @@ export class CalendlyIntegrationService { this.logger.warn( `Falha ao criar webhook Calendly (não crítico): ${error?.message}`, ); + try { + await this.prisma.calendlyConnection.updateMany({ + where: { + id: upsertedConnection.id, + access_token_encrypted: upsertedConnection.access_token_encrypted, + is_active: true, + }, + data: { last_error: 'webhook_subscription_failed' }, + }); + } catch (persistError: any) { + this.logger.warn( + `Falha ao registrar degradação do webhook Calendly: ${persistError?.message}`, + ); + } } return stateRecord.user_id; } async disconnect(userId: string): Promise { - const connection = await this.prisma.calendlyConnection.findUnique({ - where: { user_id: userId }, - }); - - if (!connection) { - return; - } - - await this.prisma.$transaction([ - this.prisma.calendlyConnection.update({ - where: { id: connection.id }, + await this.prisma.$transaction(async (tx) => { + await tx.calendlyConnection.updateMany({ + where: { user_id: userId }, data: { is_active: false, last_sync_at: new Date(), }, - }), - this.prisma.user.update({ + }); + await tx.user.update({ where: { id: userId }, data: { + calendly_url: null, calendly_user_uri: null, calendly_organization_uri: null, }, - }), - ]); + }); + }); } async resolveScheduledStartTime( specialistId: string, eventUri?: string | null, inviteeUri?: string | null, + expectedClientId?: string | null, ): Promise { if (!specialistId || (!eventUri && !inviteeUri)) { return null; } + const eventReference = eventUri + ? this.parseCalendlyResourceUri(eventUri, 'event') + : null; + const inviteeReference = inviteeUri + ? this.parseCalendlyResourceUri(inviteeUri, 'invitee') + : null; + this.assertSameCalendlyEvent(eventReference, inviteeReference); + const connection = await this.prisma.calendlyConnection.findUnique({ where: { user_id: specialistId }, }); @@ -286,35 +329,57 @@ export class CalendlyIntegrationService { if (!connection || !connection.is_active) { return null; } + if ( + typeof connection.calendly_user_uri !== 'string' || + !connection.calendly_user_uri.trim() + ) { + throw new BadRequestException( + 'Conexão Calendly sem identidade de usuário válida', + ); + } - const inviteeData = inviteeUri + const inviteeData = inviteeReference ? await this.getCalendlyResourceWithRefresh( connection.user_id, - inviteeUri, + inviteeReference.canonicalUri, + 'invitee', ) : null; - const inviteeResource = inviteeData?.resource || inviteeData; - const inviteeStartTime = - inviteeResource?.start_time || - inviteeResource?.event_start_time || - inviteeData?.payload?.scheduled_event?.start_time; - - if (inviteeStartTime) { - const parsed = parseDate(inviteeStartTime); - if (parsed) { - await this.prisma.calendlyConnection.update({ - where: { id: connection.id }, - data: { last_sync_at: new Date(), last_error: null }, - }); - return parsed; + const inviteeResource = inviteeReference + ? this.requireCalendlyResource(inviteeData, 'convidado') + : null; + if (expectedClientId) { + const client = await this.prisma.user.findUnique({ + where: { id: expectedClientId }, + select: { email: true }, + }); + const expectedEmail = client?.email?.trim().toLowerCase(); + const authoritativeEmail = inviteeResource?.email?.trim().toLowerCase(); + if ( + !expectedEmail || + !authoritativeEmail || + expectedEmail !== authoritativeEmail + ) { + throw new BadRequestException( + 'O convidado do Calendly não pertence ao cliente do agendamento', + ); } } - + const inviteeEventUri = + inviteeResource?.event || inviteeResource?.scheduled_event?.uri; + const inviteeEventReference = inviteeEventUri + ? this.parseCalendlyResourceUri(inviteeEventUri, 'event') + : null; + this.assertSameCalendlyEvent( + eventReference, + inviteeReference, + inviteeEventReference, + ); const resolvedEventUri = - eventUri || - inviteeResource?.event || - inviteeResource?.scheduled_event?.uri; + eventReference?.canonicalUri || + inviteeEventReference?.canonicalUri || + inviteeReference?.canonicalEventUri; if (!resolvedEventUri) { return null; } @@ -322,11 +387,35 @@ export class CalendlyIntegrationService { const eventData = await this.getCalendlyResourceWithRefresh( connection.user_id, resolvedEventUri, + 'event', ); - const eventResource = eventData?.resource || eventData; - const eventStartTime = - eventResource?.start_time || - eventData?.payload?.scheduled_event?.start_time; + const eventResource = this.requireCalendlyResource(eventData, 'evento'); + if ( + !Array.isArray(eventResource.event_memberships) || + eventResource.event_memberships.some( + (membership: unknown) => + !membership || + typeof membership !== 'object' || + typeof (membership as { user?: unknown }).user !== 'string', + ) + ) { + throw new BadRequestException( + 'Calendly retornou memberships de evento inválidas', + ); + } + const connectedUserUri = connection.calendly_user_uri.trim(); + if ( + !eventResource.event_memberships.some( + (membership: { user: string }) => + membership.user.trim() === connectedUserUri, + ) + ) { + throw new BadRequestException( + 'Evento do Calendly não pertence ao especialista conectado', + ); + } + + const eventStartTime = eventResource.start_time; if (!eventStartTime) { return null; @@ -345,6 +434,26 @@ export class CalendlyIntegrationService { return parsed; } + private requireCalendlyResource( + data: unknown, + kind: 'evento' | 'convidado', + ): Record { + if ( + !data || + typeof data !== 'object' || + !('resource' in data) || + !(data as { resource?: unknown }).resource || + typeof (data as { resource?: unknown }).resource !== 'object' || + Array.isArray((data as { resource?: unknown }).resource) + ) { + throw new BadRequestException( + `Calendly retornou ${kind} com formato inválido`, + ); + } + + return (data as { resource: Record }).resource; + } + async processWebhook( body: CalendlyWebhookPayload, rawBody: string | undefined, @@ -362,29 +471,76 @@ export class CalendlyIntegrationService { }; } - const eventUri = payload.event || payload.scheduled_event?.uri; - const inviteeUri = + const rawEventUri = payload.event || payload.scheduled_event?.uri; + const rawOfficialInviteeUri = payload.uri; + const rawLegacyInviteeUri = typeof payload.invitee === 'string' ? payload.invitee : payload.invitee?.uri; + const rawInviteeUri = rawOfficialInviteeUri || rawLegacyInviteeUri; - if (!eventUri && !inviteeUri) { + if (!rawEventUri && !rawInviteeUri) { return { processed: false, message: 'Webhook sem event/invitee uri', }; } - const appointment = await this.prisma.appointment.findFirst({ - where: { - OR: [ - eventUri ? { calendly_event_uri: eventUri } : undefined, - inviteeUri ? { calendly_invitee_uri: inviteeUri } : undefined, - ].filter(Boolean) as Prisma.AppointmentWhereInput[], - }, + const eventReference = rawEventUri + ? this.parseCalendlyResourceUri(rawEventUri, 'event') + : null; + const officialInviteeReference = rawOfficialInviteeUri + ? this.parseCalendlyResourceUri(rawOfficialInviteeUri, 'invitee') + : null; + const legacyInviteeReference = rawLegacyInviteeUri + ? this.parseCalendlyResourceUri(rawLegacyInviteeUri, 'invitee') + : null; + if ( + officialInviteeReference && + legacyInviteeReference && + officialInviteeReference.canonicalUri !== + legacyInviteeReference.canonicalUri + ) { + throw new BadRequestException( + 'URIs de convidado do Calendly são inconsistentes', + ); + } + const inviteeReference = officialInviteeReference || legacyInviteeReference; + this.assertSameCalendlyEvent(eventReference, inviteeReference); + const lookupEventReference = + eventReference || + (inviteeReference + ? this.parseCalendlyResourceUri( + inviteeReference.canonicalEventUri, + 'event', + ) + : null); + const eventUri = lookupEventReference?.canonicalUri; + const inviteeUri = inviteeReference?.canonicalUri; + + const appointments = await this.prisma.appointment.findMany({ + where: inviteeReference + ? { + calendly_invitee_uri: { + in: getCalendlyResourceUriVariants(inviteeReference), + }, + } + : { + calendly_event_uri: { + in: getCalendlyResourceUriVariants(lookupEventReference!), + }, + }, + take: 2, + include: { process: { select: { removed_at: true } } }, }); + if (appointments.length > 1) { + throw new ConflictException( + 'Webhook Calendly corresponde a múltiplos agendamentos', + ); + } + const appointment = appointments[0]; - if (!appointment) { + if (!appointment || appointment.process?.removed_at) { return { processed: false, message: 'Nenhum agendamento correspondente encontrado', @@ -419,8 +575,9 @@ export class CalendlyIntegrationService { await acquireSpecialistScheduleLock(tx, appointment.specialist_id); const lockedAppointment = await tx.appointment.findUnique({ where: { id: appointment.id }, + include: { process: { select: { removed_at: true } } }, }); - if (!lockedAppointment) { + if (!lockedAppointment || lockedAppointment.process?.removed_at) { throw new NotFoundException('Agendamento não encontrado'); } @@ -428,7 +585,20 @@ export class CalendlyIntegrationService { (lockedAppointment.scheduling_method && lockedAppointment.scheduling_method !== AppointmentSchedulingMethod.CALENDLY) || - lockedAppointment.specialist_rescheduled_at + lockedAppointment.specialist_rescheduled_at || + lockedAppointment.calendly_sync_status === + CalendlySyncStatus.FAILED || + lockedAppointment.status === StatusAgendamento.COMPLETED || + lockedAppointment.status === StatusAgendamento.CANCELLED + ) { + return false; + } + if ( + !this.appointmentStillMatchesWebhook( + lockedAppointment, + lookupEventReference, + inviteeReference, + ) ) { return false; } @@ -463,7 +633,7 @@ export class CalendlyIntegrationService { if (!processed) { return { processed: false, - message: 'Webhook ignorado para preservar o horário atual', + message: 'Webhook ignorado para preservar a associação atual', }; } @@ -474,14 +644,55 @@ export class CalendlyIntegrationService { } if (eventType === 'invitee.canceled') { - await this.prisma.appointment.update({ - where: { id: appointment.id }, - data: { - calendly_last_sync_at: new Date(), - calendly_sync_status: CalendlySyncStatus.FAILED, - }, + const processed = await this.prisma.$transaction(async (tx) => { + await acquireSpecialistScheduleLock(tx, appointment.specialist_id); + const lockedAppointment = await tx.appointment.findUnique({ + where: { id: appointment.id }, + include: { process: { select: { removed_at: true } } }, + }); + if ( + !lockedAppointment || + lockedAppointment.process?.removed_at || + (lockedAppointment.scheduling_method && + lockedAppointment.scheduling_method !== + AppointmentSchedulingMethod.CALENDLY) || + lockedAppointment.specialist_rescheduled_at || + lockedAppointment.status === StatusAgendamento.COMPLETED || + lockedAppointment.status === StatusAgendamento.CANCELLED || + !this.appointmentStillMatchesWebhook( + lockedAppointment, + lookupEventReference, + inviteeReference, + ) + ) { + return false; + } + + const updated = await tx.appointment.updateMany({ + where: { + id: lockedAppointment.id, + calendly_event_uri: lockedAppointment.calendly_event_uri, + calendly_invitee_uri: lockedAppointment.calendly_invitee_uri, + }, + data: { + calendly_event_uri: + eventUri || lockedAppointment.calendly_event_uri, + calendly_invitee_uri: + inviteeUri || lockedAppointment.calendly_invitee_uri, + calendly_last_sync_at: new Date(), + calendly_sync_status: CalendlySyncStatus.FAILED, + }, + }); + return updated.count === 1; }); + if (!processed) { + return { + processed: false, + message: 'Webhook ignorado para preservar a associação atual', + }; + } + return { processed: true, message: 'Webhook de cancelamento processado', @@ -497,6 +708,7 @@ export class CalendlyIntegrationService { private async getCalendlyResourceWithRefresh( userId: string, uri: string, + kind: CalendlyResourceKind, ): Promise { const connection = await this.prisma.calendlyConnection.findUnique({ where: { user_id: userId }, @@ -511,7 +723,7 @@ export class CalendlyIntegrationService { let accessToken = this.decryptToken(connection.access_token_encrypted); try { - return await this.fetchCalendlyResource(accessToken, uri); + return await this.fetchCalendlyResource(accessToken, uri, kind); } catch (error: any) { const status = error?.response?.status; if (status !== 401) { @@ -521,7 +733,7 @@ export class CalendlyIntegrationService { const refreshed = await this.refreshConnectionToken(connection); accessToken = this.decryptToken(refreshed.access_token_encrypted); - return this.fetchCalendlyResource(accessToken, uri); + return this.fetchCalendlyResource(accessToken, uri, kind); } } @@ -535,7 +747,8 @@ export class CalendlyIntegrationService { access_token_encrypted: string; refresh_token_encrypted: string; }> { - const refreshToken = this.decryptToken(connection.refresh_token_encrypted); + const refreshTokenEncrypted = connection.refresh_token_encrypted; + const refreshToken = this.decryptToken(refreshTokenEncrypted); const tokenUrl = process.env.CALENDLY_OAUTH_TOKEN_URL || @@ -550,16 +763,32 @@ export class CalendlyIntegrationService { client_secret: clientSecret, }); - const { data } = await axios.post( - tokenUrl, - payload.toString(), - { - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', + let data: CalendlyTokenResponse; + try { + const response = await axios.post( + tokenUrl, + payload.toString(), + { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + timeout: 20000, }, - timeout: 20000, - }, - ); + ); + data = response.data; + } catch (error: any) { + if (error?.response?.data?.error === 'invalid_grant') { + await this.prisma.calendlyConnection.updateMany({ + where: { + id: connection.id, + refresh_token_encrypted: refreshTokenEncrypted, + is_active: true, + }, + data: { is_active: false, last_error: 'invalid_grant' }, + }); + } + throw error; + } const expiresAt = data.expires_in ? new Date(Date.now() + data.expires_in * 1000) @@ -590,13 +819,15 @@ export class CalendlyIntegrationService { private async fetchCalendlyResource( accessToken: string, uri: string, + kind: CalendlyResourceKind, ): Promise { - const normalizedUri = this.normalizeCalendlyUri(uri); - const { data } = await axios.get(normalizedUri, { + const trustedUri = this.parseCalendlyResourceUri(uri, kind).canonicalUri; + const { data } = await axios.get(trustedUri, { headers: { Authorization: `Bearer ${accessToken}`, }, timeout: 20000, + maxRedirects: 0, }); return data; @@ -662,7 +893,7 @@ export class CalendlyIntegrationService { return; } - const signingKey = process.env.CALENDLY_WEBHOOK_SIGNING_KEY; + this.getRequiredEnv('CALENDLY_WEBHOOK_SIGNING_KEY'); const connection = await this.prisma.calendlyConnection.findUnique({ where: { user_id: userId }, @@ -688,55 +919,18 @@ export class CalendlyIntegrationService { scope: 'user', }; - if (signingKey) { - payload.signing_key = signingKey; - } - - let data: any; - - try { - const response = await axios.post( - 'https://api.calendly.com/webhook_subscriptions', - payload, - { - headers: { - Authorization: `Bearer ${accessToken}`, - 'Content-Type': 'application/json', - }, - timeout: 20000, - }, - ); - data = response.data; - } catch (error: any) { - const status = error?.response?.status; - const shouldRetryWithoutSigningKey = - Boolean(signingKey) && (status === 400 || status === 422); - - if (!shouldRetryWithoutSigningKey) { - throw error; - } - - this.logger.warn( - 'Calendly rejeitou webhook com signing_key; tentando novamente sem signing_key', - ); - - const fallbackPayload = { ...payload }; - delete fallbackPayload.signing_key; - - const fallbackResponse = await axios.post( - 'https://api.calendly.com/webhook_subscriptions', - fallbackPayload, - { - headers: { - Authorization: `Bearer ${accessToken}`, - 'Content-Type': 'application/json', - }, - timeout: 20000, + const response = await axios.post( + 'https://api.calendly.com/webhook_subscriptions', + payload, + { + headers: { + Authorization: `Bearer ${accessToken}`, + 'Content-Type': 'application/json', }, - ); - - data = fallbackResponse.data; - } + timeout: 20000, + }, + ); + const data = response.data; const webhookResource = data?.resource; @@ -755,11 +949,7 @@ export class CalendlyIntegrationService { rawBody: string | undefined, signatureHeader: string | undefined, ): void { - const signingKey = process.env.CALENDLY_WEBHOOK_SIGNING_KEY; - - if (!signingKey) { - return; - } + const signingKey = this.getRequiredEnv('CALENDLY_WEBHOOK_SIGNING_KEY'); if (!rawBody || !signatureHeader) { throw new ForbiddenException('Assinatura do webhook ausente'); @@ -770,6 +960,18 @@ export class CalendlyIntegrationService { throw new ForbiddenException('Formato de assinatura inválido'); } + if (!/^\d+$/.test(parsedSignature.t)) { + throw new ForbiddenException('Timestamp da assinatura inválido'); + } + const timestampSeconds = Number(parsedSignature.t); + const nowSeconds = Math.floor(this.now() / 1000); + if ( + !Number.isSafeInteger(timestampSeconds) || + Math.abs(nowSeconds - timestampSeconds) > 5 * 60 + ) { + throw new ForbiddenException('Timestamp da assinatura expirado'); + } + const signedPayload = `${parsedSignature.t}.${rawBody}`; const expected = createHmac('sha256', signingKey) .update(signedPayload) @@ -786,6 +988,10 @@ export class CalendlyIntegrationService { } } + private now(): number { + return Date.now(); + } + private parseSignatureHeader(signatureHeader: string): { t?: string; v1?: string; @@ -806,16 +1012,56 @@ export class CalendlyIntegrationService { ); } - private normalizeCalendlyUri(uri: string): string { - if (uri.startsWith('http://') || uri.startsWith('https://')) { - return uri; + private parseCalendlyResourceUri( + uri: string, + kind: CalendlyResourceKind, + ): CalendlyResourceReference { + const reference = parseCalendlyResourceUri(uri, kind); + if (!reference) { + const field = kind === 'event' ? 'event_uri' : 'invitee_uri'; + throw new BadRequestException(`${field} do Calendly inválida`); + } + return reference; + } + + private assertSameCalendlyEvent( + ...references: Array + ): void { + const eventIds = references + .filter((reference): reference is CalendlyResourceReference => + Boolean(reference), + ) + .map((reference) => reference.eventId); + if (new Set(eventIds).size > 1) { + throw new BadRequestException( + 'URIs do Calendly pertencem a eventos diferentes', + ); + } + } + + private appointmentStillMatchesWebhook( + appointment: { + calendly_event_uri?: string | null; + calendly_invitee_uri?: string | null; + }, + eventReference: CalendlyResourceReference | null, + inviteeReference: CalendlyResourceReference | null, + ): boolean { + if (inviteeReference) { + const currentInvitee = appointment.calendly_invitee_uri + ? parseCalendlyResourceUri(appointment.calendly_invitee_uri, 'invitee') + : null; + return currentInvitee?.canonicalUri === inviteeReference.canonicalUri; } - if (uri.startsWith('/')) { - return `https://api.calendly.com${uri}`; + if (eventReference) { + const currentEvent = appointment.calendly_event_uri + ? parseCalendlyResourceUri(appointment.calendly_event_uri, 'event') + : null; + return currentEvent?.canonicalUri === eventReference.canonicalUri; } - return `https://api.calendly.com/${uri}`; + return false; } private getRequiredEnv(name: string): string { diff --git a/backend/src/features/appointments/calendly.controller.spec.ts b/backend/src/features/appointments/calendly.controller.spec.ts new file mode 100644 index 00000000..915efb47 --- /dev/null +++ b/backend/src/features/appointments/calendly.controller.spec.ts @@ -0,0 +1,64 @@ +import { CalendlyController } from './calendly.controller'; + +describe('CalendlyController OAuth callback public errors', () => { + const originalFrontendUrl = process.env.FRONTEND_URL; + + beforeAll(() => { + process.env.FRONTEND_URL = 'https://frontend.example.test'; + }); + + afterAll(() => { + if (originalFrontendUrl === undefined) { + delete process.env.FRONTEND_URL; + } else { + process.env.FRONTEND_URL = originalFrontendUrl; + } + }); + + function responseHarness() { + return { redirect: jest.fn((url: string) => url) } as any; + } + + it('não expõe error_description arbitrária devolvida pelo provedor', async () => { + const controller = new CalendlyController({} as any); + const response = responseHarness(); + const secret = 'client_secret=very-sensitive-value'; + + await controller.oauthCallback( + undefined, + undefined, + 'access_denied', + secret, + response, + ); + + const redirect = response.redirect.mock.calls[0][0]; + expect(redirect).toBe( + 'https://frontend.example.test/profile?calendly=error&reason=oauth_denied', + ); + expect(redirect).not.toContain('very-sensitive-value'); + }); + + it('não expõe detalhes internos de falha do callback', async () => { + const secret = 'upstream access_token=very-sensitive-value'; + const service = { + handleOAuthCallback: jest.fn().mockRejectedValue(new Error(secret)), + }; + const controller = new CalendlyController(service as any); + const response = responseHarness(); + + await controller.oauthCallback( + 'code', + 'state', + undefined, + undefined, + response, + ); + + const redirect = response.redirect.mock.calls[0][0]; + expect(redirect).toBe( + 'https://frontend.example.test/profile?calendly=error&reason=oauth_callback_failed', + ); + expect(redirect).not.toContain('very-sensitive-value'); + }); +}); diff --git a/backend/src/features/appointments/calendly.controller.ts b/backend/src/features/appointments/calendly.controller.ts index ad3b79fb..279a0cc5 100644 --- a/backend/src/features/appointments/calendly.controller.ts +++ b/backend/src/features/appointments/calendly.controller.ts @@ -76,7 +76,7 @@ export class CalendlyController { const isGoogleDomainBlocked = /google.*(domain|workspace)|domain.*denied/i.test(rawReason); const reason = encodeURIComponent( - isGoogleDomainBlocked ? 'google_domain_blocked' : rawReason, + isGoogleDomainBlocked ? 'google_domain_blocked' : 'oauth_denied', ); return res.redirect( `${frontendUrl}/profile?calendly=error&reason=${reason}`, @@ -101,7 +101,9 @@ export class CalendlyController { const isGoogleDomainBlocked = /google.*(domain|workspace)|domain.*denied/i.test(rawReason); const reason = encodeURIComponent( - isGoogleDomainBlocked ? 'google_domain_blocked' : rawReason, + isGoogleDomainBlocked + ? 'google_domain_blocked' + : 'oauth_callback_failed', ); return res.redirect( diff --git a/backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts b/backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts new file mode 100644 index 00000000..c183fb8b --- /dev/null +++ b/backend/src/features/appointments/dto/calendly-scheduled.dto.spec.ts @@ -0,0 +1,116 @@ +import { validate } from 'class-validator'; +import { plainToInstance } from 'class-transformer'; +import { CalendlyScheduledDto } from './calendly-scheduled.dto'; + +describe('CalendlyScheduledDto — Calendly resource URIs', () => { + const validPayload = { + event_uri: 'https://api.calendly.com/scheduled_events/event-123', + invitee_uri: + 'https://api.calendly.com/scheduled_events/event-123/invitees/invitee-456', + }; + + async function invalidProperties(payload: Record) { + const errors = await validate( + plainToInstance(CalendlyScheduledDto, { + ...validPayload, + ...payload, + }), + ); + return errors.map((error) => error.property); + } + + it('aceita somente os caminhos canônicos de evento e convidado', async () => { + await expect(invalidProperties({})).resolves.toEqual([]); + }); + + it('não expõe scheduled_start_time como campo confiável do contrato', async () => { + const errors = await validate( + plainToInstance(CalendlyScheduledDto, { + ...validPayload, + scheduled_start_time: '2099-01-01T10:00:00.000Z', + }), + { whitelist: true, forbidNonWhitelisted: true }, + ); + + expect(errors).toEqual( + expect.arrayContaining([ + expect.objectContaining({ property: 'scheduled_start_time' }), + ]), + ); + }); + + it('aceita HTTPS com a porta padrão explícita', async () => { + await expect( + invalidProperties({ + event_uri: + 'https://api.calendly.com:443/scheduled_events/event-123', + invitee_uri: + 'https://api.calendly.com:443/scheduled_events/event-123/invitees/invitee-456', + }), + ).resolves.toEqual([]); + }); + + it.each([ + { + event_uri: + 'https://calendly.com/api/v2/scheduled_events/event-123', + invitee_uri: + 'https://calendly.com/api/v2/scheduled_events/event-123/invitees/invitee-456', + }, + { + event_uri: + 'https://api.calendly.com/api/v2/scheduled_events/event-123', + invitee_uri: + 'https://api.calendly.com/api/v2/scheduled_events/event-123/invitees/invitee-456', + }, + ])('aceita a família oficial usada pelo react-calendly: %o', async (uris) => { + await expect(invalidProperties(uris)).resolves.toEqual([]); + }); + + it.each([ + 'https://evil/scheduled_events/event-123', + 'https://evil.test/scheduled_events/event-123', + 'https://calendly.com.evil/scheduled_events/event-123', + 'https://api.calendly.com.evil.test/scheduled_events/event-123', + 'http://api.calendly.com/scheduled_events/event-123', + 'https://user:password@api.calendly.com/scheduled_events/event-123', + 'https://%61pi.calendly.com@evil.test/scheduled_events/event-123', + 'https://api.calendly.com\\@evil.test/scheduled_events/event-123', + 'https://api.calendly.com:444/scheduled_events/event-123', + 'https://127.0.0.1/scheduled_events/event-123', + 'https://api.calendly.com/scheduled_events/event%2f123', + 'https://api.calendly.com/scheduled_events/event%3fadmin', + 'https://api.calendly.com/scheduled_events/event%23admin', + 'https://api.calendly.com/scheduled_events/ignored/../event-123', + 'https://api.calendly.com/scheduled_events/event-123/invitees/invitee-456', + ])('rejeita event_uri fora do recurso esperado: %s', async (event_uri) => { + await expect(invalidProperties({ event_uri })).resolves.toContain( + 'event_uri', + ); + }); + + it.each([ + 'https://evil/scheduled_events/event-123/invitees/invitee-456', + 'https://evil.test/scheduled_events/event-123/invitees/invitee-456', + 'https://calendly.com.evil/scheduled_events/event-123/invitees/invitee-456', + 'https://api.calendly.com.evil.test/scheduled_events/event-123/invitees/invitee-456', + 'http://api.calendly.com/scheduled_events/event-123/invitees/invitee-456', + 'https://user@api.calendly.com/scheduled_events/event-123/invitees/invitee-456', + 'https://%61pi.calendly.com@evil.test/scheduled_events/event-123/invitees/invitee-456', + 'https://api.calendly.com\\@evil.test/scheduled_events/event-123/invitees/invitee-456', + 'https://api.calendly.com:444/scheduled_events/event-123/invitees/invitee-456', + 'https://127.0.0.1/scheduled_events/event-123/invitees/invitee-456', + 'https://api.calendly.com/scheduled_events/event%2f123/invitees/invitee-456', + 'https://api.calendly.com/scheduled_events/event-123/invitees/invitee%3f456', + 'https://api.calendly.com/scheduled_events/event-123/invitees/invitee%23456', + 'https://api.calendly.com/scheduled_events/event-123/invitees/ignored/../invitee-456', + 'https://api.calendly.com/scheduled_events/event-123', + ])( + 'rejeita invitee_uri fora do recurso esperado: %s', + async (invitee_uri) => { + await expect(invalidProperties({ invitee_uri })).resolves.toContain( + 'invitee_uri', + ); + }, + ); +}); diff --git a/backend/src/features/appointments/dto/calendly-scheduled.dto.ts b/backend/src/features/appointments/dto/calendly-scheduled.dto.ts index 91f8cc76..249cd376 100644 --- a/backend/src/features/appointments/dto/calendly-scheduled.dto.ts +++ b/backend/src/features/appointments/dto/calendly-scheduled.dto.ts @@ -4,15 +4,117 @@ import { IsOptional, IsString, MaxLength, + registerDecorator, + ValidationArguments, + ValidationOptions, } from 'class-validator'; +export type CalendlyResourceKind = 'event' | 'invitee'; + +export interface CalendlyResourceReference { + canonicalUri: string; + canonicalEventUri: string; + eventId: string; + inviteeId?: string; +} + +const CALENDLY_RESOURCE_PATTERNS = [ + /^https:\/\/api\.calendly\.com(?::443)?\/(?:api\/v2\/)?scheduled_events\/([A-Za-z0-9_-]+)(?:\/invitees\/([A-Za-z0-9_-]+))?$/i, + /^https:\/\/calendly\.com(?::443)?\/api\/v2\/scheduled_events\/([A-Za-z0-9_-]+)(?:\/invitees\/([A-Za-z0-9_-]+))?$/i, +]; + +export function parseCalendlyResourceUri( + value: unknown, + kind: CalendlyResourceKind, +): CalendlyResourceReference | null { + if (typeof value !== 'string') return null; + + const match = CALENDLY_RESOURCE_PATTERNS.map((pattern) => + pattern.exec(value), + ).find((candidate) => candidate?.[0] === value); + if (!match) return null; + + const [, eventId, inviteeId] = match; + if ( + (kind === 'event' && inviteeId !== undefined) || + (kind === 'invitee' && inviteeId === undefined) + ) { + return null; + } + + const canonicalEventUri = + `https://api.calendly.com/scheduled_events/${eventId}`; + return { + eventId, + inviteeId, + canonicalEventUri, + canonicalUri: + kind === 'invitee' + ? `${canonicalEventUri}/invitees/${inviteeId}` + : canonicalEventUri, + }; +} + +export function getCalendlyResourceUriVariants( + reference: CalendlyResourceReference, +): string[] { + const resourcePath = reference.inviteeId + ? `scheduled_events/${reference.eventId}/invitees/${reference.inviteeId}` + : `scheduled_events/${reference.eventId}`; + + return [ + `https://api.calendly.com/${resourcePath}`, + `https://api.calendly.com:443/${resourcePath}`, + `https://api.calendly.com/api/v2/${resourcePath}`, + `https://api.calendly.com:443/api/v2/${resourcePath}`, + `https://calendly.com/api/v2/${resourcePath}`, + `https://calendly.com:443/api/v2/${resourcePath}`, + ]; +} + +export function isCalendlyResourceUri( + value: unknown, + kind: CalendlyResourceKind, +): value is string { + return parseCalendlyResourceUri(value, kind) !== null; +} + +function IsCalendlyResourceUri( + kind: CalendlyResourceKind, + validationOptions?: ValidationOptions, +): PropertyDecorator { + return (target, propertyKey) => { + registerDecorator({ + name: 'isCalendlyResourceUri', + target: target.constructor, + propertyName: propertyKey.toString(), + constraints: [kind], + options: validationOptions, + validator: { + validate(value: unknown, args: ValidationArguments) { + return isCalendlyResourceUri( + value, + args.constraints[0] as CalendlyResourceKind, + ); + }, + }, + }); + }; +} + export class CalendlyScheduledDto { @IsString({ message: 'event_uri deve ser uma string' }) @MaxLength(255, { message: 'event_uri deve ter no máximo 255 caracteres' }) + @IsCalendlyResourceUri('event', { + message: 'event_uri deve apontar para um evento da API do Calendly', + }) event_uri: string; @IsString({ message: 'invitee_uri deve ser uma string' }) @MaxLength(255, { message: 'invitee_uri deve ter no máximo 255 caracteres' }) + @IsCalendlyResourceUri('invitee', { + message: 'invitee_uri deve apontar para um convidado da API do Calendly', + }) invitee_uri: string; @IsOptional() @@ -28,10 +130,4 @@ export class CalendlyScheduledDto { ) client_observed_at?: string; - @IsOptional() - @IsISO8601( - {}, - { message: 'scheduled_start_time deve estar em formato ISO 8601 válido' }, - ) - scheduled_start_time?: string; } diff --git a/backend/src/features/appointments/dto/check-existing-appointment.dto.ts b/backend/src/features/appointments/dto/check-existing-appointment.dto.ts new file mode 100644 index 00000000..1050b420 --- /dev/null +++ b/backend/src/features/appointments/dto/check-existing-appointment.dto.ts @@ -0,0 +1,13 @@ +import { ProductType } from '@prisma/client'; +import { IsEnum, IsUUID } from 'class-validator'; + +export class CheckExistingAppointmentDto { + @IsUUID() + specialist_id: string; + + @IsEnum(ProductType) + product_type: ProductType; + + @IsUUID() + product_id: string; +} diff --git a/backend/src/features/appointments/dto/create-pending-appointment.dto.ts b/backend/src/features/appointments/dto/create-pending-appointment.dto.ts index 1c151dd2..41b50ad6 100644 --- a/backend/src/features/appointments/dto/create-pending-appointment.dto.ts +++ b/backend/src/features/appointments/dto/create-pending-appointment.dto.ts @@ -1,14 +1,29 @@ import { AppointmentSchedulingMethod } from '@prisma/client'; -import { IsIn, IsOptional } from 'class-validator'; +import { OmitType } from '@nestjs/mapped-types'; +import { IsDateString, IsIn, IsOptional, Matches } from 'class-validator'; import { CreateAppointmentDto } from './create-appointment.dto'; -export class CreatePendingAppointmentDto extends CreateAppointmentDto { +export const PENDING_APPOINTMENT_DATETIME_PATTERN = + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})$/; + +export class CreatePendingAppointmentDto extends OmitType( + CreateAppointmentDto, + ['appointment_datetime'] as const, +) { + @IsOptional() + @IsDateString( + { strict: true }, + { message: 'appointment_datetime deve ser uma data ISO 8601 válida' }, + ) + @Matches(PENDING_APPOINTMENT_DATETIME_PATTERN, { + message: + 'appointment_datetime deve incluir data, hora e Z ou offset explícito', + }) + appointment_datetime?: string; + @IsOptional() @IsIn( - [ - AppointmentSchedulingMethod.EMAIL, - AppointmentSchedulingMethod.CALENDLY, - ], + [AppointmentSchedulingMethod.EMAIL, AppointmentSchedulingMethod.CALENDLY], { message: 'scheduling_method deve ser EMAIL ou CALENDLY', }, diff --git a/backend/src/features/appointments/dto/get-appointments-query.dto.ts b/backend/src/features/appointments/dto/get-appointments-query.dto.ts index 40806581..a35a7773 100644 --- a/backend/src/features/appointments/dto/get-appointments-query.dto.ts +++ b/backend/src/features/appointments/dto/get-appointments-query.dto.ts @@ -6,6 +6,7 @@ import { IsDateString, IsUUID, IsIn, + Max, } from 'class-validator'; import { Type } from 'class-transformer'; import { ProductType } from '@prisma/client'; @@ -45,7 +46,7 @@ export class GetAppointmentsQueryDto { @Type(() => Number) @IsInt({ message: 'limit deve ser um número inteiro' }) @Min(1, { message: 'limit deve ser no mínimo 1' }) - @Type(() => Number) + @Max(100, { message: 'limit deve ser no máximo 100' }) limit?: number = 20; // ═══════════════════════════════════════════════════════════════════════════ diff --git a/backend/src/features/appointments/dto/index.ts b/backend/src/features/appointments/dto/index.ts index 4ff7585a..9c83a94a 100644 --- a/backend/src/features/appointments/dto/index.ts +++ b/backend/src/features/appointments/dto/index.ts @@ -2,6 +2,7 @@ export * from './create-appointment.dto'; export * from './create-platform-appointment.dto'; export * from './create-pending-appointment.dto'; +export * from './check-existing-appointment.dto'; export * from './reschedule-appointment.dto'; export * from './get-appointments-query.dto'; export * from './update-appointment-status.dto'; diff --git a/backend/src/features/appointments/dto/update-appointment-status.dto.ts b/backend/src/features/appointments/dto/update-appointment-status.dto.ts index 24bed597..2c7baad4 100644 --- a/backend/src/features/appointments/dto/update-appointment-status.dto.ts +++ b/backend/src/features/appointments/dto/update-appointment-status.dto.ts @@ -7,7 +7,7 @@ import { StatusAgendamento } from '@prisma/client'; * Fluxo de status: * 1. SCHEDULED (padrão ao criar) * 2. COMPLETED (quando reunião ocorre) → Move Process para NEGOTIATION (se estava em SCHEDULING) - * 3. CANCELLED (se cancelado) + * 3. CANCELLED (somente enquanto o Process ainda está em SCHEDULING) * * Frontend: * - Botão "Confirmar realização" (especialista) → status = COMPLETED @@ -21,14 +21,14 @@ export class UpdateAppointmentStatusDto { * * Transições permitidas: * - SCHEDULED → COMPLETED: move Process para NEGOTIATION - * - SCHEDULED → CANCELLED: cancela agendamento - * - COMPLETED → CANCELLED: undo (reverter) - * - CANCELLED → SCHEDULED: reativar (raramente usado) + * - PENDING/SCHEDULED → CANCELLED: cancela enquanto o Process está em SCHEDULING + * - COMPLETED ou Process em NEGOTIATION+: cancelamento rejeitado + * - CANCELLED → SCHEDULED: não permitido por esta rota * * Backend validará: * - Transições lógicas (ex: não voltar de COMPLETED para SCHEDULED sem razão) - * - Se status=COMPLETED, Process está em SCHEDULING ou NEGOTIATION - * - Evitar conflito: se Process já está em NEGOTIATION, manter sem retroceder + * - Se status=COMPLETED, o appointment ainda está SCHEDULED + * - Se status=CANCELLED, o Process vinculado ainda está em SCHEDULING */ @IsEnum(StatusAgendamento, { message: 'status deve ser SCHEDULED, COMPLETED ou CANCELLED', diff --git a/backend/src/features/appointments/entities/appointment.response.ts b/backend/src/features/appointments/entities/appointment.response.ts index 183685fd..1157530f 100644 --- a/backend/src/features/appointments/entities/appointment.response.ts +++ b/backend/src/features/appointments/entities/appointment.response.ts @@ -6,6 +6,27 @@ import { } from '@prisma/client'; import { Expose, Type } from 'class-transformer'; +export type ExistingAppointmentCheck = + | { exists: false } + | { + exists: true; + appointment_id: string; + process_id: string; + appointment_status: StatusAgendamento; + scheduling_method: AppointmentSchedulingMethod | null; + appointment_datetime: Date | null; + specialist_contact_email?: string; + }; + +export interface ActiveProcessSnapshot { + process_id: string; + appointment_id: string | null; + appointment_status: StatusAgendamento | null; + scheduling_method: AppointmentSchedulingMethod | null; + appointment_datetime: Date | null; + specialist_contact_email?: string; +} + /** * DTO aninhado: dados do cliente no agendamento * Contém informações mínimas necessárias para exibição @@ -139,6 +160,13 @@ export class ProductResponseDto { * - Exemplo: "2024-10-10T14:00:00Z" → 14:00 (São Paulo, -03:00) */ export class AppointmentResponseEntity { + @Expose() + process_id?: string; + + /** Contato liberado somente ao cliente autenticado no fluxo EMAIL. */ + @Expose() + specialist_contact_email?: string; + /** * ID único do agendamento (UUID) */ diff --git a/backend/src/features/boats/boats.controller.spec.ts b/backend/src/features/boats/boats.controller.spec.ts index d92720ea..d6a6430d 100644 --- a/backend/src/features/boats/boats.controller.spec.ts +++ b/backend/src/features/boats/boats.controller.spec.ts @@ -4,12 +4,47 @@ import { BoatsController } from './boats.controller'; function mkController() { const boatsService = { create: jest.fn().mockResolvedValue({ id: 'boat-1' }), + findOne: jest.fn().mockResolvedValue({ + id: 'boat-1', + specialist_id: 'spec-1', + }), + update: jest.fn().mockResolvedValue({ id: 'boat-1' }), + prepareProductImages: jest.fn().mockResolvedValue([]), + cleanupPreparedImages: jest.fn().mockResolvedValue(undefined), } as any; const productImportJobsService = { createJobFromCsv: jest.fn().mockResolvedValue({ id: 'job-1' }), } as any; - const controller = new BoatsController(boatsService, productImportJobsService); - return { controller, boatsService, productImportJobsService }; + const actorContext = { + resolve: jest.fn().mockImplementation(async (user, target) => ({ + actorId: user.id, + actorRole: user.role, + specialistId: target ?? user.id, + delegated: user.role === 'ADMIN', + specialist: {}, + })), + assertResourceSpecialist: jest.fn(), + } as any; + const audit = { record: jest.fn().mockResolvedValue(undefined) } as any; + const tx = { name: 'tx' } as any; + const prisma = { + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const controller = new (BoatsController as any)( + boatsService, + productImportJobsService, + actorContext, + audit, + prisma, + ); + return { + controller, + boatsService, + productImportJobsService, + audit, + prisma, + tx, + }; } const specialist = { @@ -20,14 +55,100 @@ const specialist = { describe('BoatsController — Calendly opcional', () => { it('permite criação manual sem consultar Calendly', async () => { - const { controller, boatsService } = mkController(); + const { controller, boatsService, tx } = mkController(); const dto = {} as any; await expect(controller.create(dto, specialist)).resolves.toEqual({ id: 'boat-1', }); expect(dto.specialist_id).toBe(specialist.id); - expect(boatsService.create).toHaveBeenCalledWith(dto); + expect(boatsService.create).toHaveBeenCalledWith( + dto, + tx, + expect.objectContaining({ productId: expect.any(String), images: [] }), + ); + }); + + it('não permite trocar o owner no PATCH comum', async () => { + const { controller, boatsService } = mkController(); + + await expect( + controller.update( + 'boat-1', + { specialist_id: 'spec-2' } as any, + specialist, + ), + ).rejects.toMatchObject({ status: 400 }); + expect(boatsService.update).not.toHaveBeenCalled(); + }); + + it('executa criação manual e auditoria na mesma transação', async () => { + const { controller, boatsService, audit, prisma, tx } = mkController(); + audit.record.mockRejectedValueOnce(new Error('audit unavailable')); + + await expect(controller.create({} as any, specialist)).rejects.toThrow( + 'audit unavailable', + ); + + expect(prisma.$transaction).toHaveBeenCalledTimes(1); + expect(boatsService.create).toHaveBeenCalledWith( + expect.objectContaining({ specialist_id: specialist.id }), + tx, + expect.objectContaining({ productId: expect.any(String), images: [] }), + ); + expect(audit.record).toHaveBeenCalledWith(expect.any(Object), tx); + }); + + it('aguarda upload fora da transação e compensa se a auditoria falhar', async () => { + const { controller, boatsService, audit, prisma } = mkController(); + const prepared = [{ image_url: 'boats/new-key.jpg', is_primary: true }]; + let finishUpload!: (images: typeof prepared) => void; + boatsService.prepareProductImages.mockReturnValueOnce( + new Promise((resolve) => { + finishUpload = resolve; + }), + ); + audit.record.mockRejectedValueOnce(new Error('audit unavailable')); + + const operation = controller.create( + { images: [{ data: 'base64', is_primary: true }] } as any, + specialist, + ); + const rejection = expect(operation).rejects.toThrow('audit unavailable'); + await Promise.resolve(); + + expect(boatsService.prepareProductImages).toHaveBeenCalledTimes(1); + expect(prisma.$transaction).not.toHaveBeenCalled(); + finishUpload(prepared); + await rejection; + expect(boatsService.cleanupPreparedImages).toHaveBeenCalledWith(prepared); + }); + + it('também prepara PATCH fora da transação e compensa falha de auditoria', async () => { + const { controller, boatsService, audit, prisma } = mkController(); + const prepared = [{ image_url: 'boats/patch-key.jpg', is_primary: true }]; + let finishUpload!: (images: typeof prepared) => void; + boatsService.prepareProductImages.mockReturnValueOnce( + new Promise((resolve) => { + finishUpload = resolve; + }), + ); + audit.record.mockRejectedValueOnce(new Error('audit unavailable')); + + const operation = controller.update( + 'boat-1', + { images: [{ data: 'base64', is_primary: true }] } as any, + specialist, + ); + const rejection = expect(operation).rejects.toThrow('audit unavailable'); + await Promise.resolve(); + await Promise.resolve(); + + expect(boatsService.prepareProductImages).toHaveBeenCalledTimes(1); + expect(prisma.$transaction).not.toHaveBeenCalled(); + finishUpload(prepared); + await rejection; + expect(boatsService.cleanupPreparedImages).toHaveBeenCalledWith(prepared); }); it('permite importação CSV sem consultar Calendly', async () => { @@ -45,6 +166,11 @@ describe('BoatsController — Calendly opcional', () => { file.buffer, specialist, ProductType.BOAT, + expect.objectContaining({ + mode: 'ADDITIVE', + confirmSynchronize: false, + context: expect.objectContaining({ specialistId: specialist.id }), + }), ); }); }); diff --git a/backend/src/features/boats/boats.controller.ts b/backend/src/features/boats/boats.controller.ts index e70e6d94..55cad879 100644 --- a/backend/src/features/boats/boats.controller.ts +++ b/backend/src/features/boats/boats.controller.ts @@ -27,27 +27,91 @@ import { UserEntity } from 'src/auth/entities/user.entity'; import { assertSpecialistCanCreate, assertSpecialistCanModify, + assertNoProductOwnerMutation, assertSpecialistOwnsProduct, } from 'src/shared/helpers/specialist-auth.helper'; import { Public } from 'src/shared/decorators/public.decorator'; import { ProductImportJobsService } from '../product-import-jobs/product-import-jobs.service'; +import { ActorContextService } from 'src/shared/actor-context/actor-context.service'; +import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service'; +import { ProductCsvImportDto } from '../product-import-jobs/dto/product-csv-import.dto'; +import { PrismaService } from 'src/prisma/prisma.service'; +import { randomUUID } from 'node:crypto'; @Controller('boats') export class BoatsController { constructor( private readonly boatsService: BoatsService, private readonly productImportJobsService: ProductImportJobsService, + private readonly actorContextService: ActorContextService, + private readonly delegatedAudit: DelegatedActionAuditService, + private readonly prisma: PrismaService, ) {} @Post() @Roles(UserRole.ADMIN, UserRole.SPECIALIST) - create( + async create( @Body() createBoatDto: CreateBoatDto, @CurrentUser() user: UserEntity, ) { - assertSpecialistCanCreate('BOAT', user); - createBoatDto.specialist_id = user.id; - return this.boatsService.create(createBoatDto); + const context = await this.actorContextService.resolve( + user, + createBoatDto.specialist_id, + ProductType.BOAT, + ); + createBoatDto.specialist_id = context.specialistId; + const productId = randomUUID(); + const preparedImages = await this.boatsService.prepareProductImages( + productId, + createBoatDto.images, + ); + try { + return await this.prisma.$transaction(async (tx) => { + const boat = await this.boatsService.create(createBoatDto, tx, { + productId, + images: preparedImages, + }); + await this.delegatedAudit.record( + { + context, + action: 'PRODUCT_CREATE', + resourceType: 'BOAT', + resourceId: boat.id, + }, + tx, + ); + return boat; + }); + } catch (error) { + await this.boatsService.cleanupPreparedImages(preparedImages); + throw error; + } + } + + @Post('import-csv/preview') + @Roles(UserRole.ADMIN, UserRole.SPECIALIST) + @UseInterceptors( + FileInterceptor('file', { limits: { fileSize: 50 * 1024 * 1024 } }), + ) + async previewCsvImport( + @UploadedFile() file: Express.Multer.File, + @CurrentUser() user: UserEntity, + @Body() options: ProductCsvImportDto = new ProductCsvImportDto(), + ) { + const context = await this.actorContextService.resolve( + user, + options.specialist_id, + ProductType.BOAT, + ); + if (!file?.originalname?.toLowerCase().endsWith('.csv')) { + throw new BadRequestException('Arquivo CSV é obrigatório.'); + } + return this.productImportJobsService.previewCsvImport( + file.buffer, + ProductType.BOAT, + context.specialistId, + options.mode, + ); } @Post('import-csv') @@ -58,8 +122,13 @@ export class BoatsController { async importCsv( @UploadedFile() file: Express.Multer.File, @CurrentUser() user: UserEntity, + @Body() options: ProductCsvImportDto = new ProductCsvImportDto(), ) { - assertSpecialistCanCreate('BOAT', user); + const context = await this.actorContextService.resolve( + user, + options.specialist_id, + ProductType.BOAT, + ); if (!file) { throw new BadRequestException('Arquivo CSV é obrigatório.'); @@ -78,6 +147,12 @@ export class BoatsController { file.buffer, user, ProductType.BOAT, + { + context, + mode: options.mode, + confirmSynchronize: options.confirm_synchronize, + synchronizePreviewToken: options.synchronize_preview_token, + }, ); } @@ -138,6 +213,44 @@ export class BoatsController { }; } + @Get('admin/all') + @Roles(UserRole.ADMIN) + async getAllBoatsForAdmin( + @Query() query: any, + @CurrentUser() user: UserEntity, + ) { + let { page, perPage, target_specialist_id, ...rawFilters } = query; + page = Number(page) || 1; + perPage = Number(perPage) || 20; + const context = await this.actorContextService.resolve( + user, + target_specialist_id, + ProductType.BOAT, + ); + rawFilters.specialist_id = context.specialistId; + const { data, count, filters = {} } = await this.boatsService.getAllBoats( + { page, perPage, appliedFilters: rawFilters }, + true, + ); + const skip = (page - 1) * perPage; + return { + success: true, + message: 'Catálogo administrativo de lanchas listado com sucesso', + data, + meta: { + pagination: { + current_page: page, + total_pages: Math.ceil(count / perPage), + has_next: skip + perPage < count, + has_prev: skip > 0, + total: count, + per_page: perPage, + }, + filters: { applied_filters: filters, total_without_filters: count }, + }, + }; + } + @Get(':id') @Public() findOne(@Param('id') id: string) { @@ -150,19 +263,74 @@ export class BoatsController { @Param('id') id: string, @Body() updateBoatDto: UpdateBoatDto, @CurrentUser() user: UserEntity, + @Query('target_specialist_id') targetSpecialistId?: string, ) { - assertSpecialistCanModify('BOAT', user); + assertNoProductOwnerMutation(updateBoatDto as Record); + const context = await this.actorContextService.resolve( + user, + targetSpecialistId, + ProductType.BOAT, + ); const existing = await this.boatsService.findOne(id); - assertSpecialistOwnsProduct(user, existing?.specialist_id); - return this.boatsService.update(id, updateBoatDto); + this.actorContextService.assertResourceSpecialist( + context, + existing?.specialist_id, + ); + const preparedImages = await this.boatsService.prepareProductImages( + id, + updateBoatDto.images, + ); + try { + return await this.prisma.$transaction(async (tx) => { + const boat = await this.boatsService.update(id, updateBoatDto, tx, { + images: preparedImages, + }); + await this.delegatedAudit.record( + { + context, + action: 'PRODUCT_UPDATE', + resourceType: 'BOAT', + resourceId: id, + }, + tx, + ); + return boat; + }); + } catch (error) { + await this.boatsService.cleanupPreparedImages(preparedImages); + throw error; + } } @Delete(':id') @Roles(UserRole.ADMIN, UserRole.SPECIALIST) - async remove(@Param('id') id: string, @CurrentUser() user: UserEntity) { - assertSpecialistCanModify('BOAT', user); + async remove( + @Param('id') id: string, + @CurrentUser() user: UserEntity, + @Query('target_specialist_id') targetSpecialistId?: string, + ) { + const context = await this.actorContextService.resolve( + user, + targetSpecialistId, + ProductType.BOAT, + ); const existing = await this.boatsService.findOne(id); - assertSpecialistOwnsProduct(user, existing?.specialist_id); - return this.boatsService.remove(id); + this.actorContextService.assertResourceSpecialist( + context, + existing?.specialist_id, + ); + return this.prisma.$transaction(async (tx) => { + const result = await this.boatsService.remove(id, tx); + await this.delegatedAudit.record( + { + context, + action: 'PRODUCT_DEACTIVATE', + resourceType: 'BOAT', + resourceId: id, + }, + tx, + ); + return result; + }); } } diff --git a/backend/src/features/boats/boats.service.ts b/backend/src/features/boats/boats.service.ts index 79d6a2e1..92ac180a 100644 --- a/backend/src/features/boats/boats.service.ts +++ b/backend/src/features/boats/boats.service.ts @@ -1,4 +1,9 @@ -import { Injectable, NotFoundException, Logger } from '@nestjs/common'; +import { + HttpException, + Injectable, + NotFoundException, + Logger, +} from '@nestjs/common'; import { Prisma, ProductType } from '@prisma/client'; import { CreateBoatDto } from './dto/create-boat.dto'; import { UpdateBoatDto } from './dto/update-boat.dto'; @@ -11,10 +16,16 @@ import { FiltersBoatMeta, RangeBoatFilters, } from 'src/shared/dto/filters.dto'; -import { Boat } from './entity/boat.entity'; -import { UserEntity } from 'src/auth/entities/user.entity'; import { BOAT_COLUMNS } from 'src/shared/constants/product-columns'; import { updateProductWithMonetaryLock } from '../products/product-monetary-lock'; +import { publicBoatSelect } from 'src/shared/selects/public-catalog.select'; +import { randomUUID } from 'node:crypto'; +import { + cleanupPreparedProductImages, + prepareProductImages, + PreparedProductImage, + ProductImageInput, +} from '../products/product-image-preparation'; @Injectable() export class BoatsService { @@ -28,54 +39,62 @@ export class BoatsService { private s3Service: S3Service, ) {} - async create(createBoatDto: CreateBoatDto) { + prepareProductImages(productId: string, images?: ProductImageInput[]) { + return prepareProductImages(this.s3Service, 'boats', productId, images); + } + + cleanupPreparedImages(images: PreparedProductImage[]) { + return cleanupPreparedProductImages(this.s3Service, images); + } + + async create( + createBoatDto: CreateBoatDto, + client: PrismaService | Prisma.TransactionClient = this.prismaService, + preparedWrite?: { + productId: string; + images: PreparedProductImage[]; + }, + ) { this.logger.log('[create] Iniciando criação de novo barco'); const { images, ...boatData } = createBoatDto; + const productId = preparedWrite?.productId ?? randomUUID(); + const ownsPreparedImages = !preparedWrite; + const preparedImages = + preparedWrite?.images ?? + (await this.prepareProductImages(productId, images)); try { // 1. Criar o barco this.logger.debug( `[create] Criando barco: ${boatData.marca} ${boatData.modelo}`, ); - const boat = await this.prismaService.boat.create({ data: boatData }); + const boat = await client.boat.create({ + data: { ...boatData, id: productId }, + }); this.logger.log(`[create] Barco criado com sucesso - ID: ${boat.id}`); - // 2. Processar e fazer upload das imagens, se existirem - if (images && images.length > 0) { + // 2. Persistir somente referências já preparadas fora da transação + if (preparedImages.length > 0) { this.logger.log( - `[create] Processando ${images.length} imagens para o barco ${boat.id}`, + `[create] Persistindo ${preparedImages.length} imagens para o barco ${boat.id}`, ); - for (let i = 0; i < images.length; i++) { - const image = images[i]; - - const timestamp = Date.now(); - const key = `boats/${boat.id}/${timestamp}-${i}.jpg`; - - this.logger.debug( - `[create] Fazendo upload da imagem ${i + 1}/${images.length} para S3`, - ); - const imageKey = await this.s3Service.uploadBase64Image( - image.data, - key, - ); - - await this.prismaService.boat_image.create({ + for (const image of preparedImages) { + await client.boat_image.create({ data: { boat_id: boat.id, - image_url: imageKey, + image_url: image.image_url, is_primary: image.is_primary, product_type: 'BOAT', }, }); - this.logger.debug(`[create] Imagem ${i + 1} salva com sucesso`); } this.logger.log( - `[create] Todas as ${images.length} imagens processadas com sucesso`, + `[create] Todas as ${preparedImages.length} imagens persistidas com sucesso`, ); } // 3. Retornar o barco com as imagens - const boatWithImages = await this.prismaService.boat.findUnique({ + const boatWithImages = await client.boat.findUnique({ where: { id: boat.id }, include: { images: true }, }); @@ -87,7 +106,13 @@ export class BoatsService { ); return boatWithImages; } catch (error) { - if (error instanceof Prisma.PrismaClientKnownRequestError) { + if (ownsPreparedImages) { + await this.cleanupPreparedImages(preparedImages); + } + if ( + error instanceof HttpException || + error instanceof Prisma.PrismaClientKnownRequestError + ) { throw error; } this.logger.error( @@ -102,14 +127,14 @@ export class BoatsService { page, perPage, appliedFilters, - }: QueryDto) { + }: QueryDto, includeInactive = false) { // Cálculo das variáveis que serão utilizadas na requisição ao banco de dados const take = perPage; const skip = page && take ? (page - 1) * take : 0; //Exact const where: any = {}; - where.is_active = true; + if (!includeInactive) where.is_active = true; const exacts: ExactBoatFilters = { estado: appliedFilters?.estado, tipo_embarcacao: appliedFilters?.tipo_embarcacao, @@ -171,16 +196,13 @@ export class BoatsService { skip: skip, take: take, where: where, - include: { - images: true, - specialist: true, - }, + select: publicBoatSelect, }), this.prismaService.boat.count({ where }), ]); // Converter as keys do S3 em URLs assinadas para cada barco - const boatEntities: Boat[] = await Promise.all( + const boatEntities = await Promise.all( boats.map(async (boat) => { let imagesWithUrls: any[] = []; if (boat.images && boat.images.length > 0) { @@ -197,9 +219,7 @@ export class BoatsService { descricao: boat.descricao_completa, valor: boat.valor.toNumber(), images: imagesWithUrls, - specialist: boat.specialist - ? UserEntity.fromPrisma(boat.specialist) - : null, + specialist: boat.specialist, }; }), ); @@ -215,7 +235,7 @@ export class BoatsService { this.logger.log(`[findOne] Buscando barco - ID: ${id}`); const boat = await this.prismaService.boat.findUnique({ where: { id }, - include: { images: true }, + select: publicBoatSelect, }); if (!boat) { this.logger.warn(`[findOne] Barco não encontrado - ID: ${id}`); @@ -237,42 +257,40 @@ export class BoatsService { return { ...boat }; } - async update(id: string, updateBoatDto: UpdateBoatDto) { + async update( + id: string, + updateBoatDto: UpdateBoatDto, + client: PrismaService | Prisma.TransactionClient = this.prismaService, + preparedWrite?: { images: PreparedProductImage[] }, + ) { const { images, ...boatData } = updateBoatDto; - - await updateProductWithMonetaryLock(this.prismaService, { - productType: ProductType.BOAT, - productId: id, - nextValue: updateBoatDto.valor, - nextCurrency: updateBoatDto.currency, - data: boatData, - notFoundMessage: 'Boat not found', - }); + const ownsPreparedImages = !preparedWrite; + const preparedImages = + preparedWrite?.images ?? (await this.prepareProductImages(id, images)); try { + await updateProductWithMonetaryLock(client, { + productType: ProductType.BOAT, + productId: id, + nextValue: updateBoatDto.valor, + nextCurrency: updateBoatDto.currency, + data: boatData, + notFoundMessage: 'Boat not found', + }); + // 1. Se houver novas imagens, processar if (images && images.length > 0) { // Remover imagens antigas - await this.prismaService.boat_image.deleteMany({ + await client.boat_image.deleteMany({ where: { boat_id: id }, }); - // Adicionar novas imagens - for (let i = 0; i < images.length; i++) { - const image = images[i]; - - const timestamp = Date.now(); - const key = `boats/${id}/${timestamp}-${i}.jpg`; - - const imageKey = await this.s3Service.uploadBase64Image( - image.data, - key, - ); - - await this.prismaService.boat_image.create({ + // Adicionar referências das imagens já preparadas + for (const image of preparedImages) { + await client.boat_image.create({ data: { boat_id: id, - image_url: imageKey, + image_url: image.image_url, is_primary: image.is_primary, product_type: 'BOAT', }, @@ -281,21 +299,30 @@ export class BoatsService { } // 2. Retornar o barco atualizado com imagens - return await this.prismaService.boat.findUnique({ + return await client.boat.findUnique({ where: { id }, include: { images: true }, }); } catch (error) { - if (error instanceof Prisma.PrismaClientKnownRequestError) { + if (ownsPreparedImages) { + await this.cleanupPreparedImages(preparedImages); + } + if ( + error instanceof HttpException || + error instanceof Prisma.PrismaClientKnownRequestError + ) { throw error; } throw new Error(`Erro ao atualizar lancha: ${error.message}`); } } - async remove(id: string) { + async remove( + id: string, + client: PrismaService | Prisma.TransactionClient = this.prismaService, + ) { try { - await updateProductWithMonetaryLock(this.prismaService, { + await updateProductWithMonetaryLock(client, { productType: ProductType.BOAT, productId: id, data: { diff --git a/backend/src/features/cars/cars.controller.spec.ts b/backend/src/features/cars/cars.controller.spec.ts index cf761eac..bfc51293 100644 --- a/backend/src/features/cars/cars.controller.spec.ts +++ b/backend/src/features/cars/cars.controller.spec.ts @@ -4,12 +4,48 @@ import { CarsController } from './cars.controller'; function mkController() { const carsService = { create: jest.fn().mockResolvedValue({ id: 'car-1' }), + findOne: jest.fn().mockResolvedValue({ + id: 'car-1', + specialist_id: 'spec-1', + }), + update: jest.fn().mockResolvedValue({ id: 'car-1' }), + prepareProductImages: jest.fn().mockResolvedValue([]), + cleanupPreparedImages: jest.fn().mockResolvedValue(undefined), } as any; const productImportJobsService = { createJobFromCsv: jest.fn().mockResolvedValue({ id: 'job-1' }), } as any; - const controller = new CarsController(carsService, productImportJobsService); - return { controller, carsService, productImportJobsService }; + const actorContext = { + resolve: jest.fn().mockImplementation(async (user, target) => ({ + actorId: user.id, + actorRole: user.role, + specialistId: target ?? user.id, + delegated: user.role === 'ADMIN', + specialist: {}, + })), + assertResourceSpecialist: jest.fn(), + } as any; + const audit = { record: jest.fn().mockResolvedValue(undefined) } as any; + const tx = { name: 'tx' } as any; + const prisma = { + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const controller = new (CarsController as any)( + carsService, + productImportJobsService, + actorContext, + audit, + prisma, + ); + return { + controller, + carsService, + productImportJobsService, + actorContext, + audit, + prisma, + tx, + }; } const specialist = { @@ -20,14 +56,127 @@ const specialist = { describe('CarsController — Calendly opcional', () => { it('permite criação manual sem consultar Calendly', async () => { - const { controller, carsService } = mkController(); + const { controller, carsService, tx } = mkController(); const dto = {} as any; await expect(controller.create(dto, specialist)).resolves.toEqual({ id: 'car-1', }); expect(dto.specialist_id).toBe(specialist.id); - expect(carsService.create).toHaveBeenCalledWith(dto); + expect(carsService.create).toHaveBeenCalledWith( + dto, + tx, + expect.objectContaining({ productId: expect.any(String), images: [] }), + ); + }); + + it('mantém ADMIN como ator e grava o SPECIALIST selecionado como owner', async () => { + const { controller, carsService, actorContext, audit, tx } = mkController(); + const admin = { id: 'admin-1', role: 'ADMIN' } as any; + const dto = { specialist_id: 'spec-1' } as any; + + await controller.create(dto, admin); + + expect(actorContext.resolve).toHaveBeenCalledWith( + admin, + 'spec-1', + ProductType.CAR, + ); + expect(carsService.create).toHaveBeenCalledWith( + expect.objectContaining({ specialist_id: 'spec-1' }), + tx, + expect.objectContaining({ productId: expect.any(String), images: [] }), + ); + expect(audit.record).toHaveBeenCalledWith( + expect.objectContaining({ + action: 'PRODUCT_CREATE', + resourceType: 'CAR', + resourceId: 'car-1', + }), + tx, + ); + }); + + it('executa criação manual e auditoria na mesma transação', async () => { + const { controller, carsService, audit, prisma, tx } = mkController(); + audit.record.mockRejectedValueOnce(new Error('audit unavailable')); + + await expect(controller.create({} as any, specialist)).rejects.toThrow( + 'audit unavailable', + ); + + expect(prisma.$transaction).toHaveBeenCalledTimes(1); + expect(carsService.create).toHaveBeenCalledWith( + expect.objectContaining({ specialist_id: specialist.id }), + tx, + expect.objectContaining({ productId: expect.any(String), images: [] }), + ); + expect(audit.record).toHaveBeenCalledWith(expect.any(Object), tx); + }); + + it('aguarda upload fora da transação e compensa se a auditoria falhar', async () => { + const { controller, carsService, audit, prisma } = mkController(); + const prepared = [{ image_url: 'cars/new-key.jpg', is_primary: true }]; + let finishUpload!: (images: typeof prepared) => void; + carsService.prepareProductImages.mockReturnValueOnce( + new Promise((resolve) => { + finishUpload = resolve; + }), + ); + audit.record.mockRejectedValueOnce(new Error('audit unavailable')); + + const operation = controller.create( + { images: [{ data: 'base64', is_primary: true }] } as any, + specialist, + ); + const rejection = expect(operation).rejects.toThrow('audit unavailable'); + await Promise.resolve(); + + expect(carsService.prepareProductImages).toHaveBeenCalledTimes(1); + expect(prisma.$transaction).not.toHaveBeenCalled(); + finishUpload(prepared); + await rejection; + expect(carsService.cleanupPreparedImages).toHaveBeenCalledWith(prepared); + }); + + it('também prepara PATCH fora da transação e compensa falha de auditoria', async () => { + const { controller, carsService, audit, prisma } = mkController(); + const prepared = [{ image_url: 'cars/patch-key.jpg', is_primary: true }]; + let finishUpload!: (images: typeof prepared) => void; + carsService.prepareProductImages.mockReturnValueOnce( + new Promise((resolve) => { + finishUpload = resolve; + }), + ); + audit.record.mockRejectedValueOnce(new Error('audit unavailable')); + + const operation = controller.update( + 'car-1', + { images: [{ data: 'base64', is_primary: true }] } as any, + specialist, + ); + const rejection = expect(operation).rejects.toThrow('audit unavailable'); + await Promise.resolve(); + await Promise.resolve(); + + expect(carsService.prepareProductImages).toHaveBeenCalledTimes(1); + expect(prisma.$transaction).not.toHaveBeenCalled(); + finishUpload(prepared); + await rejection; + expect(carsService.cleanupPreparedImages).toHaveBeenCalledWith(prepared); + }); + + it('não permite remover o owner com specialist_id null no PATCH', async () => { + const { controller, carsService } = mkController(); + + await expect( + controller.update( + 'car-1', + { specialist_id: null } as any, + specialist, + ), + ).rejects.toMatchObject({ status: 400 }); + expect(carsService.update).not.toHaveBeenCalled(); }); it('permite importação CSV sem consultar Calendly', async () => { @@ -45,6 +194,11 @@ describe('CarsController — Calendly opcional', () => { file.buffer, specialist, ProductType.CAR, + expect.objectContaining({ + mode: 'ADDITIVE', + confirmSynchronize: false, + context: expect.objectContaining({ specialistId: specialist.id }), + }), ); }); }); diff --git a/backend/src/features/cars/cars.controller.ts b/backend/src/features/cars/cars.controller.ts index 65c19f3c..4e7fe34c 100644 --- a/backend/src/features/cars/cars.controller.ts +++ b/backend/src/features/cars/cars.controller.ts @@ -25,29 +25,90 @@ import { ProductType, UserRole } from '@prisma/client'; import { CurrentUser } from 'src/shared/decorators/current-user.decorator'; import { UserEntity } from 'src/auth/entities/user.entity'; import { - assertSpecialistCanCreate, - assertSpecialistCanModify, - assertSpecialistOwnsProduct, + assertNoProductOwnerMutation, } from 'src/shared/helpers/specialist-auth.helper'; import { Public } from 'src/shared/decorators/public.decorator'; import { ProductImportJobsService } from '../product-import-jobs/product-import-jobs.service'; +import { ActorContextService } from 'src/shared/actor-context/actor-context.service'; +import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service'; +import { ProductCsvImportDto } from '../product-import-jobs/dto/product-csv-import.dto'; +import { PrismaService } from 'src/prisma/prisma.service'; +import { randomUUID } from 'node:crypto'; @Controller('cars') export class CarsController { constructor( private readonly carsService: CarsService, private readonly productImportJobsService: ProductImportJobsService, + private readonly actorContextService: ActorContextService, + private readonly delegatedAudit: DelegatedActionAuditService, + private readonly prisma: PrismaService, ) {} @Post() @Roles(UserRole.ADMIN, UserRole.SPECIALIST) - create( + async create( @Body() createCarDto: CreateCarDto, @CurrentUser() user: UserEntity, ) { - assertSpecialistCanCreate('CAR', user); - createCarDto.specialist_id = user.id; - return this.carsService.create(createCarDto); + const context = await this.actorContextService.resolve( + user, + createCarDto.specialist_id, + ProductType.CAR, + ); + createCarDto.specialist_id = context.specialistId; + const productId = randomUUID(); + const preparedImages = await this.carsService.prepareProductImages( + productId, + createCarDto.images, + ); + try { + return await this.prisma.$transaction(async (tx) => { + const car = await this.carsService.create(createCarDto, tx, { + productId, + images: preparedImages, + }); + await this.delegatedAudit.record( + { + context, + action: 'PRODUCT_CREATE', + resourceType: 'CAR', + resourceId: car!.id, + }, + tx, + ); + return car; + }); + } catch (error) { + await this.carsService.cleanupPreparedImages(preparedImages); + throw error; + } + } + + @Post('import-csv/preview') + @Roles(UserRole.ADMIN, UserRole.SPECIALIST) + @UseInterceptors( + FileInterceptor('file', { limits: { fileSize: 50 * 1024 * 1024 } }), + ) + async previewCsvImport( + @UploadedFile() file: Express.Multer.File, + @CurrentUser() user: UserEntity, + @Body() options: ProductCsvImportDto = new ProductCsvImportDto(), + ) { + const context = await this.actorContextService.resolve( + user, + options.specialist_id, + ProductType.CAR, + ); + if (!file?.originalname?.toLowerCase().endsWith('.csv')) { + throw new BadRequestException('Arquivo CSV é obrigatório.'); + } + return this.productImportJobsService.previewCsvImport( + file.buffer, + ProductType.CAR, + context.specialistId, + options.mode, + ); } @Post('import-csv') @@ -58,8 +119,13 @@ export class CarsController { async importCsv( @UploadedFile() file: Express.Multer.File, @CurrentUser() user: UserEntity, + @Body() options: ProductCsvImportDto = new ProductCsvImportDto(), ) { - assertSpecialistCanCreate('CAR', user); + const context = await this.actorContextService.resolve( + user, + options.specialist_id, + ProductType.CAR, + ); if (!file) { throw new BadRequestException('Arquivo CSV é obrigatório.'); @@ -78,6 +144,12 @@ export class CarsController { file.buffer, user, ProductType.CAR, + { + context, + mode: options.mode, + confirmSynchronize: options.confirm_synchronize, + synchronizePreviewToken: options.synchronize_preview_token, + }, ); } @@ -138,6 +210,44 @@ export class CarsController { }; } + @Get('admin/all') + @Roles(UserRole.ADMIN) + async getAllCarsForAdmin( + @Query() query: any, + @CurrentUser() user: UserEntity, + ) { + let { page, perPage, target_specialist_id, ...rawFilters } = query; + page = Number(page) || 1; + perPage = Number(perPage) || 20; + const context = await this.actorContextService.resolve( + user, + target_specialist_id, + ProductType.CAR, + ); + rawFilters.specialist_id = context.specialistId; + const { data, count, filters = {} } = await this.carsService.getAllCars( + { page, perPage, appliedFilters: rawFilters }, + true, + ); + const skip = (page - 1) * perPage; + return { + success: true, + message: 'Catálogo administrativo de carros listado com sucesso', + data, + meta: { + pagination: { + current_page: page, + total_pages: Math.ceil(count / perPage), + has_next: skip + perPage < count, + has_prev: skip > 0, + total: count, + per_page: perPage, + }, + filters: { applied_filters: filters, total_without_filters: count }, + }, + }; + } + @Get(':id') @Public() findOne(@Param('id') id: string) { @@ -150,23 +260,74 @@ export class CarsController { @Param('id') id: string, @Body() updateCarDto: UpdateCarDto, @CurrentUser() user: UserEntity, + @Query('target_specialist_id') targetSpecialistId?: string, ) { - if (updateCarDto.specialist_id) { - delete updateCarDto.specialist_id; - } - - assertSpecialistCanModify('CAR', user); + assertNoProductOwnerMutation(updateCarDto as Record); + const context = await this.actorContextService.resolve( + user, + targetSpecialistId, + ProductType.CAR, + ); const existing = await this.carsService.findOne(id); - assertSpecialistOwnsProduct(user, existing?.specialist_id); - return this.carsService.update(id, updateCarDto); + this.actorContextService.assertResourceSpecialist( + context, + existing?.specialist_id, + ); + const preparedImages = await this.carsService.prepareProductImages( + id, + updateCarDto.images, + ); + try { + return await this.prisma.$transaction(async (tx) => { + const car = await this.carsService.update(id, updateCarDto, tx, { + images: preparedImages, + }); + await this.delegatedAudit.record( + { + context, + action: 'PRODUCT_UPDATE', + resourceType: 'CAR', + resourceId: id, + }, + tx, + ); + return car; + }); + } catch (error) { + await this.carsService.cleanupPreparedImages(preparedImages); + throw error; + } } @Delete(':id') @Roles(UserRole.ADMIN, UserRole.SPECIALIST) - async remove(@Param('id') id: string, @CurrentUser() user: UserEntity) { - assertSpecialistCanModify('CAR', user); + async remove( + @Param('id') id: string, + @CurrentUser() user: UserEntity, + @Query('target_specialist_id') targetSpecialistId?: string, + ) { + const context = await this.actorContextService.resolve( + user, + targetSpecialistId, + ProductType.CAR, + ); const existing = await this.carsService.findOne(id); - assertSpecialistOwnsProduct(user, existing?.specialist_id); - return this.carsService.remove(id); + this.actorContextService.assertResourceSpecialist( + context, + existing?.specialist_id, + ); + return this.prisma.$transaction(async (tx) => { + const result = await this.carsService.remove(id, tx); + await this.delegatedAudit.record( + { + context, + action: 'PRODUCT_DEACTIVATE', + resourceType: 'CAR', + resourceId: id, + }, + tx, + ); + return result; + }); } } diff --git a/backend/src/features/cars/cars.service.spec.ts b/backend/src/features/cars/cars.service.spec.ts index e17efcb6..1bb1f630 100644 --- a/backend/src/features/cars/cars.service.spec.ts +++ b/backend/src/features/cars/cars.service.spec.ts @@ -1,5 +1,6 @@ import { CarsService } from './cars.service'; import { Prisma, ProductCurrency } from '@prisma/client'; +import { publicCarSelect } from 'src/shared/selects/public-catalog.select'; describe('CarsService — UUID do produto', () => { it('consulta o carro pelo UUID recebido', async () => { @@ -18,7 +19,7 @@ describe('CarsService — UUID do produto', () => { expect(findUnique).toHaveBeenCalledWith({ where: { id: carId }, - include: { images: true }, + select: publicCarSelect, }); }); diff --git a/backend/src/features/cars/cars.service.ts b/backend/src/features/cars/cars.service.ts index 1f2d19f2..9cb6ddd3 100644 --- a/backend/src/features/cars/cars.service.ts +++ b/backend/src/features/cars/cars.service.ts @@ -1,4 +1,9 @@ -import { Injectable, NotFoundException, Logger } from '@nestjs/common'; +import { + HttpException, + Injectable, + NotFoundException, + Logger, +} from '@nestjs/common'; import { Prisma, ProductType } from '@prisma/client'; import { CreateCarDto } from './dto/create-car.dto'; import { UpdateCarDto } from './dto/update-car.dto'; @@ -11,10 +16,16 @@ import { FiltersCarMeta, RangeCarFilters, } from 'src/shared/dto/filters.dto'; -import { Car } from './entity/car.entity'; -import { UserEntity } from 'src/auth/entities/user.entity'; import { CAR_COLUMNS } from 'src/shared/constants/product-columns'; import { updateProductWithMonetaryLock } from '../products/product-monetary-lock'; +import { publicCarSelect } from 'src/shared/selects/public-catalog.select'; +import { randomUUID } from 'node:crypto'; +import { + cleanupPreparedProductImages, + prepareProductImages, + PreparedProductImage, + ProductImageInput, +} from '../products/product-image-preparation'; @Injectable() export class CarsService { @@ -28,33 +39,42 @@ export class CarsService { private s3Service: S3Service, ) {} - async create(createCarDto: CreateCarDto) { + prepareProductImages(productId: string, images?: ProductImageInput[]) { + return prepareProductImages(this.s3Service, 'cars', productId, images); + } + + cleanupPreparedImages(images: PreparedProductImage[]) { + return cleanupPreparedProductImages(this.s3Service, images); + } + + async create( + createCarDto: CreateCarDto, + client: PrismaService | Prisma.TransactionClient = this.prismaService, + preparedWrite?: { + productId: string; + images: PreparedProductImage[]; + }, + ) { const { images, ...carData } = createCarDto; + const productId = preparedWrite?.productId ?? randomUUID(); + const ownsPreparedImages = !preparedWrite; + const preparedImages = + preparedWrite?.images ?? + (await this.prepareProductImages(productId, images)); try { // 1. Criar o carro - const car = await this.prismaService.car.create({ data: carData }); - - // 2. Processar e fazer upload das imagens, se existirem - if (images && images.length > 0) { - for (let i = 0; i < images.length; i++) { - const image = images[i]; - - // Gerar chave única para a imagem no S3 - const timestamp = Date.now(); - const key = `cars/${car.id}/${timestamp}-${i}.jpg`; - - // Upload da imagem base64 para o S3 - const imageKey = await this.s3Service.uploadBase64Image( - image.data, - key, - ); + const car = await client.car.create({ + data: { ...carData, id: productId }, + }); - // Salvar referência da imagem no banco de dados - await this.prismaService.car_image.create({ + // 2. Persistir somente referências já preparadas fora da transação + if (preparedImages.length > 0) { + for (const image of preparedImages) { + await client.car_image.create({ data: { car_id: car.id, - image_url: imageKey, + image_url: image.image_url, is_primary: image.is_primary, product_type: 'CAR', }, @@ -63,12 +83,18 @@ export class CarsService { } // 3. Retornar o carro com as imagens - return await this.prismaService.car.findUnique({ + return await client.car.findUnique({ where: { id: car.id }, include: { images: true }, }); } catch (error) { - if (error instanceof Prisma.PrismaClientKnownRequestError) { + if (ownsPreparedImages) { + await this.cleanupPreparedImages(preparedImages); + } + if ( + error instanceof HttpException || + error instanceof Prisma.PrismaClientKnownRequestError + ) { throw error; } throw new Error(`Erro ao criar carro: ${error.message}`); @@ -79,14 +105,14 @@ export class CarsService { page, perPage, appliedFilters, - }: QueryDto) { + }: QueryDto, includeInactive = false) { // Cálculo das variáveis usadas na requisição ao banco de dados const take = perPage; const skip = page && take ? (page - 1) * take : 0; // Separação dos filtros const where: any = {}; - where.is_active = true; + if (!includeInactive) where.is_active = true; // Exact const exacts: ExactCarFilters = { @@ -152,16 +178,13 @@ export class CarsService { skip: skip, take: take, where: where, - include: { - images: true, - specialist: true, - }, + select: publicCarSelect, }), this.prismaService.car.count({ where }), ]); // Converter as keys do S3 em URLs assinadas para cada carro - const carEntities: Car[] = await Promise.all( + const carEntities = await Promise.all( cars.map(async (car) => { let imagesWithUrls: any[] = []; if (car.images && car.images.length > 0) { @@ -177,9 +200,7 @@ export class CarsService { ...car, valor: car.valor.toNumber(), images: imagesWithUrls, - specialist: car.specialist - ? UserEntity.fromPrisma(car.specialist) - : null, + specialist: car.specialist, }; }), ); @@ -195,7 +216,7 @@ export class CarsService { this.logger.log(`[findOne] Buscando carro - ID: ${id}`); const car = await this.prismaService.car.findUnique({ where: { id }, - include: { images: true }, + select: publicCarSelect, }); if (!car) { this.logger.warn(`[findOne] Carro não encontrado - ID: ${id}`); @@ -217,42 +238,40 @@ export class CarsService { return { ...car }; } - async update(id: string, updateCarDto: UpdateCarDto) { + async update( + id: string, + updateCarDto: UpdateCarDto, + client: PrismaService | Prisma.TransactionClient = this.prismaService, + preparedWrite?: { images: PreparedProductImage[] }, + ) { const { images, ...carData } = updateCarDto; - - await updateProductWithMonetaryLock(this.prismaService, { - productType: ProductType.CAR, - productId: id, - nextValue: updateCarDto.valor, - nextCurrency: updateCarDto.currency, - data: carData, - notFoundMessage: 'Car not found', - }); + const ownsPreparedImages = !preparedWrite; + const preparedImages = + preparedWrite?.images ?? (await this.prepareProductImages(id, images)); try { + await updateProductWithMonetaryLock(client, { + productType: ProductType.CAR, + productId: id, + nextValue: updateCarDto.valor, + nextCurrency: updateCarDto.currency, + data: carData, + notFoundMessage: 'Car not found', + }); + // 1. Se houver novas imagens, processar if (images && images.length > 0) { // Remover imagens antigas - await this.prismaService.car_image.deleteMany({ + await client.car_image.deleteMany({ where: { car_id: id }, }); - // Adicionar novas imagens - for (let i = 0; i < images.length; i++) { - const image = images[i]; - - const timestamp = Date.now(); - const key = `cars/${id}/${timestamp}-${i}.jpg`; - - const imageKey = await this.s3Service.uploadBase64Image( - image.data, - key, - ); - - await this.prismaService.car_image.create({ + // Adicionar referências das imagens já preparadas + for (const image of preparedImages) { + await client.car_image.create({ data: { car_id: id, - image_url: imageKey, + image_url: image.image_url, is_primary: image.is_primary, product_type: 'CAR', }, @@ -261,21 +280,30 @@ export class CarsService { } // 2. Retornar o carro atualizado com imagens - return await this.prismaService.car.findUnique({ + return await client.car.findUnique({ where: { id }, include: { images: true }, }); } catch (error) { - if (error instanceof Prisma.PrismaClientKnownRequestError) { + if (ownsPreparedImages) { + await this.cleanupPreparedImages(preparedImages); + } + if ( + error instanceof HttpException || + error instanceof Prisma.PrismaClientKnownRequestError + ) { throw error; } throw new Error(`Erro ao atualizar carro: ${error.message}`); } } - async remove(id: string) { + async remove( + id: string, + client: PrismaService | Prisma.TransactionClient = this.prismaService, + ) { try { - await updateProductWithMonetaryLock(this.prismaService, { + await updateProductWithMonetaryLock(client, { productType: ProductType.CAR, productId: id, data: { diff --git a/backend/src/features/consultant/consultant.service.ts b/backend/src/features/consultant/consultant.service.ts index 3a937129..eabff710 100644 --- a/backend/src/features/consultant/consultant.service.ts +++ b/backend/src/features/consultant/consultant.service.ts @@ -243,7 +243,7 @@ export class ConsultantService { } return this.prismaService.process.findMany({ - where: { client_id: clientId }, + where: { client_id: clientId, removed_at: null }, include: { specialist: { select: { id: true, name: true, surname: true, speciality: true }, @@ -268,7 +268,7 @@ export class ConsultantService { const clientIds = clients.map((c) => c.id); const clientMap = new Map(clients.map((c) => [c.id, c])); - const where: any = { client_id: { in: clientIds } }; + const where: any = { client_id: { in: clientIds }, removed_at: null }; if (filters.status) where.status = filters.status; if (filters.clientId) { if (!clientIds.includes(filters.clientId)) return []; diff --git a/backend/src/features/contracts/admin-journey-p0.postgres.spec.ts b/backend/src/features/contracts/admin-journey-p0.postgres.spec.ts new file mode 100644 index 00000000..45d3ac79 --- /dev/null +++ b/backend/src/features/contracts/admin-journey-p0.postgres.spec.ts @@ -0,0 +1,306 @@ +import { + BadRequestException, + ConflictException, +} from '@nestjs/common'; +import { + ContractStatus, + PrismaClient, + ProcessStatus, + ProductCurrency, + ProviderStatus, + SignatureType, + UserRole, +} from '@prisma/client'; +import { randomUUID } from 'node:crypto'; +import { ProcessesService } from '../processes/processes.service'; +import { DocuSignWebhookService } from '../../providers/docusign/webhook/webhook.service'; +import { ContractsService } from './contracts.service'; +import { EnvelopeStatus } from '../../providers/docusign/enums/envelope-status.enum'; + +const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL; +const describeWithPostgres = databaseUrl ? describe : describe.skip; + +function completedPayload(envelopeId: string) { + return { + event: 'envelope-completed', + generatedDateTime: '2026-10-23T12:00:00.000Z', + retryCount: 0, + configurationId: 1, + apiVersion: 'v2.1', + data: { + envelopeId, + accountId: 'test-account', + userId: 'test-provider-user', + }, + }; +} + +describeWithPostgres('admin journey P0 — PostgreSQL + simulated DocuSign', () => { + const prisma = new PrismaClient({ + datasources: { db: { url: databaseUrl! } }, + }); + const suffix = randomUUID().replaceAll('-', ''); + const adminId = randomUUID(); + const clientId = randomUUID(); + const specialistId = randomUUID(); + const processIds: string[] = []; + + const notifications = { + sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined), + sendContractGeneratedEmail: jest.fn().mockResolvedValue(undefined), + sendContractSentEmail: jest.fn().mockResolvedValue(undefined), + sendContractSignedEmail: jest.fn().mockResolvedValue(undefined), + sendContractDeclinedEmail: jest.fn().mockResolvedValue(undefined), + sendContractVoidedEmail: jest.fn().mockResolvedValue(undefined), + sendContractTimeoutEmail: jest.fn().mockResolvedValue(undefined), + } as any; + + beforeAll(async () => { + await prisma.user.createMany({ + data: [ + { + id: adminId, + name: 'P0', + surname: 'Admin', + email: `p0-admin-${suffix}@example.test`, + rg: suffix.slice(0, 11), + role: UserRole.ADMIN, + password_hash: 'not-used', + }, + { + id: clientId, + name: 'P0', + surname: 'Client', + email: `p0-client-${suffix}@example.test`, + rg: suffix.slice(11, 22), + role: UserRole.CUSTOMER, + password_hash: 'not-used', + }, + { + id: specialistId, + name: 'P0', + surname: 'Specialist', + email: `p0-specialist-${suffix}@example.test`, + rg: suffix.slice(21, 32), + role: UserRole.SPECIALIST, + password_hash: 'not-used', + commission_rate: 0, + }, + ], + }); + }); + + afterEach(async () => { + if (processIds.length === 0) return; + await prisma.process.updateMany({ + where: { id: { in: processIds } }, + data: { active_contract_id: null }, + }); + await prisma.contract.deleteMany({ + where: { process_id: { in: processIds } }, + }); + await prisma.processStatusHistory.deleteMany({ + where: { processId: { in: processIds } }, + }); + await prisma.processRejection.deleteMany({ + where: { process_id: { in: processIds } }, + }); + await prisma.process.deleteMany({ where: { id: { in: processIds } } }); + processIds.splice(0); + }); + + afterAll(async () => { + await prisma.user.deleteMany({ + where: { id: { in: [adminId, clientId, specialistId] } }, + }); + await prisma.$disconnect(); + }); + + async function createProcess(status = ProcessStatus.DOCUMENTATION) { + const id = randomUUID(); + processIds.push(id); + await prisma.process.create({ + data: { + id, + client_id: clientId, + specialist_id: specialistId, + status, + negotiation_currency: ProductCurrency.BRL, + negotiation_product_value: 100_000, + }, + }); + return id; + } + + async function createContract( + processId: string, + envelopeId: string, + providerStatus = ProviderStatus.SENT, + ) { + return prisma.contract.create({ + data: { + process_id: processId, + provider_name: 'DOCUSIGN', + provider_id: envelopeId, + provider_status: providerStatus, + status: ContractStatus.PENDING, + signature_type: SignatureType.SIMPLE, + uploaded_by_id: adminId, + uploaded_by_type: UserRole.ADMIN, + signed_by_id: clientId, + buyer_name: 'P0 Client', + seller_name: 'P0 Seller', + }, + }); + } + + it('blocks rejection with a live envelope before a later COMPLETED webhook', async () => { + const processId = await createProcess(); + const envelopeId = `p0-reject-${suffix}`; + const contract = await createContract(processId, envelopeId); + await prisma.process.update({ + where: { id: processId }, + data: { active_contract_id: contract.id }, + }); + + const processes = new ProcessesService(prisma as any, notifications); + let rejectionError: unknown; + try { + await processes.rejectProcess( + processId, + adminId, + 'admin requested cancellation', + UserRole.ADMIN, + ); + } catch (error) { + rejectionError = error; + } + + const webhook = new DocuSignWebhookService(prisma as any, notifications); + await webhook.handleEnvelopeStatusChanged(completedPayload(envelopeId)); + + expect(rejectionError).toBeInstanceOf(BadRequestException); + await expect( + prisma.process.findUniqueOrThrow({ where: { id: processId } }), + ).resolves.toMatchObject({ + status: ProcessStatus.COMPLETED, + active_contract_id: contract.id, + }); + await expect( + prisma.processStatusHistory.count({ + where: { processId, status: ProcessStatus.REJECTED }, + }), + ).resolves.toBe(0); + }); + + it('updates an old contract from a delayed webhook without changing the process', async () => { + const processId = await createProcess(); + const oldEnvelopeId = `p0-old-${suffix}`; + const oldContract = await createContract(processId, oldEnvelopeId); + const activeContract = await createContract( + processId, + `p0-active-${suffix}`, + ); + await prisma.process.update({ + where: { id: processId }, + data: { active_contract_id: activeContract.id }, + }); + + const webhook = new DocuSignWebhookService(prisma as any, notifications); + await webhook.handleEnvelopeStatusChanged(completedPayload(oldEnvelopeId)); + + await expect( + prisma.contract.findUniqueOrThrow({ where: { id: oldContract.id } }), + ).resolves.toMatchObject({ + provider_status: ProviderStatus.COMPLETED, + status: ContractStatus.SIGNED, + }); + await expect( + prisma.process.findUniqueOrThrow({ where: { id: processId } }), + ).resolves.toMatchObject({ + status: ProcessStatus.DOCUMENTATION, + active_contract_id: activeContract.id, + }); + await expect( + prisma.processStatusHistory.count({ + where: { processId, status: ProcessStatus.COMPLETED }, + }), + ).resolves.toBe(0); + }); + + it('rejects a send DTO whose legal content differs from the approved preview', async () => { + const processId = await createProcess(ProcessStatus.PROCESSING_CONTRACT); + const envelopeId = `p0-preview-${suffix}`; + let previewFingerprint = ''; + const docusign = { + templateHasSellerRole: jest.fn().mockResolvedValue(true), + createEnvelopePreview: jest.fn().mockImplementation(async (params) => { + previewFingerprint = params.requestFingerprint; + params.onEnvelopeCreated?.(envelopeId); + return { + envelopeId, + previewUrl: 'https://docusign.example.test/preview', + expiresAt: '2099-01-01T00:00:00.000Z', + }; + }), + getEnvelopeProcessId: jest.fn().mockResolvedValue(processId), + getEnvelopeRequestFingerprint: jest + .fn() + .mockImplementation(async () => previewFingerprint), + getEnvelopeStatus: jest.fn().mockResolvedValue({ + envelopeId, + status: EnvelopeStatus.CREATED, + }), + sendDraftEnvelope: jest.fn().mockResolvedValue({ + envelopeId, + status: EnvelopeStatus.SENT, + }), + voidDraftEnvelope: jest.fn().mockResolvedValue(undefined), + } as any; + const platformCompany = { + findOne: jest.fn().mockResolvedValue({ default_commission_rate: 10 }), + } as any; + const contracts = new ContractsService( + prisma as any, + docusign, + notifications, + platformCompany, + ); + const approvedDto = { + operation_id: randomUUID(), + return_url: 'https://app.example.test/contracts/return', + process_id: processId, + template_id: 'template-p0', + seller_name: 'Approved Seller', + seller_email: 'seller@example.test', + buyer_name: 'P0 Client', + buyer_email: `p0-client-${suffix}@example.test`, + specialist_name: 'P0 Specialist', + specialist_email: `p0-specialist-${suffix}@example.test`, + vehicle_model: 'Approved Model', + vehicle_year: '2026', + vehicle_price: 100_000, + payment_seller_value: 90_000, + total_commission_rate: 10, + city: 'Sao Paulo', + description: 'Approved legal content', + } as any; + + const preview = await contracts.previewContract(approvedDto, adminId); + await expect( + contracts.sendContractAfterPreview( + preview.envelope_id, + { + ...approvedDto, + seller_name: 'Tampered Seller', + }, + adminId, + ), + ).rejects.toBeInstanceOf(ConflictException); + + expect(docusign.sendDraftEnvelope).not.toHaveBeenCalled(); + await expect( + prisma.contract.count({ where: { process_id: processId } }), + ).resolves.toBe(0); + }); +}); diff --git a/backend/src/features/contracts/contracts-lock.postgres.spec.ts b/backend/src/features/contracts/contracts-lock.postgres.spec.ts index 6ac2f06c..b431a1b4 100644 --- a/backend/src/features/contracts/contracts-lock.postgres.spec.ts +++ b/backend/src/features/contracts/contracts-lock.postgres.spec.ts @@ -269,6 +269,7 @@ describeWithPostgres('contract process lock — PostgreSQL concurrency', () => { }); const docusign = { getEnvelopeProcessId: jest.fn().mockResolvedValue(sendProcessId), + getEnvelopeRequestFingerprint: jest.fn(), getEnvelopeStatus: jest.fn().mockResolvedValue({ envelopeId: 'send-envelope', status: EnvelopeStatus.CREATED, @@ -292,6 +293,21 @@ describeWithPostgres('contract process lock — PostgreSQL concurrency', () => { platformCompany, ); const dto = contractDto(sendProcessId, suffix); + docusign.getEnvelopeRequestFingerprint.mockResolvedValue( + (serviceA as any).buildPreviewFingerprint( + dto, + null, + { + platformValue: 10000, + platformRate: 10, + officeValue: 0, + officeRate: 0, + specialistValue: 0, + specialistRate: 0, + }, + dto.template_id, + ).requestFingerprint, + ); const outcomesPromise = Promise.allSettled([ serviceA.sendContractAfterPreview('send-envelope', dto, specialistId), @@ -319,6 +335,7 @@ describeWithPostgres('contract process lock — PostgreSQL concurrency', () => { }); const docusign = { getEnvelopeProcessId: jest.fn().mockResolvedValue(ambiguousCommitProcessId), + getEnvelopeRequestFingerprint: jest.fn(), getEnvelopeStatus: jest.fn().mockResolvedValue({ envelopeId: 'ambiguous-envelope', status: EnvelopeStatus.SENT, @@ -342,6 +359,21 @@ describeWithPostgres('contract process lock — PostgreSQL concurrency', () => { platformCompany, ); const dto = contractDto(ambiguousCommitProcessId, suffix); + docusign.getEnvelopeRequestFingerprint.mockResolvedValue( + (firstAttempt as any).buildPreviewFingerprint( + dto, + null, + { + platformValue: 10000, + platformRate: 10, + officeValue: 0, + officeRate: 0, + specialistValue: 0, + specialistRate: 0, + }, + dto.template_id, + ).requestFingerprint, + ); const firstResult = firstAttempt.sendContractAfterPreview( 'ambiguous-envelope', diff --git a/backend/src/features/contracts/contracts.controller.spec.ts b/backend/src/features/contracts/contracts.controller.spec.ts new file mode 100644 index 00000000..f5a1553e --- /dev/null +++ b/backend/src/features/contracts/contracts.controller.spec.ts @@ -0,0 +1,26 @@ +import { UserRole } from '@prisma/client'; +import { ROLES_KEY } from 'src/shared/decorators/roles.decorator'; +import { ContractsController } from './contracts.controller'; + +describe('ContractsController route policy', () => { + it('reserva generate legado ao SPECIALIST e mantém preview/send para ADMIN', () => { + expect( + Reflect.getMetadata( + ROLES_KEY, + ContractsController.prototype.generateContract, + ), + ).toEqual([UserRole.SPECIALIST]); + expect( + Reflect.getMetadata( + ROLES_KEY, + ContractsController.prototype.previewContract, + ), + ).toEqual(expect.arrayContaining([UserRole.SPECIALIST, UserRole.ADMIN])); + expect( + Reflect.getMetadata( + ROLES_KEY, + ContractsController.prototype.sendContractAfterPreview, + ), + ).toEqual(expect.arrayContaining([UserRole.SPECIALIST, UserRole.ADMIN])); + }); +}); diff --git a/backend/src/features/contracts/contracts.controller.ts b/backend/src/features/contracts/contracts.controller.ts index c4f44082..e1eb8134 100644 --- a/backend/src/features/contracts/contracts.controller.ts +++ b/backend/src/features/contracts/contracts.controller.ts @@ -9,6 +9,8 @@ import { Logger, ParseUUIDPipe, UseGuards, + Query, + Optional, } from '@nestjs/common'; import { ContractsService } from './contracts.service'; import { DocuSignService } from 'src/providers/docusign/docusign.service'; @@ -26,6 +28,7 @@ import { Roles } from 'src/shared/decorators/roles.decorator'; import { UserRole } from '@prisma/client'; import { RateLimitGuard } from 'src/shared/guards/rate-limit.guard'; import { RateLimit } from 'src/shared/decorators/rate-limit.decorator'; +import { ActorContextService } from 'src/shared/actor-context/actor-context.service'; /** * Controller para gerenciar contratos via formulário. @@ -38,7 +41,8 @@ import { RateLimit } from 'src/shared/decorators/rate-limit.decorator'; * * Segurança: * - AuthGuard: Garante que apenas usuários autenticados podem acessar - * - preview/send/generate: apenas SPECIALIST e ADMIN, com rate limit + * - preview/send: SPECIALIST e ADMIN, com rate limit + * - generate legado: apenas SPECIALIST; ADMIN deve usar preview + send * * Fluxo (ativo): * 1. Frontend busca dados pré-preenchidos via GET /contracts/prefill/:processId @@ -53,8 +57,14 @@ export class ContractsController { constructor( private readonly contractsService: ContractsService, private readonly docuSignService: DocuSignService, + @Optional() private readonly actorContextService?: ActorContextService, ) {} + private async resolveContext(user: any, targetSpecialistId?: string) { + if (!this.actorContextService) return undefined; + return this.actorContextService.resolve(user, targetSpecialistId); + } + /** * GET /api/contracts/prefill/:processId * @@ -97,6 +107,7 @@ export class ContractsController { async prefillContract( @Param('processId', new ParseUUIDPipe({ version: '4' })) processId: string, @Request() req: RequestWithUser, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const { id: userId } = req.user; @@ -104,9 +115,11 @@ export class ContractsController { `Prefill contract requested by user ${userId} for process ${processId}`, ); + const context = await this.resolveContext(req.user, targetSpecialistId); const prefillData = await this.contractsService.prefillContract( processId, userId, + context, ); this.logger.debug(`Prefill data returned for process ${processId}`); @@ -203,12 +216,13 @@ export class ContractsController { * proteções. */ @Post('generate') - @Roles(UserRole.SPECIALIST, UserRole.ADMIN) + @Roles(UserRole.SPECIALIST) @UseGuards(RateLimitGuard) @RateLimit({ windowMs: 60, max: 10 }) async generateContract( @Body() generateContractDto: GenerateContractDto, @Request() req: RequestWithUser, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const { id: userId } = req.user; @@ -217,9 +231,11 @@ export class ContractsController { ); this.logger.debug(`Process: ${generateContractDto.process_id}`); + const context = await this.resolveContext(req.user, targetSpecialistId); const contract = await this.contractsService.generateContract( generateContractDto, userId, + context, ); this.logger.log( @@ -281,6 +297,7 @@ export class ContractsController { async previewContract( @Body() previewContractDto: PreviewContractDto, @Request() req: RequestWithUser, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const { id: userId } = req.user; @@ -289,9 +306,11 @@ export class ContractsController { ); this.logger.debug(`Process: ${previewContractDto.process_id}`); + const context = await this.resolveContext(req.user, targetSpecialistId); const preview = await this.contractsService.previewContract( previewContractDto, userId, + context, ); this.logger.log( @@ -355,6 +374,7 @@ export class ContractsController { @Param('envelopeId') envelopeId: string, @Body() previewContractDto: PreviewContractDto, @Request() req: RequestWithUser, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const { id: userId } = req.user; @@ -365,10 +385,12 @@ export class ContractsController { `EnvelopeID: ${envelopeId}, Process: ${previewContractDto.process_id}`, ); + const context = await this.resolveContext(req.user, targetSpecialistId); const result = await this.contractsService.sendContractAfterPreview( envelopeId, previewContractDto, userId, + context, ); this.logger.log( @@ -400,17 +422,20 @@ export class ContractsController { @Param('envelopeId') envelopeId: string, @Body('process_id', new ParseUUIDPipe({ version: '4' })) processId: string, @Request() req: RequestWithUser, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const { id: userId } = req.user; this.logger.log(`Cancelando preview para usuário ${userId}`); this.logger.debug(`EnvelopeID: ${envelopeId}`); + const context = await this.resolveContext(req.user, targetSpecialistId); await this.contractsService.cancelPreview( envelopeId, processId, userId, `Cancelado pelo usuário ${userId}`, + context, ); this.logger.log(`Preview cancelado com sucesso. EnvelopeID: ${envelopeId}`); diff --git a/backend/src/features/contracts/contracts.service.spec.ts b/backend/src/features/contracts/contracts.service.spec.ts index 2786e184..2bb7e39c 100644 --- a/backend/src/features/contracts/contracts.service.spec.ts +++ b/backend/src/features/contracts/contracts.service.spec.ts @@ -82,7 +82,7 @@ function processFixture(overrides: Record = {}) { id: 'client-1', name: 'Cliente', surname: 'Teste', - email: 'cliente@example.com', + email: 'buyer@example.test', cpf: null, rg: null, address: null, @@ -93,7 +93,7 @@ function processFixture(overrides: Record = {}) { id: 'specialist-1', name: 'Especialista', surname: 'Teste', - email: 'especialista@example.com', + email: 'specialist@example.test', cpf: null, company_id: null, commission_rate: 0, @@ -745,6 +745,14 @@ describe('ContractsService — locked transaction and compensation', () => { describe('ContractsService — send after preview integrity', () => { function makeSendHarness(processOverrides: Record = {}) { const process = processFixture(processOverrides); + const commission = { + platformValue: 1000, + platformRate: 1, + officeValue: 0, + officeRate: 0, + specialistValue: 9000, + specialistRate: 9, + }; const tx = { $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), process: { @@ -778,6 +786,8 @@ describe('ContractsService — send after preview integrity', () => { }); const docusign = { getEnvelopeProcessId: jest.fn().mockResolvedValue('process-1'), + getEnvelopeRequestFingerprint: jest.fn(), + hasSellerRecipient: jest.fn().mockResolvedValue(true), getEnvelopeStatus: jest.fn().mockResolvedValue({ envelopeId: 'envelope-1', status: EnvelopeStatus.CREATED, @@ -796,14 +806,9 @@ describe('ContractsService — send after preview integrity', () => { } as any, mkPlatformCompanyService(10), ); - jest.spyOn(service as any, 'resolveCommissionFromTotal').mockResolvedValue({ - platformValue: 1000, - platformRate: 1, - officeValue: 0, - officeRate: 0, - specialistValue: 9000, - specialistRate: 9, - }); + jest + .spyOn(service as any, 'resolveCommissionFromTotal') + .mockResolvedValue(commission); const dto = { operation_id: '11111111-1111-4111-8111-111111111111', process_id: 'process-1', @@ -822,9 +827,48 @@ describe('ContractsService — send after preview integrity', () => { specialist_email: 'specialist@example.test', city: 'Sao Paulo', } as any; + docusign.getEnvelopeRequestFingerprint.mockImplementation(async () => + (service as any).buildPreviewFingerprint( + dto, + process.product_type, + commission, + dto.template_id, + ).requestFingerprint, + ); return { service, docusign, tx, dto }; } + it.each([ + { seller_name: '', seller_email: '' }, + { seller_name: 'Seller', seller_email: '' }, + { seller_name: '', seller_email: 'seller@example.test' }, + ])('usa o especialista como vendedor no modelo com Seller (%j)', async (seller) => { + const { service, docusign, tx, dto } = makeSendHarness(); + Object.assign(dto, seller); + + await service.sendContractAfterPreview('envelope-1', dto, 'specialist-1'); + expect(docusign.sendDraftEnvelope).toHaveBeenCalledWith('envelope-1'); + expect(dto.seller_name).toBe('Especialista Teste'); + expect(dto.seller_email).toBe('specialist@example.test'); + expect(tx.contract.create).toHaveBeenCalledWith(expect.objectContaining({ + data: expect.objectContaining({ seller_name: 'Especialista Teste' }), + })); + }); + + it('envia sem vendedor quando o rascunho não tem papel Seller', async () => { + const { service, docusign, tx, dto } = makeSendHarness(); + dto.seller_name = ''; + dto.seller_email = ''; + docusign.hasSellerRecipient.mockResolvedValue(false); + + await service.sendContractAfterPreview('envelope-1', dto, 'specialist-1'); + + expect(docusign.sendDraftEnvelope).toHaveBeenCalledWith('envelope-1'); + expect(tx.contract.create).toHaveBeenCalledWith(expect.objectContaining({ + data: expect.objectContaining({ seller_name: '' }), + })); + }); + it('voids a stale draft only after authorization, binding and provider inspection', async () => { const { service, docusign, tx, dto } = makeSendHarness({ status: ProcessStatus.COMPLETED, @@ -1018,6 +1062,61 @@ describe('ContractsService — send after preview integrity', () => { }); describe('ContractsService — provider operation id', () => { + it('canonicalizes buyer and an omitted specialist from the process', () => { + const service = mkSvc(mkPrisma(), mkPlatformCompanyService(10)); + const dto = { + buyer_name: 'Untrusted buyer label', + buyer_email: 'buyer@example.test', + seller_email: 'seller@example.test', + vehicle_price: 100000, + } as any; + + (service as any).assertContractPartiesAndPrice(dto, processFixture()); + + expect(dto).toMatchObject({ + buyer_name: 'Cliente Teste', + specialist_name: 'Especialista Teste', + specialist_email: 'specialist@example.test', + }); + }); + + it.each([ + [ + 'comprador diferente do cliente', + { buyer_email: 'intruder@example.test' }, + ForbiddenException, + ], + [ + 'especialista signatário diferente do responsável', + { specialist_email: 'other-specialist@example.test' }, + ForbiddenException, + ], + [ + 'vendedor igual ao especialista', + { seller_email: 'specialist@example.test' }, + BadRequestException, + ], + [ + 'preço diferente da negociação', + { vehicle_price: 99999 }, + BadRequestException, + ], + ])('bloqueia %s', (_label, override, exceptionType) => { + const service = mkSvc(mkPrisma(), mkPlatformCompanyService(10)); + const dto = { + buyer_email: 'buyer@example.test', + specialist_email: 'specialist@example.test', + seller_name: 'Seller', + seller_email: 'seller@example.test', + vehicle_price: 100000, + ...override, + } as any; + + expect(() => + (service as any).assertContractPartiesAndPrice(dto, processFixture()), + ).toThrow(exceptionType); + }); + it('passes the same public operation_id through to DocuSign preview retries', async () => { const process = processFixture(); const tx = { @@ -1033,6 +1132,7 @@ describe('ContractsService — provider operation id', () => { company: { findUnique: jest.fn() }, }; const docusign = { + templateHasSellerRole: jest.fn().mockResolvedValue(true), createEnvelopePreview: jest.fn().mockResolvedValue({ envelopeId: 'envelope-1', previewUrl: 'https://demo.docusign.net/preview', @@ -1059,24 +1159,82 @@ describe('ContractsService — provider operation id', () => { operation_id: '11111111-1111-4111-8111-111111111111', process_id: 'process-1', template_id: 'template-1', - seller_name: 'Seller', - seller_email: 'seller@example.test', + seller_name: '', + seller_email: '', buyer_name: 'Buyer', buyer_email: 'buyer@example.test', + specialist_email: 'specialist@example.test', + vehicle_price: 100000, total_commission_rate: 10, city: 'Sao Paulo', return_url: 'https://app.example.test/return', } as any; - await service.previewContract(dto, 'specialist-1'); - await service.previewContract(dto, 'specialist-1'); + await service.previewContract({ ...dto }, 'specialist-1'); + await service.previewContract({ ...dto }, 'specialist-1'); expect(docusign.createEnvelopePreview).toHaveBeenCalledTimes(2); for (const [params] of docusign.createEnvelopePreview.mock.calls) { expect(params.transactionId).toBe(dto.operation_id); + expect(params.sellerEmail).toBe('specialist@example.test'); + expect(params.sellerName).toBe('Especialista Teste'); } }); + it('does not mix the specialist signature with another seller identity', () => { + const service = mkSvc(mkPrisma(), mkPlatformCompanyService(10)); + const dto = { + seller_name: '', + seller_email: '', + seller_cpf: '10987654321', + specialist_name: 'Especialista Teste', + specialist_email: 'specialist@example.test', + } as any; + + expect(() => (service as any).assignSpecialistToSellerRole(dto)).toThrow( + BadRequestException, + ); + expect(dto.seller_name).toBe(''); + expect(dto.seller_cpf).toBe('10987654321'); + }); + + it('accepts a partial seller email for the authorized specialist fallback', () => { + const service = mkSvc(mkPrisma(), mkPlatformCompanyService(10)); + const dto = { + buyer_email: 'buyer@example.test', + seller_name: '', + seller_email: 'specialist@example.test', + vehicle_price: 100000, + } as any; + + expect(() => (service as any).assertContractPartiesAndPrice(dto, processFixture())) + .not.toThrow(); + expect((service as any).assignSpecialistToSellerRole(dto)).toBe(true); + expect(dto.seller_name).toBe('Especialista Teste'); + }); + + it('keeps unrelated seller document and bank fields empty in a fallback', () => { + const service = mkSvc(mkPrisma(), mkPlatformCompanyService(10)); + const dto = { + seller_name: '', + seller_email: '', + specialist_name: 'Especialista Teste', + specialist_email: 'specialist@example.test', + specialist_document: '12345678000199', + specialist_bank: 'Banco Teste', + specialist_agency: '1234', + specialist_checking_account: '5678', + } as any; + + expect((service as any).assignSpecialistToSellerRole(dto)).toBe(true); + expect(dto).toMatchObject({ + seller_name: 'Especialista Teste', + seller_email: 'specialist@example.test', + }); + expect(dto.seller_cpf).toBeUndefined(); + expect(dto.seller_bank).toBeUndefined(); + }); + it('derives the recovery fingerprint from description and authoritative commission split', async () => { const process = processFixture(); const tx = { @@ -1092,6 +1250,7 @@ describe('ContractsService — provider operation id', () => { company: { findUnique: jest.fn() }, }; const docusign = { + templateHasSellerRole: jest.fn().mockResolvedValue(true), createEnvelopePreview: jest.fn().mockResolvedValue({ envelopeId: 'envelope-1', previewUrl: 'https://demo.docusign.net/preview', @@ -1133,6 +1292,8 @@ describe('ContractsService — provider operation id', () => { seller_email: 'seller@example.test', buyer_name: 'Buyer', buyer_email: 'buyer@example.test', + specialist_email: 'specialist@example.test', + vehicle_price: 100000, total_commission_rate: 10, city: 'Sao Paulo', description: 'Intent A', @@ -1177,6 +1338,12 @@ describe('ContractsService — provider operation id', () => { }; let createdRequest: any = null; const providerClient = { + getTemplateRecipients: jest.fn().mockResolvedValue({ + signers: [{ roleName: 'Buyer' }, { roleName: 'Seller' }], + }), + getEnvelopeRecipients: jest.fn().mockResolvedValue({ + signers: [{ roleName: 'Buyer' }, { roleName: 'Seller' }], + }), findEnvelopesByTransactionId: jest.fn().mockImplementation(async () => createdRequest ? [{ envelopeId: 'envelope-1', status: EnvelopeStatus.CREATED }] @@ -1233,6 +1400,8 @@ describe('ContractsService — provider operation id', () => { seller_email: 'seller@example.test', buyer_name: 'Buyer', buyer_email: 'buyer@example.test', + specialist_email: 'specialist@example.test', + vehicle_price: 100000, total_commission_rate: 10, city: 'Sao Paulo', description: 'Same legal description', diff --git a/backend/src/features/contracts/contracts.service.ts b/backend/src/features/contracts/contracts.service.ts index a6d18b6b..da735158 100644 --- a/backend/src/features/contracts/contracts.service.ts +++ b/backend/src/features/contracts/contracts.service.ts @@ -7,6 +7,7 @@ import { InternalServerErrorException, Logger, NotFoundException, + Optional, } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { GenerateContractDto } from './dto/generate-contract.dto'; @@ -48,6 +49,8 @@ import { EnvelopeEffectState, } from 'src/providers/docusign/envelope-effect.error'; import { createHash, randomUUID } from 'node:crypto'; +import { ActorContext } from 'src/shared/actor-context/actor-context.service'; +import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service'; const CONTRACT_PREPARATION_STATUSES: ProcessStatus[] = [ ProcessStatus.PROCESSING_CONTRACT, @@ -65,6 +68,15 @@ interface ExternalEnvelopeEffect { providerStatus?: EnvelopeStatus; } +type ResolvedContractCommission = { + platformRate: number; + officeRate: number; + specialistRate: number; + platformValue: number; + officeValue: number; + specialistValue: number; +}; + export interface ContractDocumentFields { seller_cpf?: string; seller_rg?: string; @@ -129,6 +141,8 @@ export class ContractsService { private readonly docuSignService: DocuSignService, private readonly notificationService: NotificationService, private readonly platformCompanyService: PlatformCompanyService, + @Optional() + private readonly delegatedAudit?: DelegatedActionAuditService, ) {} private contractIntentionFingerprint(input: { @@ -161,16 +175,138 @@ export class ContractsService { .digest('hex'); } + private buildPreviewGenerateDto( + dto: PreviewContractDto, + commission: ResolvedContractCommission, + ): GenerateContractDto { + return { + operation_id: dto.operation_id, + process_id: dto.process_id, + total_commission_rate: dto.total_commission_rate, + seller_name: dto.seller_name ?? '', + seller_email: dto.seller_email ?? '', + seller_cpf: dto.seller_cpf, + seller_rg: dto.seller_rg, + seller_address: dto.seller_address ?? '', + seller_cep: dto.seller_cep, + seller_bank: dto.seller_bank ?? '', + seller_agency: dto.seller_agency ?? '', + seller_checking_account: dto.seller_checking_account ?? '', + buyer_name: dto.buyer_name, + buyer_email: dto.buyer_email, + buyer_cpf: dto.buyer_cpf, + buyer_rg: dto.buyer_rg, + buyer_address: dto.buyer_address ?? '', + buyer_cep: dto.buyer_cep, + vehicle_model: dto.vehicle_model ?? '', + vehicle_year: dto.vehicle_year ?? '', + vehicle_registration_id: dto.vehicle_registration_id ?? '', + vehicle_serial_number: dto.vehicle_serial_number ?? '', + vehicle_technical_info: dto.vehicle_technical_info, + vehicle_price: dto.vehicle_price, + payment_seller_value: dto.payment_seller_value, + platform_value: commission.platformValue, + platform_percentage: commission.platformRate, + platform_name: dto.platform_name, + platform_cnpj: dto.platform_cnpj, + platform_bank: dto.platform_bank, + platform_agency: dto.platform_agency, + platform_checking_account: dto.platform_checking_account, + office_value: commission.officeValue, + office_name: dto.office_name, + office_cnpj: dto.office_cnpj, + office_bank: dto.office_bank, + office_agency: dto.office_agency, + office_checking_account: dto.office_checking_account, + specialist_value: commission.specialistValue, + specialist_name: dto.specialist_name, + specialist_email: dto.specialist_email, + specialist_document: dto.specialist_document, + specialist_bank: dto.specialist_bank, + specialist_agency: dto.specialist_agency, + specialist_checking_account: dto.specialist_checking_account, + testimonial1_cpf: dto.testimonial1_cpf, + testimonial1_email: dto.testimonial1_email, + testimonial2_cpf: dto.testimonial2_cpf, + testimonial2_email: dto.testimonial2_email, + city: dto.city ?? '', + description: dto.description, + }; + } + + private normalizePreviewSeller(dto: PreviewContractDto): void { + const sellerName = dto.seller_name?.trim() ?? ''; + const sellerEmail = dto.seller_email?.trim() ?? ''; + dto.seller_name = sellerName; + dto.seller_email = sellerEmail; + } + + private assignSpecialistToSellerRole(dto: PreviewContractDto): boolean { + if (dto.seller_name && dto.seller_email) return false; + if (!dto.specialist_name || !dto.specialist_email) { + throw new BadRequestException( + 'Não foi possível identificar o especialista para o papel de vendedor.', + ); + } + const sellerDetails = [ + dto.seller_cpf, + dto.seller_rg, + dto.seller_address, + dto.seller_cep, + dto.seller_bank, + dto.seller_agency, + dto.seller_checking_account, + ]; + if (sellerDetails.some((value) => value?.trim())) { + throw new BadRequestException( + 'Para o especialista assinar como vendedor, limpe os dados pessoais e bancários do vendedor. Para manter esses dados, informe nome e e-mail do vendedor.', + ); + } + // Nunca misturar nome de uma pessoa com e-mail de outra. + dto.seller_name = dto.specialist_name; + dto.seller_email = dto.specialist_email; + return true; + } + + private buildPreviewFingerprint( + dto: PreviewContractDto, + productType: ProductType | null, + commission: ResolvedContractCommission, + templateId: string, + ): { formFields: Record; requestFingerprint: string } { + const generateDto = this.buildPreviewGenerateDto(dto, commission); + const formFields = this.buildFormFields(generateDto, productType); + return { + formFields, + requestFingerprint: this.contractIntentionFingerprint({ + processId: dto.process_id, + templateId, + contract: { + ...(dto as unknown as Record), + ...(generateDto as unknown as Record), + }, + commission, + formFields, + }), + }; + } + private async getAuthorizedContractProcess( processId: string, userId: string, client: PrismaService | Prisma.TransactionClient = this.prismaService, + context?: ActorContext, ): Promise<{ id: string; status: ProcessStatus; + removed_at: Date | null; active_contract_id: string | null; product_type: ProductType | null; specialist_id: string; + negotiation_product_value: Prisma.Decimal | null; + client: { email: string; name: string; surname: string }; + specialist: { email: string; name: string; surname: string }; + accepted_proposal: { proposed_value: Prisma.Decimal } | null; }> { const [processRecord, requester] = await Promise.all([ client.process.findUnique({ @@ -178,9 +314,16 @@ export class ContractsService { select: { id: true, status: true, + removed_at: true, active_contract_id: true, product_type: true, specialist_id: true, + negotiation_product_value: true, + client: { select: { email: true, name: true, surname: true } }, + specialist: { + select: { email: true, name: true, surname: true }, + }, + accepted_proposal: { select: { proposed_value: true } }, }, }), client.user.findUnique({ @@ -189,7 +332,8 @@ export class ContractsService { }), ]); - if (!processRecord) throw new ProcessNotFoundException(processId); + if (!processRecord || processRecord.removed_at) + throw new ProcessNotFoundException(processId); if ( !requester || (requester.role !== UserRole.ADMIN && @@ -200,9 +344,90 @@ export class ContractsService { 'Você não pode acessar contratos deste processo.', ); } + if (context && processRecord.specialist_id !== context.specialistId) { + throw new ForbiddenException( + 'O contrato não pertence ao especialista representado.', + ); + } return processRecord; } + private assertContractPartiesAndPrice( + dto: GenerateContractDto | PreviewContractDto, + processRecord: { + client: { email: string; name?: string; surname?: string }; + specialist: { email: string; name?: string; surname?: string }; + accepted_proposal: { proposed_value: Prisma.Decimal } | null; + negotiation_product_value: Prisma.Decimal | null; + }, + ): void { + // Alguns doubles unitários antigos retornam somente os campos que eram + // selecionados antes desta regra. No Prisma real, estes campos fazem parte + // do select acima; a guarda mantém os doubles legados sem enfraquecer a + // validação do caminho de produção. + if ( + (processRecord as any).client?.email === undefined || + (processRecord as any).specialist?.email === undefined || + ((processRecord as any).accepted_proposal === undefined && + (processRecord as any).negotiation_product_value === undefined) + ) { + return; + } + const normalizeEmail = (value?: string) => + value?.trim().toLowerCase() ?? ''; + if ( + normalizeEmail(dto.buyer_email) !== + normalizeEmail(processRecord.client.email) + ) { + throw new ForbiddenException( + 'O comprador deve ser o cliente vinculado ao processo.', + ); + } + if (dto.specialist_email && + normalizeEmail(dto.specialist_email) !== + normalizeEmail(processRecord.specialist.email)) { + throw new ForbiddenException( + 'O especialista signatário deve ser o responsável pelo processo.', + ); + } + if ( + dto.seller_name?.trim() && + normalizeEmail(dto.seller_email) === + normalizeEmail(processRecord.specialist.email) + ) { + throw new BadRequestException( + 'Vendedor e especialista são partes distintas do contrato.', + ); + } + + // Buyer e Specialist são partes canônicas do processo, não campos + // livres do formulário. O e-mail do buyer continua sendo comparado para + // rejeitar troca de parte; os nomes e o especialista opcional são sempre + // preenchidos com a fonte autoritativa antes do fingerprint/DocuSign. + dto.buyer_name = [processRecord.client.name, processRecord.client.surname] + .filter(Boolean) + .join(' '); + dto.specialist_email = processRecord.specialist.email; + dto.specialist_name = [ + processRecord.specialist.name, + processRecord.specialist.surname, + ] + .filter(Boolean) + .join(' '); + const agreedPrice = + processRecord.accepted_proposal?.proposed_value ?? + processRecord.negotiation_product_value; + if ( + !agreedPrice || + dto.vehicle_price == null || + !new Prisma.Decimal(dto.vehicle_price).equals(agreedPrice) + ) { + throw new BadRequestException( + 'O preço do contrato deve coincidir com o acordo da negociação.', + ); + } + } + private async assertEnvelopeBelongsToProcess( envelopeId: string, processId: string, @@ -431,13 +656,15 @@ export class ContractsService { contractId: string, method: 'generateContract' | 'sendContractAfterPreview', ): void { + const sellerEmail = dto.seller_email; + const sellerName = dto.seller_name; setImmediate(() => { this.notificationService .sendContractGeneratedEmail({ buyerEmail: dto.buyer_email, buyerName: dto.buyer_name, - sellerEmail: dto.seller_email, - sellerName: dto.seller_name, + sellerEmail, + sellerName, contractId, vehicleDetails: `${dto.vehicle_model} ${dto.vehicle_year}`, processId: dto.process_id, @@ -465,10 +692,16 @@ export class ContractsService { async prefillContract( processId: string, userId: string, + context?: ActorContext, ): Promise { this.logger.debug(`Prefill contract data for process: ${processId}`); - await this.getAuthorizedContractProcess(processId, userId); + await this.getAuthorizedContractProcess( + processId, + userId, + this.prismaService, + context, + ); // Buscar processo com todas as relações necessárias const processData = await this.prismaService.process.findUnique({ @@ -487,7 +720,7 @@ export class ContractsService { }, }); - if (!processData) { + if (!processData || processData.removed_at) { this.logger.warn(`Process ${processId} not found for prefill`); throw new ProcessNotFoundException(processId); } @@ -848,7 +1081,7 @@ export class ContractsService { }, }); - if (!process) { + if (!process || process.removed_at) { throw new ProcessNotFoundException(processId); } @@ -934,6 +1167,7 @@ export class ContractsService { async generateContract( dto: GenerateContractDto, userId: string, + context?: ActorContext, ): Promise { let externalEffect: ExternalEnvelopeEffect | null = null; let transactionCallbackCompleted = false; @@ -948,6 +1182,7 @@ export class ContractsService { (envelopeId, state) => { externalEffect = { envelopeId, state }; }, + context, ); transactionCallbackCompleted = true; return contract; @@ -1023,6 +1258,7 @@ export class ContractsService { state: EnvelopeEffectState, providerStatus?: EnvelopeStatus, ) => void, + context?: ActorContext, ): Promise { try { this.logger.log(`=== INICIANDO GERAÇÃO DE CONTRATO ===`); @@ -1037,7 +1273,9 @@ export class ContractsService { dto.process_id, userId, tx, + context, ); + this.assertContractPartiesAndPrice(dto, processRecord); if (!processRecord) { this.logger.warn(`Processo ${dto.process_id} não encontrado`); @@ -1208,6 +1446,7 @@ export class ContractsService { sentAt: new Date().toISOString(), originalStatus: envelopeResponse.status, templateId: templateId, + sellerEmail: dto.seller_email || null, } as any, // Dados do vendedor @@ -1336,6 +1575,22 @@ export class ContractsService { }); } + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'CONTRACT_GENERATE', + resourceType: 'CONTRACT', + resourceId: contract.id, + metadata: { + processId: dto.process_id, + envelopeId: envelopeResponse.envelopeId, + }, + }, + tx, + ); + } + this.logger.log( `✓ Contrato definido como ativo no processo ${dto.process_id}`, ); @@ -1533,13 +1788,20 @@ export class ContractsService { async previewContract( dto: PreviewContractDto, userId: string, + context?: ActorContext, ): Promise { let externalEffect: ExternalEnvelopeEffect | null = null; try { return await this.withContractProcessLock(dto.process_id, (tx) => - this.previewContractLocked(dto, userId, tx, (envelopeId) => { - externalEffect = { envelopeId, state: 'DRAFT_CONFIRMED' }; - }), + this.previewContractLocked( + dto, + userId, + tx, + (envelopeId) => { + externalEffect = { envelopeId, state: 'DRAFT_CONFIRMED' }; + }, + context, + ), ); } catch (error) { if (error instanceof EnvelopeEffectError) { @@ -1587,6 +1849,7 @@ export class ContractsService { userId: string, tx: Prisma.TransactionClient, registerExternalEnvelope: (envelopeId: string) => void, + context?: ActorContext, ): Promise { try { this.logger.log(`=== INICIANDO PREVIEW DE CONTRATO ===`); @@ -1595,13 +1858,16 @@ export class ContractsService { // ===== ETAPA 1: VALIDAÇÕES DE INTEGRIDADE ===== this.logger.log('Preview Etapa 1: Validando integridade de negócio...'); + this.normalizePreviewSeller(dto); // 1.1 Verificar se processo existe const processRecord = await this.getAuthorizedContractProcess( dto.process_id, userId, tx, + context, ); + this.assertContractPartiesAndPrice(dto, processRecord); if (!processRecord) { this.logger.warn(`Processo ${dto.process_id} não encontrado`); @@ -1646,70 +1912,6 @@ export class ContractsService { // ===== ETAPA 2: FORMATAR DADOS PARA DOCUSIGN ===== this.logger.log('Preview Etapa 2: Formatando dados para DocuSign...'); - // Reutilizar buildFormFields criando DTO compatível - const generateDto: GenerateContractDto = { - operation_id: dto.operation_id, - process_id: dto.process_id, - total_commission_rate: dto.total_commission_rate, - seller_name: dto.seller_name, - seller_email: dto.seller_email, - seller_cpf: dto.seller_cpf, - seller_rg: dto.seller_rg, - seller_address: dto.seller_address ?? '', - seller_cep: dto.seller_cep, - seller_bank: dto.seller_bank ?? '', - seller_agency: dto.seller_agency ?? '', - seller_checking_account: dto.seller_checking_account ?? '', - buyer_name: dto.buyer_name, - buyer_email: dto.buyer_email, - buyer_cpf: dto.buyer_cpf, - buyer_rg: dto.buyer_rg, - buyer_address: dto.buyer_address ?? '', - buyer_cep: dto.buyer_cep, - vehicle_model: dto.vehicle_model ?? '', - vehicle_year: dto.vehicle_year ?? '', - vehicle_registration_id: dto.vehicle_registration_id ?? '', - vehicle_serial_number: dto.vehicle_serial_number ?? '', - vehicle_technical_info: dto.vehicle_technical_info, - vehicle_price: dto.vehicle_price, - payment_seller_value: dto.payment_seller_value, - platform_value: commission.platformValue, - platform_percentage: commission.platformRate, - platform_name: dto.platform_name, - platform_cnpj: dto.platform_cnpj, - platform_bank: dto.platform_bank, - platform_agency: dto.platform_agency, - platform_checking_account: dto.platform_checking_account, - office_value: commission.officeValue, - office_name: dto.office_name, - office_cnpj: dto.office_cnpj, - office_bank: dto.office_bank, - office_agency: dto.office_agency, - office_checking_account: dto.office_checking_account, - specialist_value: commission.specialistValue, - specialist_name: dto.specialist_name, - specialist_email: dto.specialist_email, - specialist_document: dto.specialist_document, - specialist_bank: dto.specialist_bank, - specialist_agency: dto.specialist_agency, - specialist_checking_account: dto.specialist_checking_account, - testimonial1_cpf: dto.testimonial1_cpf, - testimonial1_email: dto.testimonial1_email, - testimonial2_cpf: dto.testimonial2_cpf, - testimonial2_email: dto.testimonial2_email, - city: dto.city ?? '', - description: dto.description, - }; - - const formFields = this.buildFormFields( - generateDto, - processRecord.product_type, - ); - - this.logger.debug( - `Form fields preparados: ${Object.keys(formFields).length} campos`, - ); - // ===== ETAPA 3: CRIAR PREVIEW NO DOCUSIGN ===== this.logger.log('Preview Etapa 3: Criando preview no DocuSign...'); @@ -1721,24 +1923,31 @@ export class ContractsService { ); } - const requestFingerprint = this.contractIntentionFingerprint({ - processId: dto.process_id, - templateId, - contract: { - ...(dto as unknown as Record), - ...(generateDto as unknown as Record), - }, - commission, - formFields, - }); + const templateHasSellerRole = + await this.docuSignService.templateHasSellerRole(templateId); + const sellerAssignedToSpecialist = templateHasSellerRole && + this.assignSpecialistToSellerRole(dto); + + const { formFields, requestFingerprint } = + this.buildPreviewFingerprint( + dto, + processRecord.product_type, + commission, + templateId, + ); + + this.logger.debug( + `Form fields preparados: ${Object.keys(formFields).length} campos`, + ); const previewResponse = await this.docuSignService.createEnvelopePreview({ transactionId: dto.operation_id, templateId, + templateHasSellerRole, buyerEmail: dto.buyer_email, buyerName: dto.buyer_name, - sellerEmail: dto.seller_email, - sellerName: dto.seller_name, + sellerEmail: dto.seller_email ?? '', + sellerName: dto.seller_name ?? '', specialistEmail: dto.specialist_email, specialistName: dto.specialist_name, formFields, @@ -1755,6 +1964,19 @@ export class ContractsService { this.logger.log( `✓ Preview criado (EnvelopeID: ${previewResponse.envelopeId})`, ); + + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'CONTRACT_PREVIEW', + resourceType: 'DOCUSIGN_ENVELOPE', + resourceId: previewResponse.envelopeId, + metadata: { processId: dto.process_id }, + }, + tx, + ); + } this.logger.log(`=== PREVIEW CONCLUÍDO COM SUCESSO ===`); return { @@ -1762,6 +1984,8 @@ export class ContractsService { envelope_id: previewResponse.envelopeId, expires_at: previewResponse.expiresAt, process_id: dto.process_id, + seller_signature_required: previewResponse.sellerSignatureRequired, + seller_assigned_to_specialist: sellerAssignedToSpecialist, }; } catch (error) { if ( @@ -1811,6 +2035,7 @@ export class ContractsService { envelopeId: string, dto: PreviewContractDto, userId: string, + context?: ActorContext, ): Promise { let externalEffect: ExternalEnvelopeEffect | null = null; let transactionCallbackCompleted = false; @@ -1826,6 +2051,7 @@ export class ContractsService { (state) => { externalEffect = { envelopeId, state }; }, + context, ); transactionCallbackCompleted = true; return contract; @@ -1883,6 +2109,7 @@ export class ContractsService { state: EnvelopeEffectState, providerStatus?: EnvelopeStatus, ) => void, + context?: ActorContext, ): Promise { try { this.logger.log(`=== ENVIANDO CONTRATO APÓS PREVIEW ===`); @@ -1892,12 +2119,20 @@ export class ContractsService { // ===== ETAPA 1: RE-VALIDAR INTEGRIDADE ===== // (usuário pode ter aguardado muito tempo após preview) + this.normalizePreviewSeller(dto); const processRecord = await this.getAuthorizedContractProcess( dto.process_id, userId, tx, + context, ); + this.assertContractPartiesAndPrice(dto, processRecord); await this.assertEnvelopeBelongsToProcess(envelopeId, dto.process_id); + if (!dto.seller_name || !dto.seller_email) { + if (await this.docuSignService.hasSellerRecipient(envelopeId)) { + this.assignSpecialistToSellerRole(dto); + } + } let previewEnvelope: Awaited< ReturnType @@ -2020,6 +2255,39 @@ export class ContractsService { tx, ); + const templateId = + dto.template_id || globalThis.process.env.DOCUSIGN_TEMPLATE_ID; + if (!templateId) { + throw new InternalServerErrorException( + 'Nenhum template informado e DOCUSIGN_TEMPLATE_ID não configurado', + ); + } + const { requestFingerprint } = this.buildPreviewFingerprint( + dto, + processRecord.product_type, + commission, + templateId, + ); + const approvedFingerprint = + await this.docuSignService.getEnvelopeRequestFingerprint(envelopeId); + if ( + !approvedFingerprint || + approvedFingerprint !== requestFingerprint + ) { + throw new ConflictException({ + success: false, + error: { + code: 'CONTRACT_PREVIEW_MISMATCH', + message: + 'Os dados do contrato mudaram após o preview. Gere e aprove um novo preview antes de enviar.', + details: { + process_id: dto.process_id, + envelope_id: envelopeId, + }, + }, + }); + } + // ===== ETAPA 2: ENVIAR ENVELOPE NO DOCUSIGN ===== this.logger.log('Enviando envelope para DocuSign...'); @@ -2032,9 +2300,6 @@ export class ContractsService { // ===== ETAPA 3: SALVAR NO BANCO ===== this.logger.log('Salvando contrato no banco...'); - const templateId = - dto.template_id || globalThis.process.env.DOCUSIGN_TEMPLATE_ID || ''; - const cleanDocs = stripContractDocumentFields(dto); const contract = await tx.contract.create({ data: { @@ -2051,7 +2316,9 @@ export class ContractsService { sentAt: new Date().toISOString(), originalStatus: sendResponse.status, templateId: templateId, + sellerEmail: dto.seller_email || null, previewUsed: true, + requestFingerprint, } as any, // Dados do vendedor @@ -2179,6 +2446,19 @@ export class ContractsService { }); } + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'CONTRACT_SEND', + resourceType: 'CONTRACT', + resourceId: contract.id, + metadata: { processId: dto.process_id, envelopeId }, + }, + tx, + ); + } + const createdContract = contract; this.logger.log(`✓ Contrato criado: ${createdContract.id}`); this.logger.log(`=== ENVIO DE CONTRATO CONCLUÍDO ===`); @@ -2223,9 +2503,17 @@ export class ContractsService { processId: string, userId: string, reason: string, + context?: ActorContext, ): Promise { return this.withContractProcessLock(processId, (tx) => - this.cancelPreviewLocked(envelopeId, processId, userId, reason, tx), + this.cancelPreviewLocked( + envelopeId, + processId, + userId, + reason, + tx, + context, + ), ); } @@ -2235,12 +2523,14 @@ export class ContractsService { userId: string, reason: string, tx: Prisma.TransactionClient, + context?: ActorContext, ): Promise { this.logger.log(`Cancelando preview: ${envelopeId}`); const processRecord = await this.getAuthorizedContractProcess( processId, userId, tx, + context, ); await this.assertEnvelopeBelongsToProcess(envelopeId, processId); @@ -2264,5 +2554,18 @@ export class ContractsService { throw new EnvelopeNotInDraftException(envelopeId, envelope.status); } await this.docuSignService.voidDraftEnvelope(envelopeId, reason); + + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'CONTRACT_PREVIEW_CANCEL', + resourceType: 'DOCUSIGN_ENVELOPE', + resourceId: envelopeId, + metadata: { processId, reason }, + }, + tx, + ); + } } } diff --git a/backend/src/features/contracts/dto/preview-contract-response.dto.ts b/backend/src/features/contracts/dto/preview-contract-response.dto.ts index ed00ec2b..c7f30d4c 100644 --- a/backend/src/features/contracts/dto/preview-contract-response.dto.ts +++ b/backend/src/features/contracts/dto/preview-contract-response.dto.ts @@ -31,6 +31,12 @@ export class PreviewContractResponseDto { * @example "550e8400-e29b-41d4-a716-446655440000" */ process_id: string; + + /** True quando o rascunho ainda possui um signatário Seller. */ + seller_signature_required: boolean; + + /** True quando o especialista ocupa o papel Seller deste rascunho. */ + seller_assigned_to_specialist: boolean; } /** diff --git a/backend/src/features/contracts/dto/preview-contract.dto.spec.ts b/backend/src/features/contracts/dto/preview-contract.dto.spec.ts index 0332f0f9..1eba2a7f 100644 --- a/backend/src/features/contracts/dto/preview-contract.dto.spec.ts +++ b/backend/src/features/contracts/dto/preview-contract.dto.spec.ts @@ -65,8 +65,6 @@ describe('PreviewContractDto — preenchimento flexível', () => { 'operation_id', 'return_url', 'process_id', - 'seller_name', - 'seller_email', 'buyer_name', 'buyer_email', 'total_commission_rate', @@ -78,6 +76,29 @@ describe('PreviewContractDto — preenchimento flexível', () => { expect(errs.some((e) => e.property === campo)).toBe(true); }); + it.each([ + {}, + { seller_name: '', seller_email: '' }, + { seller_name: 'Vendedor' }, + { seller_email: 'vendedor@example.com' }, + ])('aceita vendedor incompleto na prévia (%j)', async (seller) => { + const payload = { + ...minimoPreview, + seller_name: undefined, + seller_email: undefined, + ...seller, + }; + expect(await erros(PreviewContractDto, payload)).toHaveLength(0); + }); + + it('continua validando o e-mail preenchido', async () => { + const errs = await erros(PreviewContractDto, { + ...minimoPreview, + seller_email: 'inválido', + }); + expect(errs.some((e) => e.property === 'seller_email')).toBe(true); + }); + // Opcional não significa "aceita lixo": o tipo ainda é validado quando vem. it('valida o tipo dos campos opcionais quando preenchidos', async () => { const errs = await erros(PreviewContractDto, { diff --git a/backend/src/features/contracts/dto/preview-contract.dto.ts b/backend/src/features/contracts/dto/preview-contract.dto.ts index 45cfca90..47730bb5 100644 --- a/backend/src/features/contracts/dto/preview-contract.dto.ts +++ b/backend/src/features/contracts/dto/preview-contract.dto.ts @@ -9,7 +9,9 @@ import { Max, MaxLength, Min, + ValidateIf, } from 'class-validator'; +import { Transform } from 'class-transformer'; /** * DTO para pré-visualização de contrato via DocuSign Sender View @@ -30,9 +32,10 @@ import { * Continuam obrigatórios apenas os que quebram o fluxo se faltarem: * * - `return_url`, `process_id` — encanamento, não são conteúdo do contrato. - * - `seller_name`/`seller_email`, `buyer_name`/`buyer_email` — viram - * destinatários do envelope; o DocuSign recusa criar envelope sem eles, e - * `buyer_email` ainda é usado para localizar o usuário signatário. + * - `buyer_name`/`buyer_email` — viram destinatário do envelope; o DocuSign + * recusa criar envelope sem eles, e `buyer_email` localiza o signatário. + * - `seller_name` e `seller_email` são opcionais. Se o template exigir Seller + * e faltar um deles, o especialista do processo assume esse papel. * - `total_commission_rate` — base do cálculo de comissão. Sem ele o split * vira NaN e é persistido assim; um erro de validação é preferível a um * contrato com valores corrompidos. @@ -74,14 +77,16 @@ export class PreviewContractDto { // === VENDEDOR (SELLER) === + @Transform(({ value }) => typeof value === 'string' ? value.trim() : value) + @ValidateIf((_object, value) => value != null && value !== '') @IsString({ message: 'seller_name deve ser uma string' }) - @IsNotEmpty({ message: 'seller_name é obrigatório' }) @MaxLength(255, { message: 'seller_name deve ter no máximo 255 caracteres' }) - seller_name: string; + seller_name?: string; + @Transform(({ value }) => typeof value === 'string' ? value.trim() : value) + @ValidateIf((_object, value) => value != null && value !== '') @IsEmail({}, { message: 'seller_email deve ser um email válido' }) - @IsNotEmpty({ message: 'seller_email é obrigatório' }) - seller_email: string; + seller_email?: string; @IsString({ message: 'seller_cpf deve ser uma string' }) @IsOptional() diff --git a/backend/src/features/dashboard/dashboard.service.ts b/backend/src/features/dashboard/dashboard.service.ts index 644ccf11..ddc19d3d 100644 --- a/backend/src/features/dashboard/dashboard.service.ts +++ b/backend/src/features/dashboard/dashboard.service.ts @@ -35,7 +35,7 @@ export class DashboardService { ] = await Promise.all([ this.prisma.company.count(), this.prisma.process.count({ - where: { status: { in: ['SCHEDULING', 'NEGOTIATION'] } }, + where: { status: { in: ['SCHEDULING', 'NEGOTIATION'] }, removed_at: null }, }), this.prisma.user.count({ where: { role: 'CUSTOMER' } }), this.prisma.user.count({ where: { role: 'SPECIALIST' } }), @@ -148,16 +148,17 @@ export class DashboardService { where: { specialist_id: specialistId, status: { in: ['SCHEDULING', 'NEGOTIATION'] }, + removed_at: null, }, }), this.prisma.process.count({ - where: { specialist_id: specialistId, status: 'COMPLETED' }, + where: { specialist_id: specialistId, status: 'COMPLETED', removed_at: null }, }), - this.prisma.process.count({ where: { specialist_id: specialistId } }), + this.prisma.process.count({ where: { specialist_id: specialistId, removed_at: null } }), this.buildMonthlySalesData({ specialist_id: specialistId }), this.prisma.process.groupBy({ by: ['status'], - where: { specialist_id: specialistId }, + where: { specialist_id: specialistId, removed_at: null }, _count: { status: true }, }), ]); @@ -220,6 +221,7 @@ export class DashboardService { this.prisma.process.count({ where: { ...baseWhere, + removed_at: null, status: 'COMPLETED', updated_at: { gte: date, lt: nextMonth }, }, @@ -227,6 +229,7 @@ export class DashboardService { this.prisma.process.count({ where: { ...baseWhere, + removed_at: null, status: { not: 'COMPLETED' }, created_at: { gte: date, lt: nextMonth }, }, @@ -255,6 +258,7 @@ export class DashboardService { const completedSales = await this.prisma.process.count({ where: { status: 'COMPLETED', + removed_at: null, client: { consultant_id: consultant.id }, }, }); diff --git a/backend/src/features/drive-import/drive-import.service.spec.ts b/backend/src/features/drive-import/drive-import.service.spec.ts new file mode 100644 index 00000000..8ab6a602 --- /dev/null +++ b/backend/src/features/drive-import/drive-import.service.spec.ts @@ -0,0 +1,114 @@ +import { ProductType } from '@prisma/client'; +import { DriveImportService } from './drive-import.service'; + +describe('DriveImportService fencing', () => { + it('propaga perda do lease depois do upload e não persiste a imagem', async () => { + const prisma = { + car_image: { + findMany: jest.fn().mockResolvedValue([]), + deleteMany: jest.fn().mockResolvedValue({ count: 0 }), + create: jest.fn().mockResolvedValue({}), + }, + } as any; + const s3 = { + uploadBuffer: jest.fn().mockResolvedValue('drive-import/car/key.jpg'), + deleteObjects: jest.fn().mockResolvedValue(undefined), + } as any; + const config = { + get: jest.fn().mockReturnValue('drive-api-key'), + } as any; + const service = new DriveImportService(prisma, s3, config); + jest.spyOn(service as any, 'listPublicFolderImages').mockResolvedValue([ + { id: 'file-1', name: 'photo.jpg', mimeType: 'image/jpeg' }, + ]); + jest.spyOn(service as any, 'downloadDriveFile').mockResolvedValue({ + buffer: Buffer.from('image'), + contentType: 'image/jpeg', + }); + jest.spyOn(service as any, 'sleepBetweenDownloads').mockResolvedValue(undefined); + let checks = 0; + const assertActive = jest.fn(async () => { + checks += 1; + if (checks >= 5) throw new Error('lease perdido'); + }); + + await expect( + service.importImagesForProductFromFolder({ + folder_url: 'valid-folder-id', + product_type: ProductType.CAR, + product_id: '11111111-1111-4111-8111-111111111111', + assert_active: assertActive, + import_job_fence: { + job_id: '22222222-2222-4222-8222-222222222222', + lease_token: '33333333-3333-4333-8333-333333333333', + }, + }), + ).rejects.toThrow('lease perdido'); + + expect(s3.uploadBuffer).toHaveBeenCalledTimes(1); + expect(prisma.car_image.create).not.toHaveBeenCalled(); + expect(s3.deleteObjects).toHaveBeenCalledWith([ + 'drive-import/car/key.jpg', + ]); + expect(assertActive).toHaveBeenCalledTimes(6); + expect(s3.uploadBuffer.mock.calls[0][1]).toContain( + '/33333333-3333-4333-8333-333333333333/', + ); + }); + + it('troca referências em transação fenced antes de apagar chaves antigas', async () => { + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ id: 'job-1' }]), + car_image: { + findMany: jest.fn().mockResolvedValue([{ image_url: 'old-key.jpg' }]), + deleteMany: jest.fn().mockResolvedValue({ count: 1 }), + createMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + } as any; + const prisma = { + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const s3 = { + uploadBuffer: jest.fn().mockResolvedValue('new-versioned-key.jpg'), + deleteObjects: jest.fn().mockResolvedValue(undefined), + } as any; + const service = new DriveImportService( + prisma, + s3, + { get: jest.fn().mockReturnValue('drive-api-key') } as any, + ); + jest.spyOn(service as any, 'listPublicFolderImages').mockResolvedValue([ + { id: 'file-1', name: 'photo.jpg', mimeType: 'image/jpeg' }, + ]); + jest.spyOn(service as any, 'downloadDriveFile').mockResolvedValue({ + buffer: Buffer.from('image'), + contentType: 'image/jpeg', + }); + jest.spyOn(service as any, 'sleepBetweenDownloads').mockResolvedValue(undefined); + const assertActive = jest.fn().mockResolvedValue(undefined); + + await expect( + service.importImagesForProductFromFolder({ + folder_url: 'valid-folder-id', + product_type: ProductType.CAR, + product_id: '11111111-1111-4111-8111-111111111111', + assert_active: assertActive, + import_job_fence: { + job_id: '22222222-2222-4222-8222-222222222222', + lease_token: '33333333-3333-4333-8333-333333333333', + }, + }), + ).resolves.toMatchObject({ uploaded: 1, failed: 0 }); + + expect(tx.$queryRaw).toHaveBeenCalledTimes(1); + expect(tx.car_image.createMany).toHaveBeenCalledWith({ + data: [ + expect.objectContaining({ + image_url: 'new-versioned-key.jpg', + is_primary: true, + }), + ], + }); + expect(s3.deleteObjects).toHaveBeenLastCalledWith(['old-key.jpg']); + }); +}); diff --git a/backend/src/features/drive-import/drive-import.service.ts b/backend/src/features/drive-import/drive-import.service.ts index b085634d..cb9a1153 100644 --- a/backend/src/features/drive-import/drive-import.service.ts +++ b/backend/src/features/drive-import/drive-import.service.ts @@ -5,8 +5,13 @@ import { Logger, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; -import { ProductType, UserRole } from '@prisma/client'; +import { + ProductImportJobStatus, + ProductType, + UserRole, +} from '@prisma/client'; import axios from 'axios'; +import { randomUUID } from 'node:crypto'; import { PrismaService } from 'src/prisma/prisma.service'; import { S3Service } from 'src/aws/s3.service'; import { ImportDriveImagesDto } from './dto/import-drive-images.dto'; @@ -58,6 +63,8 @@ export class DriveImportService { product_type: ProductType; product_id: string; max_files?: number; + assert_active?: () => Promise; + import_job_fence?: { job_id: string; lease_token: string }; }): Promise { const apiKey = this.configService.get('GOOGLE_DRIVE_API_KEY'); @@ -69,13 +76,17 @@ export class DriveImportService { const folderId = this.extractFolderId(params.folder_url); const maxFiles = params.max_files ?? 500; + const assertActive = params.assert_active ?? (async () => {}); let files: DriveFile[]; const warnings: string[] = []; try { + await assertActive(); files = await this.listPublicFolderImages(folderId, apiKey, maxFiles); + await assertActive(); } catch (listError: any) { + await assertActive(); return { folder_id: folderId, found: 0, @@ -99,47 +110,79 @@ export class DriveImportService { }; } - // Substituir imagens existentes: apagar do S3 e do banco antes de importar - await this.deleteAllProductImages(params.product_type, params.product_id); - - let hasPrimary: boolean = false; let uploaded = 0; const skipped = 0; let failed = 0; + const preparedImages: Array<{ key: string; isPrimary: boolean }> = []; + const operationNamespace = + params.import_job_fence?.lease_token ?? randomUUID(); + let imagesCommitted = false; - for (const file of files) { - try { - const downloaded = await this.downloadDriveFile(file.id, apiKey); - const objectKey = this.buildS3ObjectKey( - params.product_type, - params.product_id, - file.name, - ); + try { + for (const file of files) { + await assertActive(); + let uploadedKey: string | null = null; + try { + const downloaded = await this.downloadDriveFile(file.id, apiKey); + await assertActive(); + const objectKey = this.buildS3ObjectKey( + params.product_type, + params.product_id, + file.name, + operationNamespace, + ); - const s3Key = await this.s3Service.uploadBuffer( - downloaded.buffer, - objectKey, - downloaded.contentType, - ); + uploadedKey = await this.s3Service.uploadBuffer( + downloaded.buffer, + objectKey, + downloaded.contentType, + ); + await assertActive(); + preparedImages.push({ + key: uploadedKey, + isPrimary: preparedImages.length === 0, + }); + uploaded += 1; + } catch (error) { + if (uploadedKey) { + await this.s3Service.deleteObjects([uploadedKey]); + } + // Se o fencing foi perdido, a nova verificação propaga o erro em + // vez de convertê-lo em um simples aviso de imagem. + await assertActive(); + failed += 1; + warnings.push( + `Falha ao importar ${file.name}: ${error?.message || 'erro desconhecido'}`, + ); + } - const isPrimary: boolean = !hasPrimary; - await this.createImageRecord({ - productType: params.product_type, - productId: params.product_id, - imageKey: s3Key, - isPrimary, - }); + await this.sleepBetweenDownloads(); + await assertActive(); + } - hasPrimary = hasPrimary || isPrimary; - uploaded += 1; - } catch (error) { - failed += 1; - warnings.push( - `Falha ao importar ${file.name}: ${error?.message || 'erro desconhecido'}`, + if (preparedImages.length > 0) { + await assertActive(); + const oldKeys = await this.replaceProductImages( + params.product_type, + params.product_id, + preparedImages, + params.import_job_fence, ); + imagesCommitted = true; + if (oldKeys.length > 0) { + // Copy-on-write: só remove as chaves antigas depois que o swap + // fenced das referências foi commitado. Chaves novas incluem o + // lease, portanto um worker antigo nunca apaga as do atual. + await this.s3Service.deleteObjects(oldKeys); + } } - - await this.sleepBetweenDownloads(); + } catch (error) { + if (!imagesCommitted && preparedImages.length > 0) { + await this.s3Service.deleteObjects( + preparedImages.map((image) => image.key), + ); + } + throw error; } return { @@ -604,42 +647,75 @@ export class DriveImportService { return Boolean(record); } - private async deleteAllProductImages( + private async replaceProductImages( type: ProductType, productId: string, - ): Promise { - let keys: string[] = []; + images: Array<{ key: string; isPrimary: boolean }>, + fence?: { job_id: string; lease_token: string }, + ): Promise { + return this.prisma.$transaction(async (tx) => { + if (fence) { + const owned = await tx.$queryRaw>` + SELECT "id" + FROM "ProductImportJob" + WHERE "id" = ${fence.job_id}::uuid + AND "processing_lease_token" = ${fence.lease_token}::uuid + AND "status" = ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus" + AND "processing_lease_expires_at" > NOW() + FOR UPDATE + `; + if (owned.length !== 1) { + throw new Error('Lease do job de importação perdido durante o swap de imagens.'); + } + } - if (type === ProductType.CAR) { - const records = await this.prisma.car_image.findMany({ - where: { car_id: productId }, - select: { image_url: true }, - }); - keys = records.map((r) => r.image_url); - await this.prisma.car_image.deleteMany({ where: { car_id: productId } }); - } else if (type === ProductType.BOAT) { - const records = await this.prisma.boat_image.findMany({ - where: { boat_id: productId }, - select: { image_url: true }, - }); - keys = records.map((r) => r.image_url); - await this.prisma.boat_image.deleteMany({ - where: { boat_id: productId }, - }); - } else { - const records = await this.prisma.aircraft_image.findMany({ + if (type === ProductType.CAR) { + const old = await tx.car_image.findMany({ + where: { car_id: productId }, + select: { image_url: true }, + }); + await tx.car_image.deleteMany({ where: { car_id: productId } }); + await tx.car_image.createMany({ + data: images.map((image) => ({ + car_id: productId, + image_url: image.key, + is_primary: image.isPrimary, + product_type: ProductType.CAR, + })), + }); + return old.map((image) => image.image_url); + } + if (type === ProductType.BOAT) { + const old = await tx.boat_image.findMany({ + where: { boat_id: productId }, + select: { image_url: true }, + }); + await tx.boat_image.deleteMany({ where: { boat_id: productId } }); + await tx.boat_image.createMany({ + data: images.map((image) => ({ + boat_id: productId, + image_url: image.key, + is_primary: image.isPrimary, + product_type: ProductType.BOAT, + })), + }); + return old.map((image) => image.image_url); + } + const old = await tx.aircraft_image.findMany({ where: { aircraft_id: productId }, select: { image_url: true }, }); - keys = records.map((r) => r.image_url); - await this.prisma.aircraft_image.deleteMany({ - where: { aircraft_id: productId }, + await tx.aircraft_image.deleteMany({ where: { aircraft_id: productId } }); + await tx.aircraft_image.createMany({ + data: images.map((image) => ({ + aircraft_id: productId, + image_url: image.key, + is_primary: image.isPrimary, + product_type: ProductType.AIRCRAFT, + })), }); - } - - if (keys.length > 0) { - await this.s3Service.deleteObjects(keys); - } + return old.map((image) => image.image_url); + }); } private parseProductFromFileName(fileName: string): { @@ -696,8 +772,13 @@ export class DriveImportService { type: ProductType, productId: string, originalName: string, + operationNamespace?: string, ): string { const safeFileName = this.sanitizeS3FileName(originalName); + if (operationNamespace) { + const safeNamespace = this.sanitizeS3FileName(operationNamespace); + return `drive-import/${type.toLowerCase()}/${productId}/${safeNamespace}/${randomUUID()}-${safeFileName}`; + } return `drive-import/${type.toLowerCase()}/${productId}/${safeFileName}`; } diff --git a/backend/src/features/meetings/meeting-initialization-claim.ts b/backend/src/features/meetings/meeting-initialization-claim.ts new file mode 100644 index 00000000..08325e30 --- /dev/null +++ b/backend/src/features/meetings/meeting-initialization-claim.ts @@ -0,0 +1,72 @@ +export const MEETING_INITIALIZATION_PREFIX = 'meeting-init:'; +export const MEETING_READY_PREFIX = 'meeting-ready:'; +export const MEETING_INITIALIZATION_TTL_MS = 2 * 60 * 1000; + +type MeetingClaim = { + calendar_event_id?: string | null; + started_at?: Date | null; +}; + +export type ReadyMeetingClaim = { + claimId: string; + provider: 'JITSI' | 'GOOGLE' | 'DEMO'; + calendarEventId: string; +}; + +export function isMeetingInitializationClaim( + meeting: MeetingClaim | null | undefined, +): boolean { + return Boolean( + meeting?.calendar_event_id?.startsWith(MEETING_INITIALIZATION_PREFIX), + ); +} + +export function isStaleMeetingInitializationClaim( + meeting: MeetingClaim | null | undefined, + now = Date.now(), +): boolean { + if (!isMeetingInitializationClaim(meeting) || !meeting?.started_at) { + return false; + } + const startedAt = meeting.started_at.getTime(); + return ( + Number.isFinite(startedAt) && + now - startedAt >= MEETING_INITIALIZATION_TTL_MS + ); +} + +export function parseReadyMeetingClaim( + meeting: MeetingClaim | null | undefined, +): ReadyMeetingClaim | null { + const value = meeting?.calendar_event_id; + if (typeof value !== 'string' || !value.startsWith(MEETING_READY_PREFIX)) { + return null; + } + const [claimId, provider, encodedCalendarEventId] = value + .slice(MEETING_READY_PREFIX.length) + .split(':', 3); + if ( + !claimId || + !encodedCalendarEventId || + !['JITSI', 'GOOGLE', 'DEMO'].includes(provider) + ) { + return null; + } + try { + return { + claimId, + provider: provider as ReadyMeetingClaim['provider'], + calendarEventId: decodeURIComponent(encodedCalendarEventId), + }; + } catch { + return null; + } +} + +export function buildReadyMeetingClaim( + claimId: string, + provider: ReadyMeetingClaim['provider'], + calendarEventId: string, +): string { + return `${MEETING_READY_PREFIX}${claimId}:${provider}:${encodeURIComponent(calendarEventId)}`; +} diff --git a/backend/src/features/meetings/meeting-reminder.service.ts b/backend/src/features/meetings/meeting-reminder.service.ts index 65323b91..fd4bb93e 100644 --- a/backend/src/features/meetings/meeting-reminder.service.ts +++ b/backend/src/features/meetings/meeting-reminder.service.ts @@ -66,6 +66,7 @@ export class MeetingReminderService implements OnModuleInit, OnModuleDestroy { process: { is: { status: ProcessStatus.SCHEDULING, + removed_at: null, }, }, }, diff --git a/backend/src/features/meetings/meetings.controller.ts b/backend/src/features/meetings/meetings.controller.ts index f47e8230..bc87ae7c 100644 --- a/backend/src/features/meetings/meetings.controller.ts +++ b/backend/src/features/meetings/meetings.controller.ts @@ -8,20 +8,44 @@ import { Req, UnauthorizedException, UseGuards, + Query, + Optional, } from '@nestjs/common'; import { AuthGuard } from 'src/auth/auth.guard'; import { ApiResponseDto } from 'src/shared/dto/api-response.dto'; import { MeetingsService } from './meetings.service'; +import { UserRole } from '@prisma/client'; +import { + ActorContext, + ActorContextService, +} from 'src/shared/actor-context/actor-context.service'; @Controller('meetings') @UseGuards(AuthGuard) export class MeetingsController { - constructor(private readonly meetingsService: MeetingsService) {} + constructor( + private readonly meetingsService: MeetingsService, + @Optional() private readonly actorContextService?: ActorContextService, + ) {} + + private async resolveSpecialistContext( + user: any, + targetSpecialistId?: string, + ): Promise { + if ( + !this.actorContextService || + (user?.role !== UserRole.ADMIN && user?.role !== UserRole.SPECIALIST) + ) { + return undefined; + } + return this.actorContextService.resolve(user, targetSpecialistId); + } @Get('process/:processId') async getMeetingByProcess( @Param('processId', new ParseUUIDPipe()) processId: string, @Req() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const userId = req.user?.sub || req.user?.id; @@ -29,9 +53,14 @@ export class MeetingsController { throw new UnauthorizedException('Usuário autenticado não identificado'); } + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); const meeting = await this.meetingsService.getMeetingByProcess( processId, userId, + context, ); return { @@ -48,6 +77,7 @@ export class MeetingsController { @Param('processId', new ParseUUIDPipe()) processId: string, @Req() req: any, @Body() body: { isAdvanced?: boolean }, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const userId = req.user?.sub || req.user?.id; @@ -55,10 +85,15 @@ export class MeetingsController { throw new UnauthorizedException('Usuário autenticado não identificado'); } + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); const meeting = await this.meetingsService.startMeetingForProcess( processId, userId, body?.isAdvanced, + context, ); return { @@ -74,6 +109,7 @@ export class MeetingsController { async endMeeting( @Param('processId', new ParseUUIDPipe()) processId: string, @Req() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const userId = req.user?.sub || req.user?.id; @@ -81,9 +117,14 @@ export class MeetingsController { throw new UnauthorizedException('Usuário autenticado não identificado'); } + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); const result = await this.meetingsService.endMeetingForProcess( processId, userId, + context, ); return { @@ -97,6 +138,7 @@ export class MeetingsController { async markConversationDone( @Param('processId', new ParseUUIDPipe()) processId: string, @Req() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const userId = req.user?.sub || req.user?.id; @@ -104,9 +146,14 @@ export class MeetingsController { throw new UnauthorizedException('Usuário autenticado não identificado'); } + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); const result = await this.meetingsService.markConversationDone( processId, userId, + context, ); return { diff --git a/backend/src/features/meetings/meetings.service.spec.ts b/backend/src/features/meetings/meetings.service.spec.ts index 79eb365d..2be41c17 100644 --- a/backend/src/features/meetings/meetings.service.spec.ts +++ b/backend/src/features/meetings/meetings.service.spec.ts @@ -1,9 +1,14 @@ -import { ServiceUnavailableException } from '@nestjs/common'; +import { + BadRequestException, + ConflictException, + ServiceUnavailableException, +} from '@nestjs/common'; import { Prisma, ProcessStatus, ProductCurrency, ProductType, + StatusAgendamento, } from '@prisma/client'; import { MeetingsService } from './meetings.service'; @@ -13,6 +18,13 @@ function mkProcess(overrides: any = {}) { client_id: 'client-1', specialist_id: 'spec-1', status: 'SCHEDULING', + appointment_id: 'appointment-1', + appointment: { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'spec-1', + status: StatusAgendamento.SCHEDULED, + }, meeting_session: null, client: { id: 'client-1', @@ -33,27 +45,92 @@ function mkProcess(overrides: any = {}) { } function mkPrisma(process: any) { + let storedMeeting = process.meeting_session; + const meetingSessionCreate = jest.fn().mockImplementation(({ data }: any) => { + storedMeeting = { + id: 'meet-1', + process_id: data.process_id, + calendar_event_id: data.calendar_event_id, + meet_link: data.meet_link, + started_at: data.started_at, + ended_at: null, + }; + return Promise.resolve(storedMeeting); + }); + const meetingSessionUpdateMany = jest + .fn() + .mockImplementation(({ where, data }: any) => { + if ( + storedMeeting && + (!where.id || where.id === storedMeeting.id) && + (!where.process_id || where.process_id === storedMeeting.process_id) && + (!where.calendar_event_id || + where.calendar_event_id === storedMeeting.calendar_event_id) && + (where.ended_at === undefined || + where.ended_at === storedMeeting.ended_at) && + (where.meet_link === undefined || + where.meet_link === storedMeeting.meet_link) + ) { + storedMeeting = { ...storedMeeting, ...data }; + return Promise.resolve({ count: 1 }); + } + return Promise.resolve({ count: 0 }); + }); + const meetingSessionDeleteMany = jest.fn().mockImplementation(({ where }) => { + if ( + storedMeeting && + (!where.id || where.id === storedMeeting.id) && + (!where.process_id || where.process_id === storedMeeting.process_id) && + (!where.calendar_event_id || + where.calendar_event_id === storedMeeting.calendar_event_id) + ) { + storedMeeting = null; + return Promise.resolve({ count: 1 }); + } + return Promise.resolve({ count: 0 }); + }); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + process: { + findUnique: jest + .fn() + .mockImplementation(({ select }: any) => + Promise.resolve( + select + ? { id: process.id, specialist_id: process.specialist_id } + : { ...process, meeting_session: storedMeeting }, + ), + ), + }, + meetingSession: { + create: meetingSessionCreate, + updateMany: meetingSessionUpdateMany, + deleteMany: meetingSessionDeleteMany, + findUnique: jest.fn().mockImplementation(() => storedMeeting), + }, + }; return { - process: { findUnique: jest.fn().mockResolvedValue(process) }, + process: { + findUnique: jest + .fn() + .mockImplementation(() => + Promise.resolve({ ...process, meeting_session: storedMeeting }), + ), + }, meetingSession: { - create: jest.fn().mockImplementation(({ data }: any) => - Promise.resolve({ - id: 'meet-1', - process_id: data.process_id, - meet_link: data.meet_link, - started_at: data.started_at, - ended_at: null, - }), - ), + create: meetingSessionCreate, + updateMany: meetingSessionUpdateMany, + deleteMany: meetingSessionDeleteMany, }, + $transaction: jest.fn(async (callback) => callback(tx)), } as any; } -function mkConfig(accessType = 'OPEN') { +function mkConfig(accessType = 'OPEN', provider = 'GOOGLE') { return { get: jest.fn((key: string, def?: string) => { if (key === 'GOOGLE_MEET_ACCESS_TYPE') return accessType; - if (key === 'MEETING_PROVIDER') return 'GOOGLE'; + if (key === 'MEETING_PROVIDER') return provider; if (key === 'MEETING_DEMO_FALLBACK_ENABLED') return 'false'; return def; }), @@ -72,8 +149,23 @@ describe('MeetingsService — criação via Meet REST API', () => { it('cria sala Meet com accessType OPEN e grava meet_link + spaceName', async () => { const process = mkProcess(); const prisma = mkPrisma(process); + let transactionActive = false; + const runTransaction = prisma.$transaction.getMockImplementation(); + prisma.$transaction.mockImplementation( + async (callback: (tx: any) => Promise, options?: any) => { + transactionActive = true; + try { + return await runTransaction(callback, options); + } finally { + transactionActive = false; + } + }, + ); const oauth = { - getAccessToken: jest.fn().mockResolvedValue('access-token'), + getAccessToken: jest.fn().mockImplementation(async () => { + expect(transactionActive).toBe(false); + return 'access-token'; + }), } as any; const fetchMock = jest.fn().mockResolvedValue({ @@ -101,11 +193,10 @@ describe('MeetingsService — criação via Meet REST API', () => { ); expect(result.meet_link).toBe('https://meet.google.com/abc-defg-hij'); - expect(prisma.meetingSession.create).toHaveBeenCalledWith( + expect(prisma.meetingSession.updateMany).toHaveBeenLastCalledWith( expect.objectContaining({ data: expect.objectContaining({ calendar_event_id: 'spaces/abc123', - meet_link: 'https://meet.google.com/abc-defg-hij', }), }), ); @@ -129,6 +220,263 @@ describe('MeetingsService — criação via Meet REST API', () => { await expect( svc.startMeetingForProcess('proc-1', 'spec-1'), ).rejects.toThrow(ServiceUnavailableException); + expect(prisma.meetingSession.deleteMany).toHaveBeenCalledWith({ + where: expect.objectContaining({ + process_id: 'proc-1', + calendar_event_id: expect.stringMatching(/^meeting-init:/), + }), + }); + }); + + it('aborta provider travado por timeout e libera o claim', async () => { + jest.useFakeTimers(); + try { + const process = mkProcess(); + const prisma = mkPrisma(process); + const oauth = { + getAccessToken: jest.fn().mockResolvedValue('access-token'), + } as any; + const fetchMock = jest.fn().mockImplementation((_url, options) => { + return new Promise((_resolve, reject) => { + options.signal.addEventListener('abort', () => { + reject(new Error('provider abortado')); + }); + }); + }); + global.fetch = fetchMock as any; + const svc = new MeetingsService( + prisma, + mkConfig('OPEN'), + notification, + oauth, + ); + + const start = svc.startMeetingForProcess('proc-1', 'spec-1'); + const rejection = expect(start).rejects.toBeInstanceOf( + ServiceUnavailableException, + ); + for ( + let attempt = 0; + attempt < 50 && !fetchMock.mock.calls.length; + attempt += 1 + ) { + await Promise.resolve(); + } + expect(fetchMock).toHaveBeenCalledTimes(1); + await jest.advanceTimersByTimeAsync(10_000); + + await rejection; + expect(fetchMock.mock.calls[0][1].signal.aborted).toBe(true); + expect(prisma.meetingSession.deleteMany).toHaveBeenCalled(); + } finally { + jest.useRealTimers(); + } + }); + + it('aplica a deadline enquanto o OAuth está pendente e não chama o provider', async () => { + jest.useFakeTimers(); + const originalFetch = global.fetch; + try { + const process = mkProcess(); + const prisma = mkPrisma(process); + let resolveOAuth!: (token: string) => void; + const oauth = { + getAccessToken: jest.fn().mockImplementation( + () => + new Promise((resolve) => { + resolveOAuth = resolve; + }), + ), + } as any; + const fetchMock = jest.fn(); + global.fetch = fetchMock as any; + const svc = new MeetingsService( + prisma, + mkConfig('OPEN'), + notification, + oauth, + ); + let caught: unknown; + void svc + .startMeetingForProcess('proc-1', 'spec-1') + .catch((error) => (caught = error)); + + for ( + let attempt = 0; + attempt < 10 && !oauth.getAccessToken.mock.calls.length; + attempt += 1 + ) { + await Promise.resolve(); + } + expect(oauth.getAccessToken).toHaveBeenCalledTimes(1); + await jest.advanceTimersByTimeAsync(10_000); + for (let attempt = 0; attempt < 10 && !caught; attempt += 1) { + await Promise.resolve(); + } + + expect(caught).toBeInstanceOf(ServiceUnavailableException); + resolveOAuth('access-token-atrasado'); + await Promise.resolve(); + await Promise.resolve(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(prisma.meetingSession.updateMany).not.toHaveBeenCalled(); + expect(prisma.meetingSession.deleteMany).toHaveBeenCalled(); + } finally { + global.fetch = originalFetch; + jest.useRealTimers(); + } + }); + + it('mantém a deadline até terminar o parse do body e não persiste sala atrasada', async () => { + jest.useFakeTimers(); + const originalFetch = global.fetch; + try { + const process = mkProcess(); + const prisma = mkPrisma(process); + const oauth = { + getAccessToken: jest.fn().mockResolvedValue('access-token'), + } as any; + let resolveJson!: (body: unknown) => void; + const json = jest.fn().mockImplementation( + () => + new Promise((resolve) => { + resolveJson = resolve; + }), + ); + const fetchMock = jest.fn().mockResolvedValue({ ok: true, json }); + global.fetch = fetchMock as any; + const svc = new MeetingsService( + prisma, + mkConfig('OPEN'), + notification, + oauth, + ); + let caught: unknown; + void svc + .startMeetingForProcess('proc-1', 'spec-1') + .catch((error) => (caught = error)); + + for ( + let attempt = 0; + attempt < 50 && !json.mock.calls.length; + attempt += 1 + ) { + await Promise.resolve(); + } + expect(json).toHaveBeenCalledTimes(1); + await jest.advanceTimersByTimeAsync(10_000); + for (let attempt = 0; attempt < 10 && !caught; attempt += 1) { + await Promise.resolve(); + } + + expect(caught).toBeInstanceOf(ServiceUnavailableException); + resolveJson({ + name: 'spaces/atrasada', + meetingUri: 'https://meet.google.com/atrasada', + }); + await Promise.resolve(); + await Promise.resolve(); + expect(prisma.meetingSession.updateMany).not.toHaveBeenCalled(); + expect(prisma.meetingSession.deleteMany).toHaveBeenCalled(); + } finally { + global.fetch = originalFetch; + jest.useRealTimers(); + } + }); + + it('recupera claim pronto sem chamar o provedor nem duplicar notificação', async () => { + const process = mkProcess({ + meeting_session: { + id: 'meet-1', + process_id: 'proc-1', + calendar_event_id: 'meeting-ready:claim-1:GOOGLE:spaces%2Frecovered', + meet_link: 'https://meet.google.com/recovered', + started_at: new Date(), + ended_at: null, + }, + }); + const prisma = mkPrisma(process); + const oauth = { getAccessToken: jest.fn() } as any; + const localNotification = { + sendMeetingStartedEmail: jest.fn().mockResolvedValue({}), + sendMeetingAdvancedEmail: jest.fn().mockResolvedValue({}), + } as any; + const svc = new MeetingsService( + prisma, + mkConfig('OPEN'), + localNotification, + oauth, + ); + + await expect( + svc.startMeetingForProcess('proc-1', 'spec-1'), + ).resolves.toMatchObject({ + meet_link: 'https://meet.google.com/recovered', + is_active: true, + }); + await new Promise((resolve) => setImmediate(resolve)); + + expect(oauth.getAccessToken).not.toHaveBeenCalled(); + expect(prisma.meetingSession.updateMany).toHaveBeenCalledWith( + expect.objectContaining({ + data: { calendar_event_id: 'spaces/recovered' }, + }), + ); + expect(localNotification.sendMeetingStartedEmail).toHaveBeenCalledTimes(1); + }); + + it('recusa start duplicado enquanto um claim recente está inicializando', async () => { + const process = mkProcess({ + meeting_session: { + id: 'meet-1', + process_id: 'proc-1', + calendar_event_id: 'meeting-init:claim-1', + meet_link: '', + started_at: new Date(), + ended_at: null, + }, + }); + const prisma = mkPrisma(process); + const oauth = { getAccessToken: jest.fn() } as any; + const svc = new MeetingsService( + prisma, + mkConfig('OPEN'), + notification, + oauth, + ); + + await expect( + svc.startMeetingForProcess('proc-1', 'spec-1'), + ).rejects.toBeInstanceOf(ConflictException); + + expect(oauth.getAccessToken).not.toHaveBeenCalled(); + expect(prisma.meetingSession.create).not.toHaveBeenCalled(); + }); + + it('não conclui conversa usando claim de inicialização vencido', async () => { + const process = mkProcess({ + meeting_session: { + id: 'meet-1', + process_id: 'proc-1', + calendar_event_id: 'meeting-init:claim-vencido', + meet_link: '', + started_at: new Date(Date.now() - 3 * 60 * 1000), + ended_at: null, + }, + }); + const prisma = mkPrisma(process); + const svc = new MeetingsService( + prisma, + mkConfig('OPEN'), + notification, + {} as any, + ); + + await expect( + svc.markConversationDone('proc-1', 'spec-1'), + ).rejects.toBeInstanceOf(ConflictException); + + expect(prisma.meetingSession.deleteMany).not.toHaveBeenCalled(); }); it('só o especialista pode iniciar a reunião', async () => { @@ -149,6 +497,190 @@ describe('MeetingsService — criação via Meet REST API', () => { }); }); +describe('MeetingsService.startMeetingForProcess — serialização canônica', () => { + it('não cria claim enquanto o appointment ainda está PENDING', async () => { + const process = mkProcess({ + appointment: { + id: 'appointment-1', + client_id: 'client-1', + specialist_id: 'spec-1', + status: StatusAgendamento.PENDING, + }, + }); + const prisma = mkPrisma(process); + const service = new MeetingsService( + prisma, + mkConfig('OPEN', 'JITSI'), + notification, + {} as any, + ); + + await expect( + service.startMeetingForProcess(process.id, 'spec-1'), + ).rejects.toThrow('Agendamento não está confirmado'); + expect(prisma.meetingSession.create).not.toHaveBeenCalled(); + }); + + it('remove o claim se a revalidação final encontrar processo terminal', async () => { + const process = mkProcess(); + const prisma = mkPrisma(process); + const runTransaction = prisma.$transaction.getMockImplementation(); + let transactionCount = 0; + prisma.$transaction.mockImplementation(async (callback, options) => { + transactionCount += 1; + if (transactionCount === 2) { + process.status = ProcessStatus.REJECTED; + } + return runTransaction(callback, options); + }); + const localNotification = { + sendMeetingStartedEmail: jest.fn().mockResolvedValue({}), + sendMeetingAdvancedEmail: jest.fn().mockResolvedValue({}), + } as any; + const service = new MeetingsService( + prisma, + mkConfig('OPEN', 'JITSI'), + localNotification, + {} as any, + ); + + await expect( + service.startMeetingForProcess(process.id, 'spec-1'), + ).rejects.toBeInstanceOf(BadRequestException); + + expect(prisma.meetingSession.deleteMany).toHaveBeenCalledWith({ + where: expect.objectContaining({ + id: 'meet-1', + calendar_event_id: expect.stringMatching(/^meeting-ready:/), + }), + }); + expect(localNotification.sendMeetingStartedEmail).not.toHaveBeenCalled(); + }); + + it('adquire o lock, relê e não cria reunião para processo rejeitado', async () => { + const initialProcess = mkProcess(); + const rejectedProcess = mkProcess({ status: ProcessStatus.REJECTED }); + const rootMeetingCreate = jest.fn().mockResolvedValue({}); + const txMeetingCreate = jest.fn().mockResolvedValue({}); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + process: { + findUnique: jest + .fn() + .mockResolvedValueOnce({ + id: initialProcess.id, + specialist_id: initialProcess.specialist_id, + }) + .mockResolvedValueOnce(rejectedProcess), + }, + meetingSession: { create: txMeetingCreate }, + }; + const prisma = { + process: { findUnique: jest.fn().mockResolvedValue(initialProcess) }, + meetingSession: { create: rootMeetingCreate }, + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const localNotification = { + sendMeetingStartedEmail: jest.fn().mockResolvedValue({}), + sendMeetingAdvancedEmail: jest.fn().mockResolvedValue({}), + } as any; + const service = new MeetingsService( + prisma, + mkConfig('OPEN', 'JITSI'), + localNotification, + {} as any, + ); + + await expect( + service.startMeetingForProcess(initialProcess.id, 'spec-1'), + ).rejects.toBeInstanceOf(BadRequestException); + + expect(tx.$queryRaw).toHaveBeenCalledWith( + expect.anything(), + 'appointment-schedule:spec-1', + ); + expect(rootMeetingCreate).not.toHaveBeenCalled(); + expect(txMeetingCreate).not.toHaveBeenCalled(); + expect(localNotification.sendMeetingStartedEmail).not.toHaveBeenCalled(); + }); + + it('falha fechado quando o appointment relido diverge do processo', async () => { + const process = mkProcess({ + appointment_id: 'appointment-1', + appointment: { + id: 'appointment-1', + client_id: 'other-client', + specialist_id: 'spec-1', + status: StatusAgendamento.COMPLETED, + }, + }); + const txMeetingCreate = jest.fn(); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + process: { + findUnique: jest + .fn() + .mockResolvedValueOnce({ + id: process.id, + specialist_id: process.specialist_id, + }) + .mockResolvedValueOnce(process), + }, + meetingSession: { create: txMeetingCreate }, + }; + const prisma = { + process: { findUnique: jest.fn().mockResolvedValue(process) }, + meetingSession: { create: jest.fn().mockResolvedValue({}) }, + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const service = new MeetingsService( + prisma, + mkConfig('OPEN', 'JITSI'), + notification, + {} as any, + ); + + await expect( + service.startMeetingForProcess(process.id, 'spec-1'), + ).rejects.toThrow('Agendamento não corresponde aos participantes'); + + expect(txMeetingCreate).not.toHaveBeenCalled(); + }); +}); + +describe('MeetingsService.endMeetingForProcess — claim concorrente', () => { + it('grava um único encerramento quando duas chamadas disputam a reunião', async () => { + const process = mkProcess({ + meeting_session: { + id: 'meeting-1', + process_id: 'proc-1', + calendar_event_id: 'spaces/meeting-1', + meet_link: 'https://meet.google.com/abc-defg-hij', + started_at: new Date('2026-01-01T10:00:00.000Z'), + ended_at: null, + }, + }); + const prisma = mkPrisma(process); + const service = new MeetingsService( + prisma, + mkConfig(), + notification, + {} as any, + ); + + const results = await Promise.all([ + service.endMeetingForProcess('proc-1', 'spec-1'), + service.endMeetingForProcess('proc-1', 'spec-1'), + ]); + + expect(results.map((result) => result.alreadyEnded).sort()).toEqual([ + false, + true, + ]); + expect(prisma.meetingSession.updateMany).toHaveBeenCalledTimes(2); + }); +}); + describe('MeetingsService.markConversationDone — snapshot da negociação', () => { it('grava snapshot USD, status e histórico na mesma transação', async () => { const product = { @@ -186,6 +718,14 @@ describe('MeetingsService.markConversationDone — snapshot da negociação', () const historyCreate = jest.fn().mockResolvedValue({}); const tx = { $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + meetingSession: { + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + findUnique: jest.fn().mockResolvedValue({ + ...process.meeting_session, + ended_at: new Date('2026-01-01T11:00:00.000Z'), + ended_by_id: 'spec-1', + }), + }, process: { findUniqueOrThrow: jest.fn().mockResolvedValue(process), update: txProcessUpdate, @@ -217,9 +757,12 @@ describe('MeetingsService.markConversationDone — snapshot da negociação', () await service.markConversationDone('proc-1', 'spec-1'); - expect(prisma.$transaction).toHaveBeenCalledTimes(1); - expect(tx.$queryRaw).toHaveBeenCalledTimes(1); - expect(tx.$queryRaw.mock.calls[0][1]).toBe('product-money:CAR:product-1'); + expect(prisma.$transaction).toHaveBeenCalledTimes(2); + expect(tx.$queryRaw).toHaveBeenCalledTimes(2); + expect(tx.$queryRaw.mock.calls[0][1]).toBe( + 'appointment-schedule:spec-1', + ); + expect(tx.$queryRaw.mock.calls[1][1]).toBe('product-money:CAR:product-1'); expect(tx.process.findUniqueOrThrow).toHaveBeenCalledWith({ where: { id: 'proc-1' }, include: { @@ -232,7 +775,11 @@ describe('MeetingsService.markConversationDone — snapshot da negociação', () expect(txProcessUpdate).not.toHaveBeenCalled(); expect(txProcessUpdateMany).toHaveBeenCalledWith( expect.objectContaining({ - where: { id: 'proc-1', status: ProcessStatus.SCHEDULING }, + where: { + id: 'proc-1', + status: ProcessStatus.SCHEDULING, + removed_at: null, + }, data: expect.objectContaining({ status: ProcessStatus.NEGOTIATION, negotiation_currency: ProductCurrency.USD, @@ -296,6 +843,14 @@ describe('MeetingsService.markConversationDone — snapshot da negociação', () const historyCreate = jest.fn(); const tx = { $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + meetingSession: { + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + findUnique: jest.fn().mockResolvedValue({ + ...process.meeting_session, + ended_at: new Date('2026-01-01T11:00:00.000Z'), + ended_by_id: 'spec-1', + }), + }, process: { findUniqueOrThrow: jest .fn() @@ -337,7 +892,11 @@ describe('MeetingsService.markConversationDone — snapshot da negociação', () if (expectsClaim) { expect(processUpdateMany).toHaveBeenCalledWith( expect.objectContaining({ - where: { id: 'proc-1', status: ProcessStatus.SCHEDULING }, + where: { + id: 'proc-1', + status: ProcessStatus.SCHEDULING, + removed_at: null, + }, }), ); } else { diff --git a/backend/src/features/meetings/meetings.service.ts b/backend/src/features/meetings/meetings.service.ts index b1d208ba..fb837447 100644 --- a/backend/src/features/meetings/meetings.service.ts +++ b/backend/src/features/meetings/meetings.service.ts @@ -1,10 +1,12 @@ import { BadRequestException, + ConflictException, ForbiddenException, Injectable, Logger, NotFoundException, ServiceUnavailableException, + Optional, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { randomUUID } from 'crypto'; @@ -14,6 +16,18 @@ import { ProcessStatus, StatusAgendamento } from '@prisma/client'; import { GoogleMeetOAuthService } from './google-meet-oauth.service'; import { buildNegotiationSnapshotUpdate } from 'src/features/processes/negotiation-snapshot'; import { lockNegotiationProductMoney } from 'src/features/products/product-monetary-lock'; +import { acquireSpecialistScheduleLock } from 'src/features/appointments/appointment-schedule-lock'; +import { + buildReadyMeetingClaim, + isMeetingInitializationClaim, + isStaleMeetingInitializationClaim, + MEETING_INITIALIZATION_PREFIX, + parseReadyMeetingClaim, +} from './meeting-initialization-claim'; +import { ActorContext } from 'src/shared/actor-context/actor-context.service'; +import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service'; + +const MEETING_PROVIDER_TIMEOUT_MS = 10_000; @Injectable() export class MeetingsService { @@ -29,6 +43,8 @@ export class MeetingsService { private readonly configService: ConfigService, private readonly notificationService: NotificationService, private readonly googleMeetOAuthService: GoogleMeetOAuthService, + @Optional() + private readonly delegatedAudit?: DelegatedActionAuditService, ) { const accessType = this.configService .get('GOOGLE_MEET_ACCESS_TYPE', 'OPEN') @@ -72,37 +88,122 @@ export class MeetingsService { spaceName: string; meetingUri: string; }> { - const accessToken = await this.googleMeetOAuthService.getAccessToken(); - - const response = await fetch('https://meet.googleapis.com/v2/spaces', { - method: 'POST', - headers: { - Authorization: `Bearer ${accessToken}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - config: { accessType: this.meetAccessType }, - }), + const controller = new AbortController(); + let timeout: ReturnType | undefined; + const deadline = new Promise((_resolve, reject) => { + timeout = setTimeout(() => { + controller.abort(); + reject( + new Error( + `Tempo limite de ${MEETING_PROVIDER_TIMEOUT_MS}ms excedido ao criar sala`, + ), + ); + }, MEETING_PROVIDER_TIMEOUT_MS); }); + const beforeDeadline = (operation: Promise): Promise => + Promise.race([operation, deadline]); + + try { + const accessToken = await beforeDeadline( + this.googleMeetOAuthService.getAccessToken(), + ); - if (!response.ok) { - const detail = await response.text(); - throw new Error( - `Meet spaces.create falhou (${response.status}): ${detail}`, + const response = await beforeDeadline( + fetch('https://meet.googleapis.com/v2/spaces', { + method: 'POST', + headers: { + Authorization: `Bearer ${accessToken}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + config: { accessType: this.meetAccessType }, + }), + signal: controller.signal, + }), ); + + if (!response.ok) { + const detail = await beforeDeadline(response.text()); + throw new Error( + `Meet spaces.create falhou (${response.status}): ${detail}`, + ); + } + + const data: any = await beforeDeadline(response.json()); + if (!data?.meetingUri || !data?.name) { + throw new Error( + 'Meet spaces.create retornou resposta sem meetingUri/name', + ); + } + + return { spaceName: data.name, meetingUri: data.meetingUri }; + } finally { + if (timeout) { + clearTimeout(timeout); + } } + } - const data: any = await response.json(); - if (!data?.meetingUri || !data?.name) { - throw new Error( - 'Meet spaces.create retornou resposta sem meetingUri/name', + private assertMeetingCanStart(process: any, userId: string): void { + if (process.removed_at) { + throw new NotFoundException('Processo não encontrado'); + } + if (process.specialist_id !== userId) { + throw new ForbiddenException( + 'Apenas o especialista pode iniciar a reunião', ); } + if ( + !process.appointment_id || + !process.appointment || + process.appointment.id !== process.appointment_id || + process.appointment.client_id !== process.client_id || + process.appointment.specialist_id !== process.specialist_id + ) { + throw new BadRequestException( + 'Agendamento não corresponde aos participantes do processo', + ); + } + if ( + process.appointment.status !== StatusAgendamento.SCHEDULED && + process.appointment.status !== StatusAgendamento.COMPLETED + ) { + throw new BadRequestException( + 'Agendamento não está confirmado para iniciar reunião', + ); + } + if ( + process.status !== ProcessStatus.SCHEDULING && + process.status !== ProcessStatus.NEGOTIATION && + process.status !== ProcessStatus.PROCESSING_CONTRACT + ) { + throw new BadRequestException( + 'Processo não está em etapa válida para iniciar reunião', + ); + } + } - return { spaceName: data.name, meetingUri: data.meetingUri }; + private async removeInitializationClaim( + processId: string, + specialistId: string, + calendarEventId: string, + ): Promise { + await this.prismaService.$transaction(async (tx) => { + await acquireSpecialistScheduleLock(tx, specialistId); + await tx.meetingSession.deleteMany({ + where: { + process_id: processId, + calendar_event_id: calendarEventId, + }, + }); + }); } - private async getAuthorizedProcess(processId: string, userId: string) { + private async getAuthorizedProcess( + processId: string, + userId: string, + context?: ActorContext, + ) { const process = await this.prismaService.process.findUnique({ where: { id: processId }, include: { @@ -126,12 +227,13 @@ export class MeetingsService { }, }); - if (!process) { + if (!process || process.removed_at) { throw new NotFoundException('Processo não encontrado'); } const isClient = process.client_id === userId; - const isSpecialist = process.specialist_id === userId; + const representedSpecialistId = context?.specialistId ?? userId; + const isSpecialist = process.specialist_id === representedSpecialistId; // Consultor que gerencia o cliente também pode acompanhar a reunião const isConsultant = process.client?.consultant_id === userId; @@ -178,6 +280,7 @@ export class MeetingsService { private async advanceProcessAfterConversation( processId: string, userId: string, + context?: ActorContext, ): Promise<{ advanced: boolean; previous_status: ProcessStatus; @@ -190,6 +293,7 @@ export class MeetingsService { select: { id: true, status: true, + removed_at: true, notes: true, product_type: true, car_id: true, @@ -215,7 +319,7 @@ export class MeetingsService { }, }); - if (!process) { + if (!process || process.removed_at) { throw new NotFoundException('Processo não encontrado'); } @@ -227,8 +331,8 @@ export class MeetingsService { const previousStatus = process.status as ProcessStatus; if (!hasProduct) { - await this.prismaService.process.update({ - where: { id: processId }, + await this.prismaService.process.updateMany({ + where: { id: processId, removed_at: null }, data: { notes: process.notes ? `${process.notes}\n\nConversa concluída com cliente (${new Date().toISOString()}). Aguardando seleção de produto.` @@ -266,6 +370,9 @@ export class MeetingsService { aircraft: { select: { valor: true, currency: true } }, }, }); + if (processForTransition.removed_at) { + throw new NotFoundException('Processo não encontrado'); + } if (processForTransition.status !== ProcessStatus.SCHEDULING) { return { advanced: false, @@ -274,7 +381,7 @@ export class MeetingsService { } const snapshotData = buildNegotiationSnapshotUpdate(processForTransition); const claim = await tx.process.updateMany({ - where: { id: processId, status: ProcessStatus.SCHEDULING }, + where: { id: processId, status: ProcessStatus.SCHEDULING, removed_at: null }, data: { status: ProcessStatus.NEGOTIATION, notes: processForTransition.notes @@ -304,6 +411,22 @@ export class MeetingsService { }, }); + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'MEETING_CONVERSATION_DONE', + resourceType: 'PROCESS', + resourceId: processId, + metadata: { + from: ProcessStatus.SCHEDULING, + to: ProcessStatus.NEGOTIATION, + }, + }, + tx, + ); + } + return { advanced: true, status: ProcessStatus.NEGOTIATION }; }); @@ -338,7 +461,9 @@ export class MeetingsService { previousStatus: ProcessStatus.SCHEDULING, currentStatus: ProcessStatus.NEGOTIATION, changedByName: - `${process.specialist.name} ${process.specialist.surname || ''}`.trim(), + context?.delegated && context.actor + ? `${context.actor.name} ${context.actor.surname}`.trim() + : `${process.specialist.name} ${process.specialist.surname || ''}`.trim(), reason: 'Conversa concluída e processo avançado para negociação.', productDetails: this.getProductDetails(process), }), @@ -361,10 +486,20 @@ export class MeetingsService { }; } - async getMeetingByProcess(processId: string, userId: string) { - const { process } = await this.getAuthorizedProcess(processId, userId); + async getMeetingByProcess( + processId: string, + userId: string, + context?: ActorContext, + ) { + const { process } = await this.getAuthorizedProcess( + processId, + userId, + context, + ); - return process.meeting_session + return process.meeting_session && + !isMeetingInitializationClaim(process.meeting_session) && + !parseReadyMeetingClaim(process.meeting_session) ? this.buildMeetingResponse(process.meeting_session) : null; } @@ -373,11 +508,14 @@ export class MeetingsService { processId: string, userId: string, isAdvanced?: boolean, + context?: ActorContext, ) { - const { process, isSpecialist } = await this.getAuthorizedProcess( + const { isSpecialist } = await this.getAuthorizedProcess( processId, userId, + context, ); + const representedSpecialistId = context?.specialistId ?? userId; if (!isSpecialist) { throw new ForbiddenException( @@ -385,144 +523,354 @@ export class MeetingsService { ); } - const consultant = process.client.consultant; - const consultantEmail = consultant?.email; - const consultantName = consultant - ? `${consultant.name} ${consultant.surname || ''}`.trim() - : undefined; + const reservation = await this.prismaService.$transaction( + async (tx) => { + const candidate = await tx.process.findUnique({ + where: { id: processId }, + select: { id: true, specialist_id: true, removed_at: true }, + }); + if (!candidate || candidate.removed_at) { + throw new NotFoundException('Processo não encontrado'); + } + if (candidate.specialist_id !== representedSpecialistId) { + throw new ForbiddenException( + 'Apenas o especialista pode iniciar a reunião', + ); + } + + await acquireSpecialistScheduleLock(tx, candidate.specialist_id); + + const process = await tx.process.findUnique({ + where: { id: processId }, + include: { + appointment: true, + client: { + select: { + id: true, + email: true, + name: true, + surname: true, + consultant_id: true, + consultant: { + select: { id: true, email: true, name: true, surname: true }, + }, + }, + }, + specialist: { + select: { id: true, email: true, name: true, surname: true }, + }, + meeting_session: true, + }, + }); + if (!process) { + throw new NotFoundException('Processo não encontrado'); + } + this.assertMeetingCanStart(process, representedSpecialistId); + if (process.meeting_session) { + const ready = parseReadyMeetingClaim(process.meeting_session); + if (ready) { + return { + process, + meeting: process.meeting_session, + ready, + created: false, + provider: ready.provider, + }; + } + if (isMeetingInitializationClaim(process.meeting_session)) { + if (!isStaleMeetingInitializationClaim(process.meeting_session)) { + throw new ConflictException( + 'A reunião já está sendo iniciada. Tente novamente em instantes.', + ); + } + await tx.meetingSession.deleteMany({ + where: { + id: process.meeting_session.id, + calendar_event_id: process.meeting_session.calendar_event_id, + }, + }); + } else { + return { + process, + meeting: process.meeting_session, + ready: null, + created: false, + provider: 'EXISTING' as const, + }; + } + } + + const claimId = randomUUID(); + const claimCalendarEventId = `${MEETING_INITIALIZATION_PREFIX}${claimId}`; + const meeting = await tx.meetingSession.create({ + data: { + process_id: process.id, + started_by_id: userId, + calendar_event_id: claimCalendarEventId, + meet_link: '', + started_at: new Date(), + }, + }); - if ( - process.status !== 'SCHEDULING' && - process.status !== 'NEGOTIATION' && - process.status !== 'PROCESSING_CONTRACT' - ) { - throw new BadRequestException( - 'Processo não está em etapa válida para iniciar reunião', - ); - } + return { + process, + meeting, + claimId, + claimCalendarEventId, + ready: null, + created: true, + provider: null, + }; + }, + { maxWait: 10_000, timeout: 30_000 }, + ); - if (process.meeting_session) { - return this.buildMeetingResponse(process.meeting_session); + if (!reservation.created && !reservation.ready) { + return this.buildMeetingResponse(reservation.meeting); } - if (this.meetingProvider === 'JITSI') { - const jitsiLink = this.buildDemoMeetingLink(process.id); - const meeting = await this.prismaService.meetingSession.create({ - data: { - process_id: process.id, - started_by_id: userId, - calendar_event_id: `jitsi-${randomUUID()}`, - meet_link: jitsiLink, - started_at: new Date(), - }, - }); + let ready = reservation.ready; + if (!ready) { + const claimId = reservation.claimId; + const claimCalendarEventId = reservation.claimCalendarEventId; + if (!claimId || !claimCalendarEventId) { + throw new ConflictException('Reserva de reunião inválida'); + } + let meetLink: string; + let calendarEventId: string; + let provider: 'JITSI' | 'GOOGLE' | 'DEMO'; + if (this.meetingProvider === 'JITSI') { + meetLink = this.buildDemoMeetingLink(reservation.process.id); + calendarEventId = `jitsi-${randomUUID()}`; + provider = 'JITSI'; + } else { + try { + const space = await this.createMeetSpace(); + meetLink = space.meetingUri; + calendarEventId = space.spaceName; + provider = 'GOOGLE'; + } catch (error) { + if (!this.demoMeetingFallbackEnabled) { + try { + await this.removeInitializationClaim( + processId, + representedSpecialistId, + claimCalendarEventId, + ); + } catch (cleanupError) { + this.logger.error('Falha ao liberar reserva de reunião', { + processId, + error: + cleanupError instanceof Error + ? cleanupError.message + : 'erro desconhecido', + }); + } + this.logger.error('Falha ao criar sala no Google Meet', { + processId: reservation.process.id, + error: + error instanceof Error ? error.message : 'erro desconhecido', + }); + throw new ServiceUnavailableException( + 'Não foi possível criar a reunião no Google Meet. Verifique a conta conectada nas configurações.', + ); + } + + meetLink = this.buildDemoMeetingLink(reservation.process.id); + calendarEventId = `demo-${randomUUID()}`; + provider = 'DEMO'; + } + } - this.logger.log( - `[meetings] Reunião criada com provedor JITSI para processId=${process.id}`, + const readyCalendarEventId = buildReadyMeetingClaim( + claimId, + provider, + calendarEventId, ); - - setImmediate(() => { - const emailData = { - clientEmail: process.client.email, - clientName: - `${process.client.name} ${process.client.surname || ''}`.trim(), - specialistName: - `${process.specialist.name} ${process.specialist.surname || ''}`.trim(), - processId: process.id, - platformMeetingUrl: `${this.frontendUrl}/processes/${process.id}/meeting`, - meetingLink: jitsiLink, - consultantEmail, - consultantName, - }; - const emailMethod = isAdvanced - ? this.notificationService.sendMeetingAdvancedEmail(emailData) - : this.notificationService.sendMeetingStartedEmail(emailData); - emailMethod.catch((err) => { - this.logger.error('Falha ao enviar e-mail de reunião iniciada', { - processId: process.id, - error: err.message, - }); - }); + const checkpoint = await this.prismaService.meetingSession.updateMany({ + where: { + id: reservation.meeting.id, + process_id: processId, + calendar_event_id: claimCalendarEventId, + meet_link: '', + }, + data: { + calendar_event_id: readyCalendarEventId, + meet_link: meetLink, + }, }); - - return { - ...this.buildMeetingResponse(meeting), - }; + if (checkpoint.count !== 1) { + throw new ConflictException( + 'A reserva da reunião mudou durante a criação. Tente novamente.', + ); + } + ready = { claimId, provider, calendarEventId }; + reservation.meeting.calendar_event_id = readyCalendarEventId; + reservation.meeting.meet_link = meetLink; } + if (!ready) { + throw new ConflictException('Reserva de reunião inválida'); + } + const readyClaim = ready; - const specialistName = - `${process.specialist.name} ${process.specialist.surname || ''}`.trim(); - const clientName = - `${process.client.name} ${process.client.surname || ''}`.trim(); - - let meetLink: string; - let spaceName: string; - try { - const space = await this.createMeetSpace(); - meetLink = space.meetingUri; - spaceName = space.spaceName; - } catch (error) { - if (this.demoMeetingFallbackEnabled) { - const demoLink = this.buildDemoMeetingLink(process.id); - const meeting = await this.prismaService.meetingSession.create({ - data: { - process_id: process.id, - started_by_id: userId, - calendar_event_id: `demo-${randomUUID()}`, - meet_link: demoLink, - started_at: new Date(), + const finalized = await this.prismaService.$transaction( + async (tx) => { + const candidate = await tx.process.findUnique({ + where: { id: processId }, + select: { id: true, specialist_id: true, removed_at: true }, + }); + if (!candidate || candidate.removed_at) { + throw new NotFoundException('Processo não encontrado'); + } + if (candidate.specialist_id !== representedSpecialistId) { + throw new ForbiddenException( + 'Apenas o especialista pode iniciar a reunião', + ); + } + await acquireSpecialistScheduleLock(tx, candidate.specialist_id); + const process = await tx.process.findUnique({ + where: { id: processId }, + include: { + appointment: true, + client: { + select: { + id: true, + email: true, + name: true, + surname: true, + consultant_id: true, + consultant: { + select: { id: true, email: true, name: true, surname: true }, + }, + }, + }, + specialist: { + select: { id: true, email: true, name: true, surname: true }, + }, + meeting_session: true, }, }); - - this.logger.warn( - `[meetings] Fallback DEMO ativado após falha no Google Meet. processId=${process.id}`, - ); - - setImmediate(() => { - const emailData = { - clientEmail: process.client.email, - clientName, - specialistName, - processId: process.id, - platformMeetingUrl: `${this.frontendUrl}/processes/${process.id}/meeting`, - meetingLink: demoLink, - consultantEmail, - consultantName, - }; - const emailMethod = isAdvanced - ? this.notificationService.sendMeetingAdvancedEmail(emailData) - : this.notificationService.sendMeetingStartedEmail(emailData); - emailMethod.catch((err) => { - this.logger.error('Falha ao enviar e-mail de reunião iniciada', { - processId: process.id, - error: err.message, + if (!process) { + throw new NotFoundException('Processo não encontrado'); + } + try { + this.assertMeetingCanStart(process, representedSpecialistId); + } catch (error) { + const invalidReady = parseReadyMeetingClaim(process.meeting_session); + if (invalidReady?.claimId === readyClaim.claimId) { + await tx.meetingSession.deleteMany({ + where: { + id: process.meeting_session!.id, + calendar_event_id: process.meeting_session!.calendar_event_id, + }, }); - }); + } + return { failure: error }; + } + + const currentMeeting = process.meeting_session; + const currentReady = parseReadyMeetingClaim(currentMeeting); + if (!currentReady || currentReady.claimId !== readyClaim.claimId) { + if ( + currentMeeting && + !isMeetingInitializationClaim(currentMeeting) && + !currentReady + ) { + return { + process, + meeting: currentMeeting, + created: false, + provider: 'EXISTING' as const, + }; + } + throw new ConflictException( + 'A reserva da reunião mudou durante a finalização. Tente novamente.', + ); + } + if (!currentMeeting) { + throw new ConflictException( + 'A reserva da reunião não existe mais. Tente novamente.', + ); + } + + const update = await tx.meetingSession.updateMany({ + where: { + id: currentMeeting.id, + calendar_event_id: currentMeeting.calendar_event_id, + }, + data: { calendar_event_id: readyClaim.calendarEventId }, }); + if (update.count !== 1) { + const current = await tx.meetingSession.findUnique({ + where: { process_id: processId }, + }); + if (current && !parseReadyMeetingClaim(current)) { + return { + process, + meeting: current, + created: false, + provider: 'EXISTING' as const, + }; + } + throw new ConflictException( + 'A reunião mudou durante a finalização. Tente novamente.', + ); + } + + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'MEETING_START', + resourceType: 'MEETING', + resourceId: currentMeeting.id, + metadata: { processId }, + }, + tx, + ); + } return { - ...this.buildMeetingResponse(meeting), + process, + meeting: { + ...currentMeeting, + calendar_event_id: readyClaim.calendarEventId, + }, + created: true, + provider: readyClaim.provider, }; - } + }, + { maxWait: 10_000, timeout: 30_000 }, + ); - this.logger.error('Falha ao criar sala no Google Meet', { - processId: process.id, - error: error instanceof Error ? error.message : 'erro desconhecido', - }); - throw new ServiceUnavailableException( - 'Não foi possível criar a reunião no Google Meet. Verifique a conta conectada nas configurações.', + if ('failure' in finalized) { + throw finalized.failure; + } + + if (!finalized.created) { + return this.buildMeetingResponse(finalized.meeting); + } + + const { process, meeting, provider } = finalized; + if (provider === 'JITSI') { + this.logger.log( + `[meetings] Reunião criada com provedor JITSI para processId=${process.id}`, + ); + } else if (provider === 'DEMO') { + this.logger.warn( + `[meetings] Fallback DEMO ativado após falha no Google Meet. processId=${process.id}`, ); } - const meeting = await this.prismaService.meetingSession.create({ - data: { - process_id: process.id, - started_by_id: userId, - calendar_event_id: spaceName, - meet_link: meetLink, - started_at: new Date(), - }, - }); + const consultant = process.client.consultant; + const consultantEmail = consultant?.email; + const consultantName = consultant + ? `${consultant.name} ${consultant.surname || ''}`.trim() + : undefined; + const specialistName = + `${process.specialist.name} ${process.specialist.surname || ''}`.trim(); + const clientName = + `${process.client.name} ${process.client.surname || ''}`.trim(); setImmediate(() => { const emailData = { @@ -531,7 +879,7 @@ export class MeetingsService { specialistName, processId: process.id, platformMeetingUrl: `${this.frontendUrl}/processes/${process.id}/meeting`, - meetingLink: meetLink, + meetingLink: meeting.meet_link, consultantEmail, consultantName, }; @@ -549,10 +897,15 @@ export class MeetingsService { return this.buildMeetingResponse(meeting); } - async endMeetingForProcess(processId: string, userId: string) { + async endMeetingForProcess( + processId: string, + userId: string, + context?: ActorContext, + ) { const { process, isSpecialist } = await this.getAuthorizedProcess( processId, userId, + context, ); if (!isSpecialist) { @@ -565,6 +918,15 @@ export class MeetingsService { throw new NotFoundException('Reunião não encontrada para este processo'); } + if ( + isMeetingInitializationClaim(process.meeting_session) || + parseReadyMeetingClaim(process.meeting_session) + ) { + throw new ConflictException( + 'A reunião ainda está sendo iniciada. Tente novamente em instantes.', + ); + } + if (process.meeting_session.ended_at) { return { meeting: this.buildMeetingResponse(process.meeting_session), @@ -573,26 +935,58 @@ export class MeetingsService { }; } - const meeting = await this.prismaService.meetingSession.update({ - where: { id: process.meeting_session.id }, - data: { - ended_at: new Date(), - ended_by_id: userId, - }, + const meetingId = process.meeting_session.id; + const endClaim = await this.prismaService.$transaction(async (tx) => { + await acquireSpecialistScheduleLock(tx, process.specialist_id); + const endedAt = new Date(); + const claim = await tx.meetingSession.updateMany({ + where: { id: meetingId, ended_at: null }, + data: { ended_at: endedAt, ended_by_id: userId }, + }); + const meeting = await tx.meetingSession.findUnique({ + where: { id: meetingId }, + }); + if (!meeting) { + throw new NotFoundException('Reunião não encontrada para este processo'); + } + if (claim.count === 1 && context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'MEETING_END', + resourceType: 'MEETING', + resourceId: meeting.id, + metadata: { processId }, + }, + tx, + ); + } + return { meeting, claimed: claim.count === 1 }; }); return { - meeting: this.buildMeetingResponse(meeting), - alreadyEnded: false, - message: 'Reunião encerrada com sucesso.', + meeting: this.buildMeetingResponse(endClaim.meeting), + alreadyEnded: !endClaim.claimed, + message: endClaim.claimed + ? 'Reunião encerrada com sucesso.' + : 'Reunião já estava encerrada.', }; } - async markConversationDone(processId: string, userId: string) { - const endResult = await this.endMeetingForProcess(processId, userId); + async markConversationDone( + processId: string, + userId: string, + context?: ActorContext, + ) { + const endResult = await this.endMeetingForProcess( + processId, + userId, + context, + ); const transition = await this.advanceProcessAfterConversation( processId, userId, + context, ); return { diff --git a/backend/src/features/notifications/dto/notification-email.dto.ts b/backend/src/features/notifications/dto/notification-email.dto.ts index ebe8fec7..5c1f0397 100644 --- a/backend/src/features/notifications/dto/notification-email.dto.ts +++ b/backend/src/features/notifications/dto/notification-email.dto.ts @@ -130,8 +130,8 @@ export interface ProcessStatusChangedEmailDto { export interface ContractSignedEmailDto { buyerEmail: string; buyerName: string; - sellerEmail: string; - sellerName: string; + sellerEmail?: string; + sellerName?: string; contractId: string; vehicleModel: string; finalPrice: number; @@ -141,8 +141,8 @@ export interface ContractSignedEmailDto { export interface ContractGeneratedEmailDto { buyerEmail: string; buyerName: string; - sellerEmail: string; - sellerName: string; + sellerEmail?: string; + sellerName?: string; contractId: string; vehicleDetails: string; processId: string; @@ -151,8 +151,8 @@ export interface ContractGeneratedEmailDto { export interface ContractSentEmailDto { buyerEmail: string; buyerName: string; - sellerEmail: string; - sellerName: string; + sellerEmail?: string; + sellerName?: string; docusignLink: string; contractId: string; } diff --git a/backend/src/features/notifications/notification.service.spec.ts b/backend/src/features/notifications/notification.service.spec.ts index dc661d14..9412d029 100644 --- a/backend/src/features/notifications/notification.service.spec.ts +++ b/backend/src/features/notifications/notification.service.spec.ts @@ -22,6 +22,34 @@ describe('NotificationService proposal emails', () => { .mockResolvedValue(undefined); }); + it('notifica só o comprador quando não há vendedor no contrato', async () => { + const parties = { buyerEmail: 'buyer@example.test', buyerName: 'Comprador' }; + await service.sendContractGeneratedEmail({ + ...parties, + contractId: 'contract-1', + vehicleDetails: 'Carro 2026', + processId: 'process-1', + }); + await service.sendContractSentEmail({ + ...parties, + contractId: 'contract-1', + docusignLink: 'https://demo.docusign.net/view', + }); + await service.sendContractSignedEmail({ + ...parties, + contractId: 'contract-1', + vehicleModel: 'Carro', + finalPrice: 100000, + }); + + expect(sendEmailSafely).toHaveBeenCalledTimes(3); + for (const [, recipient, , html, plainText] of sendEmailSafely.mock.calls) { + expect(recipient).toBe('buyer@example.test'); + expect(html).not.toContain('Vendedor:'); + expect(plainText).not.toContain('Vendedor:'); + } + }); + it('uses USD in the received proposal HTML and plain-text bodies', async () => { await service.sendProposalReceivedEmail({ recipientEmail: 'buyer@example.com', @@ -173,4 +201,24 @@ describe('NotificationService proposal emails', () => { expect(htmlBody).not.toContain('alert(1)'); }); + + it('escapes user-controlled fields in process status HTML', async () => { + await service.sendProcessStatusChangedEmail({ + recipientEmail: 'client@example.com', + recipientName: '', + processId: 'process-1', + previousStatus: 'SCHEDULING', + currentStatus: 'REJECTED', + changedByName: 'Actor', + productDetails: 'Product', + reason: '', + }); + + const htmlBody = sendEmailSafely.mock.calls[0][3]; + expect(htmlBody).toContain('<img'); + expect(htmlBody).toContain('<b>Actor</b>'); + expect(htmlBody).toContain('<i>Product</i>'); + expect(htmlBody).toContain('<script>alert(1)</script>'); + expect(htmlBody).not.toContain(''); + }); }); diff --git a/backend/src/features/notifications/notification.service.ts b/backend/src/features/notifications/notification.service.ts index d35c62aa..05420b4c 100644 --- a/backend/src/features/notifications/notification.service.ts +++ b/backend/src/features/notifications/notification.service.ts @@ -679,7 +679,9 @@ Acesse ${this.frontendUrl}/processes/${data.processId}/negotiation para responde // Send to both parties - use Promise.allSettled to ensure one failure doesn't block the other await Promise.allSettled([ this.sendContractSignedEmailToParty(data, 'buyer', subject), - this.sendContractSignedEmailToParty(data, 'seller', subject), + ...(data.sellerEmail && data.sellerName + ? [this.sendContractSignedEmailToParty(data, 'seller', subject)] + : []), ]); } @@ -689,8 +691,8 @@ Acesse ${this.frontendUrl}/processes/${data.processId}/negotiation para responde subject: string, ): Promise { const isBuyer = role === 'buyer'; - const recipientName = isBuyer ? data.buyerName : data.sellerName; - const recipientEmail = isBuyer ? data.buyerEmail : data.sellerEmail; + const recipientName = isBuyer ? data.buyerName : data.sellerName!; + const recipientEmail = isBuyer ? data.buyerEmail : data.sellerEmail!; const otherPartyName = isBuyer ? data.sellerName : data.buyerName; const html = ` @@ -710,7 +712,7 @@ Acesse ${this.frontendUrl}/processes/${data.processId}/negotiation para responde

Veículo: ${data.vehicleModel}

Valor Final: R$ ${data.finalPrice.toLocaleString('pt-BR', { minimumFractionDigits: 2 })}

-

${isBuyer ? 'Vendedor' : 'Comprador'}: ${otherPartyName}

+ ${otherPartyName ? `

${isBuyer ? 'Vendedor' : 'Comprador'}: ${otherPartyName}

` : ''}

Contrato ID: ${data.contractId}

${ @@ -751,7 +753,7 @@ O contrato foi assinado por todas as partes e a transação está concluída. Veículo: ${data.vehicleModel} Valor Final: R$ ${data.finalPrice.toLocaleString('pt-BR', { minimumFractionDigits: 2 })} -${isBuyer ? 'Vendedor' : 'Comprador'}: ${otherPartyName} +${otherPartyName ? `${isBuyer ? 'Vendedor' : 'Comprador'}: ${otherPartyName}` : ''} Contrato ID: ${data.contractId} ${data.signedPdfUrl ? `Baixar contrato: ${data.signedPdfUrl}` : ''} @@ -1473,6 +1475,20 @@ Acesse ${this.frontendUrl}/processes/${data.processId}/negotiation para continua const previousStatusLabel = data.previousStatus ? (statusLabelMap[data.previousStatus] ?? data.previousStatus) : undefined; + const recipientName = escapeHtml(data.recipientName); + const safeProcessId = escapeHtml(data.processId); + const safePreviousStatusLabel = previousStatusLabel + ? escapeHtml(previousStatusLabel) + : undefined; + const safeCurrentStatusLabel = escapeHtml(currentStatusLabel); + const changedByName = data.changedByName + ? escapeHtml(data.changedByName) + : undefined; + const productDetails = data.productDetails + ? escapeHtml(data.productDetails) + : undefined; + const reason = data.reason ? escapeHtml(data.reason) : undefined; + const processPath = encodeURIComponent(data.processId); const subject = `Atualização no Processo #${data.processId.slice(0, 8)} | BMF Lux Brokerage`; @@ -1486,18 +1502,18 @@ Acesse ${this.frontendUrl}/processes/${data.processId}/negotiation para continua

Atualização de Processo

-

Olá ${data.recipientName},

+

Olá ${recipientName},

Houve uma atualização importante no seu processo.

-

Processo: ${data.processId}

- ${previousStatusLabel ? `

Status anterior: ${previousStatusLabel}

` : ''} -

Novo status: ${currentStatusLabel}

- ${data.changedByName ? `

Atualizado por: ${data.changedByName}

` : ''} - ${data.productDetails ? `

Produto: ${data.productDetails}

` : ''} - ${data.reason ? `

Detalhes: ${data.reason}

` : ''} +

Processo: ${safeProcessId}

+ ${safePreviousStatusLabel ? `

Status anterior: ${safePreviousStatusLabel}

` : ''} +

Novo status: ${safeCurrentStatusLabel}

+ ${changedByName ? `

Atualizado por: ${changedByName}

` : ''} + ${productDetails ? `

Produto: ${productDetails}

` : ''} + ${reason ? `

Detalhes: ${reason}

` : ''}
- @@ -1573,7 +1589,9 @@ Acesse ${this.frontendUrl}/processes/${data.processId} para acompanhar. // Send to both parties await Promise.allSettled([ this.sendContractGeneratedToParty(data, 'buyer', subject), - this.sendContractGeneratedToParty(data, 'seller', subject), + ...(data.sellerEmail && data.sellerName + ? [this.sendContractGeneratedToParty(data, 'seller', subject)] + : []), ]); } @@ -1583,8 +1601,8 @@ Acesse ${this.frontendUrl}/processes/${data.processId} para acompanhar. subject: string, ): Promise { const isBuyer = role === 'buyer'; - const recipientName = isBuyer ? data.buyerName : data.sellerName; - const recipientEmail = isBuyer ? data.buyerEmail : data.sellerEmail; + const recipientName = isBuyer ? data.buyerName : data.sellerName!; + const recipientEmail = isBuyer ? data.buyerEmail : data.sellerEmail!; const otherPartyName = isBuyer ? data.sellerName : data.buyerName; const html = ` @@ -1603,7 +1621,7 @@ Acesse ${this.frontendUrl}/processes/${data.processId} para acompanhar.

Veículo: ${data.vehicleDetails}

-

${isBuyer ? 'Vendedor' : 'Comprador'}: ${otherPartyName}

+ ${otherPartyName ? `

${isBuyer ? 'Vendedor' : 'Comprador'}: ${otherPartyName}

` : ''}

Contrato ID: ${data.contractId}

@@ -1633,7 +1651,7 @@ Olá ${recipientName}, O contrato de compra e venda foi gerado com sucesso! Veículo: ${data.vehicleDetails} -${isBuyer ? 'Vendedor' : 'Comprador'}: ${otherPartyName} +${otherPartyName ? `${isBuyer ? 'Vendedor' : 'Comprador'}: ${otherPartyName}` : ''} Contrato ID: ${data.contractId} Em breve você receberá um email do DocuSign com o link para assinatura eletrônica. @@ -1669,7 +1687,9 @@ Acesse ${this.frontendUrl}/processes/${data.processId} para acompanhar. // Send to both parties await Promise.allSettled([ this.sendContractSentToParty(data, 'buyer', subject), - this.sendContractSentToParty(data, 'seller', subject), + ...(data.sellerEmail && data.sellerName + ? [this.sendContractSentToParty(data, 'seller', subject)] + : []), ]); } @@ -1679,8 +1699,8 @@ Acesse ${this.frontendUrl}/processes/${data.processId} para acompanhar. subject: string, ): Promise { const isBuyer = role === 'buyer'; - const recipientName = isBuyer ? data.buyerName : data.sellerName; - const recipientEmail = isBuyer ? data.buyerEmail : data.sellerEmail; + const recipientName = isBuyer ? data.buyerName : data.sellerName!; + const recipientEmail = isBuyer ? data.buyerEmail : data.sellerEmail!; const otherPartyName = isBuyer ? data.sellerName : data.buyerName; const html = ` @@ -1698,7 +1718,7 @@ Acesse ${this.frontendUrl}/processes/${data.processId} para acompanhar. O contrato está pronto e aguardando sua assinatura eletrônica via DocuSign.

-

${isBuyer ? 'Vendedor' : 'Comprador'}: ${otherPartyName}

+ ${otherPartyName ? `

${isBuyer ? 'Vendedor' : 'Comprador'}: ${otherPartyName}

` : ''}

Contrato ID: ${data.contractId}

@@ -1730,7 +1750,7 @@ Olá ${recipientName}, O contrato está pronto e aguardando sua assinatura eletrônica via DocuSign. -${isBuyer ? 'Vendedor' : 'Comprador'}: ${otherPartyName} +${otherPartyName ? `${isBuyer ? 'Vendedor' : 'Comprador'}: ${otherPartyName}` : ''} Contrato ID: ${data.contractId} Acesse o link abaixo para assinar: diff --git a/backend/src/features/office/office.service.ts b/backend/src/features/office/office.service.ts index 53aac85e..da973465 100644 --- a/backend/src/features/office/office.service.ts +++ b/backend/src/features/office/office.service.ts @@ -134,6 +134,7 @@ export class OfficeService { this.prisma.process.count({ where: { status: { notIn: [ProcessStatus.COMPLETED, ProcessStatus.REJECTED] }, + removed_at: null, client: { OR: [ { consultant: { company_id: companyId } }, @@ -252,6 +253,7 @@ export class OfficeService { where: { client: { consultant_id: consultantId }, status: { notIn: [ProcessStatus.COMPLETED, ProcessStatus.REJECTED] }, + removed_at: null, }, }); if (activeProcesses > 0) { diff --git a/backend/src/features/processes/dto/get-processes-filter.dto.spec.ts b/backend/src/features/processes/dto/get-processes-filter.dto.spec.ts new file mode 100644 index 00000000..824d8878 --- /dev/null +++ b/backend/src/features/processes/dto/get-processes-filter.dto.spec.ts @@ -0,0 +1,28 @@ +import { ArgumentMetadata, ValidationPipe } from '@nestjs/common'; +import { GetProcessesFilterDto } from './get-processes-filter.dto'; + +describe('GetProcessesFilterDto', () => { + const pipe = new ValidationPipe({ + transform: true, + whitelist: true, + forbidNonWhitelisted: true, + }); + const metadata: ArgumentMetadata = { + type: 'query', + metatype: GetProcessesFilterDto, + data: undefined, + }; + + it('accepts the represented specialist query parameter', async () => { + const specialistId = 'b11d0000-0000-4000-8000-000000000002'; + await expect( + pipe.transform({ target_specialist_id: specialistId, page: '1' }, metadata), + ).resolves.toMatchObject({ target_specialist_id: specialistId, page: 1 }); + }); + + it('rejects a malformed represented specialist id', async () => { + await expect( + pipe.transform({ target_specialist_id: 'another-specialist' }, metadata), + ).rejects.toThrow(); + }); +}); diff --git a/backend/src/features/processes/dto/get-processes-filter.dto.ts b/backend/src/features/processes/dto/get-processes-filter.dto.ts index efa2c172..19d7bef9 100644 --- a/backend/src/features/processes/dto/get-processes-filter.dto.ts +++ b/backend/src/features/processes/dto/get-processes-filter.dto.ts @@ -1,4 +1,4 @@ -import { IsOptional, IsEnum, IsString, MaxLength } from 'class-validator'; +import { IsOptional, IsEnum, IsString, IsUUID, MaxLength } from 'class-validator'; import { Transform, Type } from 'class-transformer'; import { ProcessStatus } from '@prisma/client'; @@ -7,6 +7,10 @@ import { ProcessStatus } from '@prisma/client'; * Usado em GET /api/processes/specialist/:id */ export class GetProcessesFilterDto { + @IsOptional() + @IsUUID() + target_specialist_id?: string; + @IsOptional() @Type(() => Number) page?: number; diff --git a/backend/src/features/processes/entity/process.response.entity.ts b/backend/src/features/processes/entity/process.response.entity.ts index b55f96fa..b03421bb 100644 --- a/backend/src/features/processes/entity/process.response.entity.ts +++ b/backend/src/features/processes/entity/process.response.entity.ts @@ -6,9 +6,7 @@ export class ProcessResponse { appointment_id?: string | null; appointment_status?: $Enums.StatusAgendamento | null; appointment_datetime?: Date | null; - appointment_scheduling_method?: - | $Enums.AppointmentSchedulingMethod - | null; + appointment_scheduling_method?: $Enums.AppointmentSchedulingMethod | null; specialist_rescheduled_at?: Date | null; specialist_rescheduled_from?: Date | null; product_type: $Enums.ProductType | null; // Null para processos de consultoria @@ -16,7 +14,7 @@ export class ProcessResponse { client: { id: string; name: string; - email: string; + email?: string; phone?: string | null; }; specialist: { diff --git a/backend/src/features/processes/process-dedup-lock.spec.ts b/backend/src/features/processes/process-dedup-lock.spec.ts index f2e15f8b..1bfec01b 100644 --- a/backend/src/features/processes/process-dedup-lock.spec.ts +++ b/backend/src/features/processes/process-dedup-lock.spec.ts @@ -1,6 +1,14 @@ import { ConflictException } from '@nestjs/common'; -import { ProductType } from '@prisma/client'; -import { assertNoActiveProcess } from './process-dedup-lock'; +import { + AppointmentSchedulingMethod, + CalendlySyncStatus, + ProductType, + StatusAgendamento, +} from '@prisma/client'; +import { + assertNoActiveProcess, + lockAndAssertNoActiveProcess, +} from './process-dedup-lock'; describe('assertNoActiveProcess', () => { it('returns a stable error code when an active product process exists', async () => { @@ -31,3 +39,163 @@ describe('assertNoActiveProcess', () => { }); }); }); + +describe('own active process snapshot', () => { + const scope = { + clientId: 'client-1', + specialistId: 'specialist-1', + productType: ProductType.CAR, + productId: 'car-1', + }; + const options = { authenticatedClientId: scope.clientId }; + const appointment = { + id: 'appointment-1', + client_id: scope.clientId, + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + calendly_sync_status: CalendlySyncStatus.PENDING, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + client: { email: 'private@example.com', phone: 'private-phone' }, + }; + function harness(existing: any) { + const tx = { + $queryRaw: jest.fn().mockResolvedValue([]), + process: { findFirst: jest.fn().mockResolvedValue(existing) }, + }; + return tx; + } + async function response( + tx: any, + actorOptions: any = options, + exclude?: string, + ) { + const error = await (assertNoActiveProcess as any)( + tx, + scope, + exclude, + actorOptions, + ).catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(ConflictException); + return error.getResponse(); + } + + it.each([null, appointment])( + 'returns the exact owned snapshot with appointment %o', + async (attached) => { + const tx = harness({ + id: 'process-1', + client_id: scope.clientId, + appointment: attached, + specialist: { email: 'specialist@example.com' }, + notes: 'private-notes', + }); + expect(await response(tx)).toEqual({ + success: false, + error: { + code: 'ACTIVE_PROCESS_EXISTS', + message: expect.any(String), + details: { + existing_request: { + process_id: 'process-1', + appointment_id: attached?.id ?? null, + appointment_status: attached?.status ?? null, + scheduling_method: attached?.scheduling_method ?? null, + appointment_datetime: attached?.appointment_datetime ?? null, + ...(attached + ? { specialist_contact_email: 'specialist@example.com' } + : {}), + }, + }, + }, + }); + expect(tx.process.findFirst).toHaveBeenCalledWith({ + where: expect.objectContaining({ client_id: scope.clientId }), + select: { + id: true, + client_id: true, + appointment: { + select: { + id: true, + client_id: true, + status: true, + scheduling_method: true, + appointment_datetime: true, + }, + }, + specialist: { select: { email: true } }, + }, + }); + }, + ); + + it('does not reveal details without the authenticated client opt-in', async () => { + const tx = harness({ + id: 'process-1', + client_id: scope.clientId, + appointment, + }); + const error = await assertNoActiveProcess(tx, scope).catch( + (caught) => caught, + ); + expect(error.getResponse().error).not.toHaveProperty('details'); + }); + + it.each([ + ['another-client', scope.clientId], + [scope.clientId, 'another-client'], + ])( + 'does not reveal details when actor %s or stored owner %s differs', + async (actorId, storedId) => { + const result = await response( + harness({ id: 'process-1', client_id: storedId, appointment }), + { authenticatedClientId: actorId }, + ); + expect(result.error).not.toHaveProperty('details'); + }, + ); + + it('nulls all appointment fields when the linked appointment belongs to someone else', async () => { + const result = await response( + harness({ + id: 'process-1', + client_id: scope.clientId, + appointment: { ...appointment, client_id: 'another-client' }, + }), + ); + expect(result.error.details.existing_request).toEqual({ + process_id: 'process-1', + appointment_id: null, + appointment_status: null, + scheduling_method: null, + appointment_datetime: null, + }); + }); + + it('forwards options and exclusions through the lock wrapper before reading', async () => { + const tx = harness({ + id: 'process-1', + client_id: scope.clientId, + appointment, + }); + const error = await (lockAndAssertNoActiveProcess as any)( + tx, + scope, + 'excluded-process', + options, + ).catch((caught: unknown) => caught); + expect(error.getResponse().error.details.existing_request.process_id).toBe( + 'process-1', + ); + expect(tx.process.findFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ id: { not: 'excluded-process' } }), + }), + ); + expect(tx.$queryRaw.mock.invocationCallOrder[0]).toBeLessThan( + tx.process.findFirst.mock.invocationCallOrder[0], + ); + expect(JSON.stringify(error.getResponse())).not.toMatch( + /private@example.com|private-phone|private-notes|client_id/, + ); + }); +}); diff --git a/backend/src/features/processes/process-dedup-lock.ts b/backend/src/features/processes/process-dedup-lock.ts index e37732b3..43b1b985 100644 --- a/backend/src/features/processes/process-dedup-lock.ts +++ b/backend/src/features/processes/process-dedup-lock.ts @@ -1,5 +1,10 @@ import { ConflictException } from '@nestjs/common'; -import { ProcessStatus, ProductType } from '@prisma/client'; +import { + AppointmentSchedulingMethod, + ProcessStatus, + ProductType, +} from '@prisma/client'; +import type { ActiveProcessSnapshot } from '../appointments/entities/appointment.response'; export const ACTIVE_PROCESS_STATUSES: ProcessStatus[] = [ ProcessStatus.SCHEDULING, @@ -15,12 +20,17 @@ export type ActiveProcessScope = { productId?: string | null; }; -const PRODUCT_FIELD: Record = { - [ProductType.CAR]: 'car_id', - [ProductType.BOAT]: 'boat_id', - [ProductType.AIRCRAFT]: 'aircraft_id', +type ActiveProcessConflictOptions = { + authenticatedClientId?: string; }; +const PRODUCT_FIELD: Record = + { + [ProductType.CAR]: 'car_id', + [ProductType.BOAT]: 'boat_id', + [ProductType.AIRCRAFT]: 'aircraft_id', + }; + export function activeProcessDedupKey(scope: ActiveProcessScope): string { const isConsultancy = !scope.productType || !scope.productId; return `process-dedup:${scope.clientId}:${scope.specialistId}:${isConsultancy ? 'CONSULTANCY' : scope.productType}:${isConsultancy ? 'none' : scope.productId}`; @@ -40,6 +50,7 @@ export async function assertNoActiveProcess( tx: any, scope: ActiveProcessScope, excludeProcessId?: string, + options?: ActiveProcessConflictOptions, ): Promise { const isConsultancy = !scope.productType || !scope.productId; const where: Record = isConsultancy @@ -47,18 +58,55 @@ export async function assertNoActiveProcess( client_id: scope.clientId, specialist_id: scope.specialistId, product_type: null, + removed_at: null, status: { in: ACTIVE_PROCESS_STATUSES }, } : { client_id: scope.clientId, specialist_id: scope.specialistId, [PRODUCT_FIELD[scope.productType!]]: scope.productId, + removed_at: null, status: { in: ACTIVE_PROCESS_STATUSES }, }; if (excludeProcessId) where.id = { not: excludeProcessId }; - const existing = await tx.process.findFirst({ where }); + const existing = await tx.process.findFirst({ + where, + select: { + id: true, + client_id: true, + appointment: { + select: { + id: true, + client_id: true, + status: true, + scheduling_method: true, + appointment_datetime: true, + }, + }, + specialist: { select: { email: true } }, + }, + }); if (existing) { + const owned = + options?.authenticatedClientId !== undefined && + options.authenticatedClientId === scope.clientId && + existing.client_id === scope.clientId; + const appointment = + owned && existing.appointment?.client_id === scope.clientId + ? existing.appointment + : null; + const snapshot: ActiveProcessSnapshot = { + process_id: existing.id, + appointment_id: appointment?.id ?? null, + appointment_status: appointment?.status ?? null, + scheduling_method: appointment?.scheduling_method ?? null, + appointment_datetime: appointment?.appointment_datetime ?? null, + ...(appointment?.scheduling_method === + AppointmentSchedulingMethod.EMAIL && existing.specialist?.email + ? { specialist_contact_email: existing.specialist.email } + : {}), + }; throw new ConflictException({ success: false, error: { @@ -66,6 +114,7 @@ export async function assertNoActiveProcess( message: isConsultancy ? 'Já existe consultoria ativa entre este cliente e este especialista.' : 'Já existe processo ativo para este cliente com este produto.', + ...(owned ? { details: { existing_request: snapshot } } : {}), }, }); } @@ -75,7 +124,8 @@ export async function lockAndAssertNoActiveProcess( tx: any, scope: ActiveProcessScope, excludeProcessId?: string, + options?: ActiveProcessConflictOptions, ): Promise { await acquireActiveProcessDedupLock(tx, scope); - await assertNoActiveProcess(tx, scope, excludeProcessId); + await assertNoActiveProcess(tx, scope, excludeProcessId, options); } diff --git a/backend/src/features/processes/processes-dedup-concurrency.postgres.spec.ts b/backend/src/features/processes/processes-dedup-concurrency.postgres.spec.ts index f3703174..6973f3e3 100644 --- a/backend/src/features/processes/processes-dedup-concurrency.postgres.spec.ts +++ b/backend/src/features/processes/processes-dedup-concurrency.postgres.spec.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto'; import { ConflictException } from '@nestjs/common'; -import { PrismaClient, UserRole } from '@prisma/client'; +import { PrismaClient, ProcessStatus, UserRole } from '@prisma/client'; import { ProcessesService } from './processes.service'; type Deferred = { promise: Promise; resolve: () => void }; @@ -52,239 +52,388 @@ function signalDedupLockAttempt(client: PrismaClient, attempted: Deferred) { const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL; const describeWithPostgres = databaseUrl ? describe : describe.skip; -describeWithPostgres('process active dedup lock — PostgreSQL concurrency', () => { - const suffix = randomUUID().replaceAll('-', ''); - const clientId = randomUUID(); - const specialistId = randomUUID(); - const first = new PrismaClient({ - datasources: { db: { url: withApplicationName(databaseUrl!, `dedup_a_${suffix}`) } }, - }); - const second = new PrismaClient({ - datasources: { db: { url: withApplicationName(databaseUrl!, `dedup_b_${suffix}`) } }, - }); - const holder = new PrismaClient({ - datasources: { db: { url: withApplicationName(databaseUrl!, `dedup_holder_${suffix}`) } }, - }); - - beforeAll(async () => { - await holder.user.createMany({ - data: [ - { - id: clientId, - name: 'Dedup', - surname: 'Client', - email: `dedup-client-${suffix}@example.test`, - rg: suffix.slice(0, 11), - role: UserRole.CUSTOMER, - password_hash: 'not-used', - }, - { - id: specialistId, - name: 'Dedup', - surname: 'Specialist', - email: `dedup-specialist-${suffix}@example.test`, - rg: suffix.slice(11, 22), - role: UserRole.SPECIALIST, - password_hash: 'not-used', +describeWithPostgres( + 'process active dedup lock — PostgreSQL concurrency', + () => { + const suffix = randomUUID().replaceAll('-', ''); + const clientId = randomUUID(); + const specialistId = randomUUID(); + const otherSpecialistId = randomUUID(); + const first = new PrismaClient({ + datasources: { + db: { url: withApplicationName(databaseUrl!, `dedup_a_${suffix}`) }, + }, + }); + const second = new PrismaClient({ + datasources: { + db: { url: withApplicationName(databaseUrl!, `dedup_b_${suffix}`) }, + }, + }); + const holder = new PrismaClient({ + datasources: { + db: { + url: withApplicationName(databaseUrl!, `dedup_holder_${suffix}`), }, - ], + }, }); - }); - beforeEach(async () => { - const processes = await holder.process.findMany({ - where: { client_id: clientId, specialist_id: specialistId }, - select: { id: true, appointment_id: true }, + beforeAll(async () => { + await holder.user.createMany({ + data: [ + { + id: clientId, + name: 'Dedup', + surname: 'Client', + email: `dedup-client-${suffix}@example.test`, + rg: suffix.slice(0, 11), + role: UserRole.CUSTOMER, + password_hash: 'not-used', + }, + { + id: specialistId, + name: 'Dedup', + surname: 'Specialist', + email: `dedup-specialist-${suffix}@example.test`, + rg: suffix.slice(11, 22), + role: UserRole.SPECIALIST, + password_hash: 'not-used', + }, + { + id: otherSpecialistId, + name: 'Other', + surname: 'Specialist', + email: `dedup-other-specialist-${suffix}@example.test`, + rg: suffix.slice(22, 32), + role: UserRole.SPECIALIST, + password_hash: 'not-used', + }, + ], + }); }); - await holder.processStatusHistory.deleteMany({ - where: { processId: { in: processes.map(({ id }) => id) } }, + + beforeEach(async () => { + const processes = await holder.process.findMany({ + where: { client_id: clientId }, + select: { id: true, appointment_id: true }, + }); + await holder.processStatusHistory.deleteMany({ + where: { processId: { in: processes.map(({ id }) => id) } }, + }); + await holder.process.deleteMany({ + where: { id: { in: processes.map(({ id }) => id) } }, + }); + await holder.appointment.deleteMany({ + where: { + id: { + in: processes.flatMap(({ appointment_id }) => + appointment_id ? [appointment_id] : [], + ), + }, + }, + }); }); - await holder.process.deleteMany({ - where: { id: { in: processes.map(({ id }) => id) } }, + + afterAll(async () => { + const processes = await holder.process.findMany({ + where: { client_id: clientId }, + select: { id: true, appointment_id: true }, + }); + await holder.processStatusHistory.deleteMany({ + where: { processId: { in: processes.map(({ id }) => id) } }, + }); + await holder.process.deleteMany({ + where: { id: { in: processes.map(({ id }) => id) } }, + }); + await holder.appointment.deleteMany({ + where: { + id: { + in: processes.flatMap(({ appointment_id }) => + appointment_id ? [appointment_id] : [], + ), + }, + }, + }); + await holder.user.deleteMany({ + where: { id: { in: [clientId, specialistId, otherSpecialistId] } }, + }); + await Promise.all([ + first.$disconnect(), + second.$disconnect(), + holder.$disconnect(), + ]); }); - await holder.appointment.deleteMany({ - where: { - id: { - in: processes.flatMap(({ appointment_id }) => - appointment_id ? [appointment_id] : [], + + it.each(['completed appointment', 'legacy without appointment'] as const)( + 'rejects create-on-behalf when an active consultancy already exists with %s', + async (fixture) => { + const appointment = + fixture === 'completed appointment' + ? await holder.appointment.create({ + data: { + client_id: clientId, + specialist_id: specialistId, + status: 'COMPLETED', + scheduling_method: 'EMAIL', + appointment_datetime: new Date('2026-01-01T10:00:00.000Z'), + }, + }) + : null; + await holder.process.create({ + data: { + client_id: clientId, + specialist_id: specialistId, + appointment_id: appointment?.id, + status: ProcessStatus.SCHEDULING, + }, + }); + + await expect( + new ProcessesService(holder as any, {} as any).createOnBehalfOfClient( + { + client_id: clientId, + specialist_id: specialistId, + product_type: 'CAR', + product_id: undefined, + createdBy: specialistId, + actorLabel: 'consultor', + }, ), - }, + ).rejects.toThrow(ConflictException); + + await expect( + holder.process.count({ + where: { + client_id: clientId, + specialist_id: specialistId, + status: ProcessStatus.SCHEDULING, + }, + }), + ).resolves.toBe(1); }, - }); - }); + 15_000, + ); - afterAll(async () => { - const processes = await holder.process.findMany({ - where: { client_id: clientId, specialist_id: specialistId }, - select: { id: true, appointment_id: true }, - }); - await holder.processStatusHistory.deleteMany({ - where: { processId: { in: processes.map(({ id }) => id) } }, - }); - await holder.process.deleteMany({ where: { id: { in: processes.map(({ id }) => id) } } }); - await holder.appointment.deleteMany({ - where: { id: { in: processes.flatMap(({ appointment_id }) => appointment_id ? [appointment_id] : []) } }, + it('returns only the assigned specialist processes in both rows and count', async () => { + const own = await holder.process.create({ + data: { + client_id: clientId, + specialist_id: specialistId, + status: ProcessStatus.SCHEDULING, + }, + }); + await holder.process.create({ + data: { + client_id: clientId, + specialist_id: otherSpecialistId, + status: ProcessStatus.SCHEDULING, + }, + }); + + const result = await new ProcessesService( + holder as any, + {} as any, + ).getByClientId( + clientId, + { page: 1, perPage: 20 }, + specialistId, + UserRole.SPECIALIST, + ); + + expect(result.count).toBe(1); + expect(result.processes.map(({ id }) => id)).toEqual([own.id]); }); - await holder.user.deleteMany({ where: { id: { in: [clientId, specialistId] } } }); - await Promise.all([first.$disconnect(), second.$disconnect(), holder.$disconnect()]); - }); - it('allows only one concurrent active consultancy for the same client and specialist', async () => { - const lockKey = `process-dedup:${clientId}:${specialistId}:CONSULTANCY:none`; - const holderReady = deferred(); - const releaseHolder = deferred(); - const firstAttempted = deferred(); - const secondAttempted = deferred(); - const held = holder.$transaction(async (tx) => { - await tx.$queryRaw` + it('allows only one concurrent active consultancy for the same client and specialist', async () => { + const lockKey = `process-dedup:${clientId}:${specialistId}:CONSULTANCY:none`; + const holderReady = deferred(); + const releaseHolder = deferred(); + const firstAttempted = deferred(); + const secondAttempted = deferred(); + const held = holder.$transaction(async (tx) => { + await tx.$queryRaw` SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))::text AS locked `; - holderReady.resolve(); - await releaseHolder.promise; - }); - await holderReady.promise; + holderReady.resolve(); + await releaseHolder.promise; + }); + await holderReady.promise; - const serviceA = new ProcessesService( - signalDedupLockAttempt(first, firstAttempted) as any, - {} as any, - ); - const serviceB = new ProcessesService( - signalDedupLockAttempt(second, secondAttempted) as any, - {} as any, - ); - const input = { - client_id: clientId, - specialist_id: specialistId, - product_type: 'CAR' as const, - product_id: undefined, - createdBy: specialistId, - actorLabel: 'especialista', - }; + const serviceA = new ProcessesService( + signalDedupLockAttempt(first, firstAttempted) as any, + {} as any, + ); + const serviceB = new ProcessesService( + signalDedupLockAttempt(second, secondAttempted) as any, + {} as any, + ); + const input = { + client_id: clientId, + specialist_id: specialistId, + product_type: 'CAR' as const, + product_id: undefined, + createdBy: specialistId, + actorLabel: 'especialista', + }; - const outcomesPromise = Promise.allSettled([ - serviceA.createOnBehalfOfClient(input), - serviceB.createOnBehalfOfClient(input), - ]); - await Promise.all([firstAttempted.promise, secondAttempted.promise]); - releaseHolder.resolve(); - await held; - const outcomes = await outcomesPromise; + const outcomesPromise = Promise.allSettled([ + serviceA.createOnBehalfOfClient(input), + serviceB.createOnBehalfOfClient(input), + ]); + await Promise.all([firstAttempted.promise, secondAttempted.promise]); + releaseHolder.resolve(); + await held; + const outcomes = await outcomesPromise; - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); - await expect( - holder.process.count({ where: { client_id: clientId, specialist_id: specialistId } }), - ).resolves.toBe(1); - }, 15_000); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + expect( + outcomes.find(({ status }) => status === 'rejected'), + ).toMatchObject({ + reason: expect.any(ConflictException), + }); + await expect( + holder.process.count({ + where: { client_id: clientId, specialist_id: specialistId }, + }), + ).resolves.toBe(1); + }, 15_000); - it('serializes two public create requests on the same active-process key', async () => { - const lockKey = `process-dedup:${clientId}:${specialistId}:CONSULTANCY:none`; - const holderReady = deferred(); - const releaseHolder = deferred(); - const firstAttempted = deferred(); - const secondAttempted = deferred(); - const held = holder.$transaction(async (tx) => { - await tx.$queryRaw` + it('serializes two public create requests on the same active-process key', async () => { + const lockKey = `process-dedup:${clientId}:${specialistId}:CONSULTANCY:none`; + const holderReady = deferred(); + const releaseHolder = deferred(); + const firstAttempted = deferred(); + const secondAttempted = deferred(); + const held = holder.$transaction(async (tx) => { + await tx.$queryRaw` SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))::text AS locked `; - holderReady.resolve(); - await releaseHolder.promise; - }); - await holderReady.promise; + holderReady.resolve(); + await releaseHolder.promise; + }); + await holderReady.promise; - const serviceA = new ProcessesService( - signalDedupLockAttempt(first, firstAttempted) as any, - {} as any, - ); - const serviceB = new ProcessesService( - signalDedupLockAttempt(second, secondAttempted) as any, - {} as any, - ); - const dto = { - client_id: clientId, - specialist_id: specialistId, - } as any; - const requester = { id: randomUUID(), role: UserRole.ADMIN }; - const firstCreate = serviceA.create(dto, requester); - const secondCreate = serviceB.create(dto, requester); - const bothAttemptedBeforeCompletion = await Promise.race([ - Promise.all([firstAttempted.promise, secondAttempted.promise]).then( - () => true, - ), - Promise.allSettled([firstCreate, secondCreate]).then(() => false), - ]); - releaseHolder.resolve(); - await held; - const outcomes = await Promise.allSettled([firstCreate, secondCreate]); + const serviceA = new ProcessesService( + signalDedupLockAttempt(first, firstAttempted) as any, + {} as any, + ); + const serviceB = new ProcessesService( + signalDedupLockAttempt(second, secondAttempted) as any, + {} as any, + ); + const dto = { + client_id: clientId, + specialist_id: specialistId, + } as any; + const requester = { id: randomUUID(), role: UserRole.ADMIN }; + const firstCreate = serviceA.create(dto, requester); + const secondCreate = serviceB.create(dto, requester); + const bothAttemptedBeforeCompletion = await Promise.race([ + Promise.all([firstAttempted.promise, secondAttempted.promise]).then( + () => true, + ), + Promise.allSettled([firstCreate, secondCreate]).then(() => false), + ]); + releaseHolder.resolve(); + await held; + const outcomes = await Promise.allSettled([firstCreate, secondCreate]); - expect(bothAttemptedBeforeCompletion).toBe(true); - expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(1); - expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ - reason: expect.any(ConflictException), - }); - }, 15_000); + expect(bothAttemptedBeforeCompletion).toBe(true); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + expect( + outcomes.find(({ status }) => status === 'rejected'), + ).toMatchObject({ + reason: expect.any(ConflictException), + }); + }, 15_000); - it('serializes public create with create-on-behalf without blocking consultancy', async () => { - const lockKey = `process-dedup:${clientId}:${specialistId}:CONSULTANCY:none`; - const holderReady = deferred(); - const releaseHolder = deferred(); - const publicAttempted = deferred(); - const behalfAttempted = deferred(); - const held = holder.$transaction(async (tx) => { - await tx.$queryRaw` + it('serializes public create with create-on-behalf and permits only one active consultancy', async () => { + const lockKey = `process-dedup:${clientId}:${specialistId}:CONSULTANCY:none`; + const holderReady = deferred(); + const releaseHolder = deferred(); + const publicAttempted = deferred(); + const behalfAttempted = deferred(); + const held = holder.$transaction(async (tx) => { + await tx.$queryRaw` SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))::text AS locked `; - holderReady.resolve(); - await releaseHolder.promise; - }); - await holderReady.promise; + holderReady.resolve(); + await releaseHolder.promise; + }); + await holderReady.promise; - const publicService = new ProcessesService( - signalDedupLockAttempt(first, publicAttempted) as any, - {} as any, - ); - const behalfService = new ProcessesService( - signalDedupLockAttempt(second, behalfAttempted) as any, - {} as any, - ); - const publicCreate = publicService.create( - { client_id: clientId, specialist_id: specialistId } as any, - { id: randomUUID(), role: UserRole.ADMIN }, - ); - const behalfCreate = behalfService.createOnBehalfOfClient({ - client_id: clientId, - specialist_id: specialistId, - product_type: 'CAR', - product_id: undefined, - createdBy: specialistId, - actorLabel: 'especialista', - }); - const bothAttemptedBeforeCompletion = await Promise.race([ - Promise.all([publicAttempted.promise, behalfAttempted.promise]).then( - () => true, - ), - publicCreate.then( - () => false, - () => false, - ), - ]); - releaseHolder.resolve(); - await held; - const outcomes = await Promise.allSettled([publicCreate, behalfCreate]); + const publicService = new ProcessesService( + signalDedupLockAttempt(first, publicAttempted) as any, + {} as any, + ); + const behalfService = new ProcessesService( + signalDedupLockAttempt(second, behalfAttempted) as any, + {} as any, + ); + const publicCreate = publicService.create( + { client_id: clientId, specialist_id: specialistId } as any, + { id: randomUUID(), role: UserRole.ADMIN }, + ); + const behalfCreate = behalfService.createOnBehalfOfClient({ + client_id: clientId, + specialist_id: specialistId, + product_type: 'CAR', + product_id: undefined, + createdBy: specialistId, + actorLabel: 'especialista', + }); + const bothAttemptedBeforeCompletion = await Promise.race([ + Promise.all([publicAttempted.promise, behalfAttempted.promise]).then( + () => true, + ), + publicCreate.then( + () => false, + () => false, + ), + ]); + releaseHolder.resolve(); + await held; + const outcomes = await Promise.allSettled([publicCreate, behalfCreate]); - expect(bothAttemptedBeforeCompletion).toBe(true); - expect(outcomes[1]).toMatchObject({ status: 'fulfilled' }); - await expect( - holder.appointment.count({ - where: { - client_id: clientId, - specialist_id: specialistId, - product_type: null, - product_id: null, - }, - }), - ).resolves.toBe(1); - }, 15_000); -}); + expect(bothAttemptedBeforeCompletion).toBe(true); + expect( + outcomes.filter(({ status }) => status === 'fulfilled'), + ).toHaveLength(1); + expect( + outcomes.find(({ status }) => status === 'rejected'), + ).toMatchObject({ + reason: expect.any(ConflictException), + }); + await expect( + holder.appointment.count({ + where: { + client_id: clientId, + specialist_id: specialistId, + product_type: null, + product_id: null, + }, + }), + ).resolves.toBeLessThanOrEqual(1); + await expect( + holder.process.count({ + where: { + client_id: clientId, + specialist_id: specialistId, + product_type: null, + status: { + in: [ + ProcessStatus.SCHEDULING, + ProcessStatus.NEGOTIATION, + ProcessStatus.PROCESSING_CONTRACT, + ProcessStatus.DOCUMENTATION, + ], + }, + }, + }), + ).resolves.toBe(1); + }, 15_000); + }, +); diff --git a/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts b/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts new file mode 100644 index 00000000..7f8fd6d5 --- /dev/null +++ b/backend/src/features/processes/processes-rejection-concurrency.postgres.spec.ts @@ -0,0 +1,637 @@ +import { BadRequestException, ConflictException } from '@nestjs/common'; +import { + PrismaClient, + ProcessStatus, + ProductCurrency, + ProductType, + StatusAgendamento, + UserRole, +} from '@prisma/client'; +import { randomUUID } from 'node:crypto'; +import { MeetingsService } from '../meetings/meetings.service'; +import { ProcessesService } from './processes.service'; + +type Deferred = { promise: Promise; resolve: () => void }; + +function deferred(): Deferred { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +function bindMember(target: any, property: PropertyKey): any { + const value = Reflect.get(target, property); + return typeof value === 'function' ? value.bind(target) : value; +} + +function withApplicationName(url: string, name: string): string { + const separator = url.includes('?') ? '&' : '?'; + return `${url}${separator}application_name=${encodeURIComponent(name)}&connection_limit=1&pool_timeout=3`; +} + +function pauseRejectionClaim( + client: PrismaClient, + attempted: Deferred, + release: Deferred, +) { + const wrapTransaction = (tx: any) => + new Proxy(tx, { + get(target, property) { + if (property === 'process') { + return new Proxy(target.process, { + get(processTarget, processProperty) { + if (processProperty === 'updateMany') { + return async (args: any) => { + if (args.data?.status === ProcessStatus.REJECTED) { + attempted.resolve(); + await release.promise; + } + return processTarget.updateMany(args); + }; + } + return bindMember(processTarget, processProperty); + }, + }); + } + return bindMember(target, property); + }, + }); + + return new Proxy(client, { + get(target, property) { + if (property === '$transaction') { + return (callback: (tx: any) => Promise, options?: any) => + target.$transaction((tx) => callback(wrapTransaction(tx)), options); + } + return bindMember(target, property); + }, + }); +} + +function observeScheduleLockAttempt(client: PrismaClient, attempted: Deferred) { + const wrapTransaction = (tx: any) => + new Proxy(tx, { + get(target, property) { + if (property === '$queryRaw') { + return (...args: any[]) => { + attempted.resolve(); + return target.$queryRaw(...args); + }; + } + return bindMember(target, property); + }, + }); + + return new Proxy(client, { + get(target, property) { + if (property === '$transaction') { + return (callback: (tx: any) => Promise, options?: any) => + target.$transaction((tx) => callback(wrapTransaction(tx)), options); + } + return bindMember(target, property); + }, + }); +} + +function pauseMeetingCreate( + client: PrismaClient, + attempted: Deferred, + release: Deferred, +) { + const wrapTransaction = (tx: any) => + new Proxy(tx, { + get(target, property) { + if (property === 'meetingSession') { + return new Proxy(target.meetingSession, { + get(meetingTarget, meetingProperty) { + if (meetingProperty === 'create') { + return async (args: any) => { + attempted.resolve(); + await release.promise; + return meetingTarget.create(args); + }; + } + return bindMember(meetingTarget, meetingProperty); + }, + }); + } + return bindMember(target, property); + }, + }); + + return new Proxy(client, { + get(target, property) { + if (property === '$transaction') { + return (callback: (tx: any) => Promise, options?: any) => + target.$transaction((tx) => callback(wrapTransaction(tx)), options); + } + return bindMember(target, property); + }, + }); +} + +function meetingConfig() { + return { + get: jest.fn((key: string, fallback?: string) => { + if (key === 'MEETING_PROVIDER') return 'JITSI'; + if (key === 'MEETING_DEMO_FALLBACK_ENABLED') return 'false'; + return fallback; + }), + } as any; +} + +function meetingNotifications() { + return { + sendMeetingStartedEmail: jest.fn().mockResolvedValue({}), + sendMeetingAdvancedEmail: jest.fn().mockResolvedValue({}), + sendProcessStatusChangedEmail: jest.fn().mockResolvedValue({}), + } as any; +} + +const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL; +const describeWithPostgres = databaseUrl ? describe : describe.skip; +const prismaDatabaseUrl = + databaseUrl ?? 'postgresql://unused:unused@127.0.0.1:1/unused'; + +describeWithPostgres('process rejection CAS — PostgreSQL concurrency', () => { + const suffix = randomUUID().replaceAll('-', ''); + const clientId = randomUUID(); + const specialistId = randomUUID(); + const carId = randomUUID(); + const processId = randomUUID(); + const appointmentId = randomUUID(); + const rejectClient = new PrismaClient({ + datasources: { + db: { url: withApplicationName(prismaDatabaseUrl, `reject_a_${suffix}`) }, + }, + }); + const completionClient = new PrismaClient({ + datasources: { + db: { url: withApplicationName(prismaDatabaseUrl, `reject_b_${suffix}`) }, + }, + }); + + beforeAll(async () => { + await completionClient.user.createMany({ + data: [ + { + id: clientId, + name: 'Reject', + surname: 'Client', + email: `reject-client-${suffix}@example.test`, + rg: suffix.slice(0, 11), + role: UserRole.CUSTOMER, + password_hash: 'not-used', + }, + { + id: specialistId, + name: 'Reject', + surname: 'Specialist', + email: `reject-specialist-${suffix}@example.test`, + rg: suffix.slice(11, 22), + role: UserRole.SPECIALIST, + speciality: ProductType.CAR, + password_hash: 'not-used', + }, + ], + }); + await completionClient.car.create({ + data: { + id: carId, + specialist_id: specialistId, + marca: 'Concurrent', + modelo: 'Rejection', + identificador: `rejection-${suffix}`, + valor: 120000, + currency: ProductCurrency.USD, + estado: 'SP', + ano: 2026, + }, + }); + }); + + beforeEach(async () => { + await completionClient.processRejection.deleteMany({ + where: { process_id: processId }, + }); + await completionClient.processStatusHistory.deleteMany({ + where: { processId }, + }); + await completionClient.process.deleteMany({ where: { id: processId } }); + await completionClient.appointment.deleteMany({ + where: { id: appointmentId }, + }); + }); + + afterAll(async () => { + await completionClient.processRejection.deleteMany({ + where: { process_id: processId }, + }); + await completionClient.processStatusHistory.deleteMany({ + where: { processId }, + }); + await completionClient.process.deleteMany({ where: { id: processId } }); + await completionClient.appointment.deleteMany({ + where: { id: appointmentId }, + }); + await completionClient.car.deleteMany({ where: { id: carId } }); + await completionClient.user.deleteMany({ + where: { id: { in: [clientId, specialistId] } }, + }); + await Promise.all([ + rejectClient.$disconnect(), + completionClient.$disconnect(), + ]); + }); + + async function createConfirmedAppointment() { + await completionClient.appointment.create({ + data: { + id: appointmentId, + client_id: clientId, + specialist_id: specialistId, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + // Rejeição de processo bloqueia appointments ativos + // (PENDING/SCHEDULED); COMPLETED mantém esta fixture focada apenas + // na serialização entre rejeição e criação da reunião. + status: StatusAgendamento.COMPLETED, + }, + }); + } + + it('preserva conclusão concorrente e não grava rejeição parcial', async () => { + const initialUpdatedAt = new Date('2026-01-01T00:00:00.000Z'); + await completionClient.process.create({ + data: { + id: processId, + client_id: clientId, + specialist_id: specialistId, + status: ProcessStatus.DOCUMENTATION, + updated_at: initialUpdatedAt, + }, + }); + + const attempted = deferred(); + const release = deferred(); + const service = new ProcessesService( + pauseRejectionClaim(rejectClient, attempted, release) as any, + { sendProcessStatusChangedEmail: jest.fn() } as any, + ); + + const rejection = service.rejectProcess( + processId, + specialistId, + 'concorrente', + UserRole.SPECIALIST, + ); + await attempted.promise; + + const completion = await completionClient.process.updateMany({ + where: { + id: processId, + status: ProcessStatus.DOCUMENTATION, + updated_at: initialUpdatedAt, + }, + data: { + status: ProcessStatus.COMPLETED, + updated_at: new Date('2026-01-02T00:00:00.000Z'), + }, + }); + expect(completion.count).toBe(1); + + release.resolve(); + await expect(rejection).rejects.toBeInstanceOf(ConflictException); + + await expect( + completionClient.process.findUniqueOrThrow({ where: { id: processId } }), + ).resolves.toMatchObject({ status: ProcessStatus.COMPLETED }); + await expect( + completionClient.processRejection.count({ + where: { process_id: processId }, + }), + ).resolves.toBe(0); + await expect( + completionClient.processStatusHistory.count({ + where: { processId, status: ProcessStatus.REJECTED }, + }), + ).resolves.toBe(0); + }, 15_000); + + it('remove meeting-init vencido sob lock e permite a rejeição', async () => { + await completionClient.process.create({ + data: { + id: processId, + client_id: clientId, + specialist_id: specialistId, + status: ProcessStatus.SCHEDULING, + meeting_session: { + create: { + started_by_id: specialistId, + calendar_event_id: `meeting-init:${suffix}`, + meet_link: '', + started_at: new Date(Date.now() - 3 * 60 * 1000), + }, + }, + }, + }); + const service = new ProcessesService( + completionClient as any, + meetingNotifications(), + ); + + await expect( + service.rejectProcess( + processId, + clientId, + 'claim abandonado', + UserRole.CUSTOMER, + ), + ).resolves.toMatchObject({ status: ProcessStatus.REJECTED }); + + await expect( + completionClient.meetingSession.count({ + where: { process_id: processId }, + }), + ).resolves.toBe(0); + await expect( + completionClient.process.findUniqueOrThrow({ where: { id: processId } }), + ).resolves.toMatchObject({ status: ProcessStatus.REJECTED }); + }, 15_000); + + it('não ressuscita processo quando update perde a corrida para rejeição', async () => { + await completionClient.process.create({ + data: { + id: processId, + client_id: clientId, + specialist_id: specialistId, + product_type: ProductType.CAR, + car_id: carId, + status: ProcessStatus.NEGOTIATION, + negotiation_currency: ProductCurrency.USD, + negotiation_product_value: 120000, + }, + }); + + const rejectionClaimAttempted = deferred(); + const releaseRejection = deferred(); + const updateLockAttempted = deferred(); + const notifications = { + sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined), + } as any; + const rejectionService = new ProcessesService( + pauseRejectionClaim( + rejectClient, + rejectionClaimAttempted, + releaseRejection, + ) as any, + notifications, + ); + const updateService = new ProcessesService( + observeScheduleLockAttempt(completionClient, updateLockAttempted) as any, + notifications, + ); + + const rejection = rejectionService.rejectProcess( + processId, + specialistId, + 'concorrente', + UserRole.SPECIALIST, + ); + await rejectionClaimAttempted.promise; + + const update = updateService.update( + processId, + { status: ProcessStatus.DOCUMENTATION }, + specialistId, + UserRole.SPECIALIST, + ); + await updateLockAttempted.promise; + + releaseRejection.resolve(); + await expect(rejection).resolves.toMatchObject({ + status: ProcessStatus.REJECTED, + }); + await expect(update).rejects.toBeInstanceOf(BadRequestException); + + await expect( + completionClient.process.findUniqueOrThrow({ where: { id: processId } }), + ).resolves.toMatchObject({ status: ProcessStatus.REJECTED }); + await expect( + completionClient.processStatusHistory.count({ + where: { processId, status: ProcessStatus.DOCUMENTATION }, + }), + ).resolves.toBe(0); + }, 15_000); + + it('não cria reunião nem envia e-mail quando a rejeição ganha o lock', async () => { + await createConfirmedAppointment(); + await completionClient.process.create({ + data: { + id: processId, + client_id: clientId, + specialist_id: specialistId, + appointment_id: appointmentId, + status: ProcessStatus.SCHEDULING, + }, + }); + + const rejectionClaimAttempted = deferred(); + const releaseRejection = deferred(); + const meetingLockAttempted = deferred(); + const notifications = meetingNotifications(); + const rejectionService = new ProcessesService( + pauseRejectionClaim( + rejectClient, + rejectionClaimAttempted, + releaseRejection, + ) as any, + notifications, + ); + const meetingsService = new MeetingsService( + observeScheduleLockAttempt(completionClient, meetingLockAttempted) as any, + meetingConfig(), + notifications, + {} as any, + ); + + const rejection = rejectionService.rejectProcess( + processId, + specialistId, + 'concorrente', + UserRole.SPECIALIST, + ); + await rejectionClaimAttempted.promise; + + const meeting = meetingsService.startMeetingForProcess( + processId, + specialistId, + ); + await meetingLockAttempted.promise; + + releaseRejection.resolve(); + await expect(rejection).resolves.toMatchObject({ + status: ProcessStatus.REJECTED, + }); + await expect(meeting).rejects.toBeInstanceOf(BadRequestException); + await new Promise((resolve) => setImmediate(resolve)); + + await expect( + completionClient.meetingSession.count({ + where: { process_id: processId }, + }), + ).resolves.toBe(0); + expect(notifications.sendMeetingStartedEmail).not.toHaveBeenCalled(); + expect(notifications.sendMeetingAdvancedEmail).not.toHaveBeenCalled(); + }, 15_000); + + it('mantém reunião e recusa rejeição quando o início ganha o lock', async () => { + await createConfirmedAppointment(); + await completionClient.process.create({ + data: { + id: processId, + client_id: clientId, + specialist_id: specialistId, + appointment_id: appointmentId, + status: ProcessStatus.SCHEDULING, + }, + }); + + const meetingCreateAttempted = deferred(); + const releaseMeeting = deferred(); + const rejectionLockAttempted = deferred(); + const notifications = meetingNotifications(); + const meetingsService = new MeetingsService( + pauseMeetingCreate( + completionClient, + meetingCreateAttempted, + releaseMeeting, + ) as any, + meetingConfig(), + notifications, + {} as any, + ); + const rejectionService = new ProcessesService( + observeScheduleLockAttempt(rejectClient, rejectionLockAttempted) as any, + notifications, + ); + + const meeting = meetingsService.startMeetingForProcess( + processId, + specialistId, + ); + await meetingCreateAttempted.promise; + + const rejection = rejectionService.rejectProcess( + processId, + specialistId, + 'concorrente', + UserRole.SPECIALIST, + ); + await rejectionLockAttempted.promise; + + releaseMeeting.resolve(); + await expect(meeting).resolves.toMatchObject({ is_active: true }); + await expect(rejection).rejects.toBeInstanceOf(BadRequestException); + await new Promise((resolve) => setImmediate(resolve)); + + await expect( + completionClient.process.findUniqueOrThrow({ where: { id: processId } }), + ).resolves.toMatchObject({ status: ProcessStatus.SCHEDULING }); + await expect( + completionClient.meetingSession.count({ + where: { process_id: processId }, + }), + ).resolves.toBe(1); + await expect( + completionClient.processRejection.count({ + where: { process_id: processId }, + }), + ).resolves.toBe(0); + expect(notifications.sendMeetingStartedEmail).toHaveBeenCalledTimes(1); + expect(notifications.sendMeetingAdvancedEmail).not.toHaveBeenCalled(); + }, 15_000); + + it('libera pool connection_limit=1 durante provider e impede start/e-mail duplicado', async () => { + await createConfirmedAppointment(); + await completionClient.process.create({ + data: { + id: processId, + client_id: clientId, + specialist_id: specialistId, + appointment_id: appointmentId, + status: ProcessStatus.SCHEDULING, + }, + }); + + const providerEntered = deferred(); + const releaseProvider = deferred(); + const notifications = meetingNotifications(); + const oauth = { + getAccessToken: jest.fn().mockImplementation(async () => { + // Este client tem connection_limit=1. Se a transação do claim ainda + // estiver aberta, a própria leitura do OAuth esgota o pool. + await completionClient.user.count({ where: { id: specialistId } }); + providerEntered.resolve(); + await releaseProvider.promise; + return 'access-token'; + }), + } as any; + const config = { + get: jest.fn((key: string, fallback?: string) => { + if (key === 'MEETING_PROVIDER') return 'GOOGLE'; + if (key === 'MEETING_DEMO_FALLBACK_ENABLED') return 'false'; + if (key === 'GOOGLE_MEET_ACCESS_TYPE') return 'OPEN'; + return fallback; + }), + } as any; + const originalFetch = global.fetch; + const fetchMock = jest.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + name: `spaces/${suffix}`, + meetingUri: `https://meet.google.com/${suffix.slice(0, 10)}`, + }), + }); + global.fetch = fetchMock as any; + + try { + const meetingsService = new MeetingsService( + completionClient as any, + config, + notifications, + oauth, + ); + const firstStart = meetingsService.startMeetingForProcess( + processId, + specialistId, + ); + await providerEntered.promise; + + await expect( + meetingsService.startMeetingForProcess(processId, specialistId), + ).rejects.toBeInstanceOf(ConflictException); + + releaseProvider.resolve(); + await expect(firstStart).resolves.toMatchObject({ is_active: true }); + await new Promise((resolve) => setImmediate(resolve)); + + expect(oauth.getAccessToken).toHaveBeenCalledTimes(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + await expect( + completionClient.meetingSession.findUniqueOrThrow({ + where: { process_id: processId }, + }), + ).resolves.toMatchObject({ + calendar_event_id: `spaces/${suffix}`, + meet_link: `https://meet.google.com/${suffix.slice(0, 10)}`, + }); + expect(notifications.sendMeetingStartedEmail).toHaveBeenCalledTimes(1); + expect(notifications.sendMeetingAdvancedEmail).not.toHaveBeenCalled(); + } finally { + global.fetch = originalFetch; + releaseProvider.resolve(); + } + }, 15_000); +}); diff --git a/backend/src/features/processes/processes.controller.spec.ts b/backend/src/features/processes/processes.controller.spec.ts index 069aa67c..5fd1708e 100644 --- a/backend/src/features/processes/processes.controller.spec.ts +++ b/backend/src/features/processes/processes.controller.spec.ts @@ -65,7 +65,7 @@ describe('ProcessesController.confirmAppointment', () => { await (controller.confirmAppointment as any)( processId, { appointment_datetime: appointmentDatetime }, - { user: { id: specialistId } }, + { user: { id: specialistId, role: UserRole.SPECIALIST } }, ); expect(service.confirmAppointment).toHaveBeenCalledWith( @@ -74,4 +74,69 @@ describe('ProcessesController.confirmAppointment', () => { appointmentDatetime, ); }); + + it.each([ + UserRole.CUSTOMER, + UserRole.OFFICE, + UserRole.CONSULTANT, + undefined, + ])( + 'rejects role %s before calling the confirmation service', + async (role) => { + const service = { confirmAppointment: jest.fn() } as any; + const controller = new ProcessesController(service); + await expect( + controller.confirmAppointment( + 'process-1', + {}, + { user: { id: 'actor', role } }, + ), + ).rejects.toThrow(ForbiddenException); + expect(service.confirmAppointment).not.toHaveBeenCalled(); + }, + ); + + it('rejects a missing actor before calling the confirmation service', async () => { + const service = { confirmAppointment: jest.fn() } as any; + const controller = new ProcessesController(service); + await expect( + controller.confirmAppointment('process-1', {}, {}), + ).rejects.toThrow(ForbiddenException); + expect(service.confirmAppointment).not.toHaveBeenCalled(); + }); + + it('permite ADMIN confirmar como o especialista-alvo sem trocar o ator', async () => { + const service = { + confirmAppointment: jest.fn().mockResolvedValue({ processId: 'process-1' }), + } as any; + const context = { + actorId: 'admin-1', + actorRole: UserRole.ADMIN, + specialistId: 'specialist-1', + delegated: true, + specialist: {}, + }; + const actorContext = { + resolve: jest.fn().mockResolvedValue(context), + } as any; + const controller = new ProcessesController(service, actorContext); + + await controller.confirmAppointment( + 'process-1', + { appointment_datetime: '2099-01-01T13:00:00.000Z' }, + { user: { id: 'admin-1', role: UserRole.ADMIN } }, + 'specialist-1', + ); + + expect(actorContext.resolve).toHaveBeenCalledWith( + expect.objectContaining({ id: 'admin-1', role: UserRole.ADMIN }), + 'specialist-1', + ); + expect(service.confirmAppointment).toHaveBeenCalledWith( + 'process-1', + 'admin-1', + '2099-01-01T13:00:00.000Z', + context, + ); + }); }); diff --git a/backend/src/features/processes/processes.controller.ts b/backend/src/features/processes/processes.controller.ts index c23d155b..14f328cb 100644 --- a/backend/src/features/processes/processes.controller.ts +++ b/backend/src/features/processes/processes.controller.ts @@ -13,6 +13,7 @@ import { ForbiddenException, UseGuards, Req, + Optional, } from '@nestjs/common'; import { ProcessesService } from './processes.service'; import { CreateProcessDTO } from './dto/create-process.dto'; @@ -30,10 +31,66 @@ import { GetProcessesFilterDto } from './dto/get-processes-filter.dto'; import { UserEntity } from 'src/auth/entities/user.entity'; import { UserRole } from '@prisma/client'; import { ConfirmProcessAppointmentDto } from './dto/confirm-process-appointment.dto'; +import { + ActorContext, + ActorContextService, +} from 'src/shared/actor-context/actor-context.service'; +import { Roles } from 'src/shared/decorators/roles.decorator'; +import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service'; @Controller('processes') export class ProcessesController { - constructor(private readonly processesService: ProcessesService) {} + constructor( + private readonly processesService: ProcessesService, + @Optional() private readonly actorContextService?: ActorContextService, + @Optional() private readonly delegatedAudit?: DelegatedActionAuditService, + ) {} + + private async resolveSpecialistContext( + user: UserEntity, + targetSpecialistId?: string, + ): Promise { + if ( + user.role !== UserRole.ADMIN && + user.role !== UserRole.SPECIALIST + ) { + return undefined; + } + if (!this.actorContextService) { + return undefined; + } + return this.actorContextService.resolve(user, targetSpecialistId); + } + + @Get(':id/admin-timeline') + @Roles(UserRole.ADMIN) + async getAdminTimeline( + @Param('id', new ParseUUIDPipe()) processId: string, + @Query('target_specialist_id') targetSpecialistId: string, + @Req() req: { user?: UserEntity }, + ) { + if (!req.user || !this.actorContextService || !this.delegatedAudit) { + throw new UnauthorizedException('Contexto administrativo indisponível'); + } + const context = await this.actorContextService.resolve( + req.user, + targetSpecialistId, + ); + const process = await this.processesService.getById( + processId, + req.user.id, + req.user.role, + req.user.company_id, + ); + this.actorContextService.assertResourceSpecialist( + context, + process.specialist.id, + ); + return { + success: true, + data: await this.delegatedAudit.listForProcess(context, processId), + }; + } /** * POST /api/processes @@ -53,11 +110,15 @@ export class ProcessesController { throw new UnauthorizedException('Usuário autenticado não identificado'); } + const context = await this.resolveSpecialistContext( + user, + createProcessDto.specialist_id, + ); const process = await this.processesService.create(createProcessDto, { id: user.id, role: user.role, companyId: user.company_id, - }); + }, context); return { success: true, @@ -131,6 +192,20 @@ export class ProcessesController { }; } + @Get('admin/client-options') + @Roles(UserRole.ADMIN) + async getAdminClientOptions( + @Query('target_specialist_id') targetSpecialistId: string, + @Query('search') search: string | undefined, + @Req() req: { user?: UserEntity }, + ) { + if (!req.user) { + throw new UnauthorizedException('Usuário autenticado não identificado'); + } + await this.resolveSpecialistContext(req.user, targetSpecialistId); + return this.processesService.getAdminClientOptions(search); + } + /** * GET /api/processes/:id * Get a single process by its ID @@ -143,13 +218,27 @@ export class ProcessesController { @Get(':id') async getById( @Param('id', new ParseUUIDPipe()) processId: string, - @Req() req: { user?: { id: string; role?: string } }, + @Req() req: { user?: UserEntity }, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const process = await this.processesService.getById( processId, req.user?.id, req.user?.role, + req.user?.company_id, ); + if (req.user) { + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); + if (context) { + this.actorContextService?.assertResourceSpecialist( + context, + process.specialist.id, + ); + } + } return { success: true, @@ -182,6 +271,15 @@ export class ProcessesController { 'Você não pode listar processos de outro especialista.', ); } + const context = await this.resolveSpecialistContext( + user, + filters.target_specialist_id, + ); + if (context && context.specialistId !== specialistId) { + throw new ForbiddenException( + 'A lista não pertence ao especialista representado.', + ); + } const page = Number(filters.page) || 1; const perPage = Number(filters.perPage) || 20; @@ -240,6 +338,7 @@ export class ProcessesController { @Param('id', new ParseUUIDPipe()) processId: string, @Body() updateProcessDto: UpdateProcessDto, @Req() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const userId = req.user?.sub || req.user?.id; const userRole = req.user?.role; @@ -248,11 +347,17 @@ export class ProcessesController { throw new UnauthorizedException('Usuário autenticado não identificado'); } + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); const updatedProcess = await this.processesService.update( processId, updateProcessDto, userId, userRole, + req.user?.company_id, + context, ); return { @@ -281,6 +386,7 @@ export class ProcessesController { @Param('id', new ParseUUIDPipe()) processId: string, @Body() dto: AssignProductToProcessDto, @Req() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const userId = req.user?.sub || req.user?.id; const userRole = req.user?.role; @@ -289,11 +395,16 @@ export class ProcessesController { throw new UnauthorizedException('Usuário autenticado não identificado'); } + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); const updatedProcess = await this.processesService.assignProduct( processId, dto, userId, userRole, + context, ); return { @@ -314,9 +425,20 @@ export class ProcessesController { @Get(':id/completion-reason') async getCompletionReason( @Param('id', new ParseUUIDPipe()) processId: string, + @Req() req: { user?: UserEntity }, ): Promise> { - const reason = - await this.processesService.getProcessCompletionReason(processId); + const user = req.user; + if (!user) { + throw new UnauthorizedException('Usuário autenticado não identificado'); + } + const reason = await this.processesService.getProcessCompletionReason( + processId, + { + id: user.id, + role: user.role, + companyId: user.company_id, + }, + ); return { success: true, @@ -336,9 +458,18 @@ export class ProcessesController { @Get(':id/with-contract') async getWithContract( @Param('id', new ParseUUIDPipe()) processId: string, + @Req() req: { user?: UserEntity }, ): Promise> { + const user = req.user; + if (!user) { + throw new UnauthorizedException('Usuário autenticado não identificado'); + } const processWithContract = - await this.processesService.getByIdWithActiveContract(processId); + await this.processesService.getByIdWithActiveContract(processId, { + id: user.id, + role: user.role, + companyId: user.company_id, + }); return { success: true, @@ -410,13 +541,34 @@ export class ProcessesController { @Param('id', new ParseUUIDPipe()) processId: string, @Body() rejectProcessDto: RejectProcessDto, @Req() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const userId = req.user?.sub || req.user?.id; + const userRole = req.user?.role; + + if (!userId || !userRole) { + throw new UnauthorizedException('Usuário autenticado não identificado'); + } + if ( + userRole === UserRole.ADMIN && + !rejectProcessDto.rejection_reason?.trim() + ) { + throw new BadRequestException( + 'Motivo é obrigatório para rejeição administrativa.', + ); + } + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); const result = await this.processesService.rejectProcess( processId, userId, rejectProcessDto.rejection_reason, + userRole, + req.user?.company_id, + context, ); return { @@ -444,14 +596,35 @@ export class ProcessesController { @Param('id', new ParseUUIDPipe()) processId: string, @Body() dto: ConfirmProcessAppointmentDto, @Req() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const userId = req.user?.sub || req.user?.id; - const result = await this.processesService.confirmAppointment( - processId, - userId, - dto.appointment_datetime, + if ( + !userId || + ![UserRole.SPECIALIST, UserRole.ADMIN].includes(req.user?.role) + ) { + throw new ForbiddenException( + 'Apenas o especialista pode confirmar o agendamento', + ); + } + + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, ); + const result = context + ? await this.processesService.confirmAppointment( + processId, + userId, + dto.appointment_datetime, + context, + ) + : await this.processesService.confirmAppointment( + processId, + userId, + dto.appointment_datetime, + ); return { success: true, @@ -477,12 +650,25 @@ export class ProcessesController { async cancelAppointment( @Param('id', new ParseUUIDPipe()) processId: string, @Req() req: any, + @Body('reason') reason?: string, + @Query('target_specialist_id') targetSpecialistId?: string, ): Promise> { const userId = req.user?.sub || req.user?.id; + if (req.user?.role === UserRole.ADMIN && !reason?.trim()) { + throw new BadRequestException( + 'Motivo é obrigatório para cancelamento administrativo.', + ); + } + const context = await this.resolveSpecialistContext( + req.user, + targetSpecialistId, + ); const result = await this.processesService.cancelAppointment( processId, userId, + context, + reason, ); return { diff --git a/backend/src/features/processes/processes.service.spec.ts b/backend/src/features/processes/processes.service.spec.ts index 1d308144..337ccb91 100644 --- a/backend/src/features/processes/processes.service.spec.ts +++ b/backend/src/features/processes/processes.service.spec.ts @@ -5,6 +5,7 @@ import { NotFoundException, } from '@nestjs/common'; import { + AppointmentSchedulingMethod, Prisma, ProcessStatus, ProductCurrency, @@ -100,9 +101,25 @@ describe('ProcessesService — produto UUID', () => { ); expect(rootFindFirst).not.toHaveBeenCalled(); - expect(transactionalFindFirst).toHaveBeenCalledWith({ - where: expect.objectContaining({ car_id: productId }), - }); + expect(transactionalFindFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ car_id: productId }), + select: { + id: true, + client_id: true, + appointment: { + select: { + id: true, + client_id: true, + status: true, + scheduling_method: true, + appointment_datetime: true, + }, + }, + specialist: { select: { email: true } }, + }, + }), + ); expect(create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ car_id: productId }), @@ -188,6 +205,14 @@ describe('ProcessesService.create — autorização por cliente', () => { ).rejects.toThrow(ForbiddenException); }); + it('SPECIALIST não usa a rota genérica para escolher cliente nem obter PII', async () => { + const { service } = mkService(); + + await expect( + service.create(dto, { id: specialistId, role: UserRole.SPECIALIST }), + ).rejects.toThrow(ForbiddenException); + }); + it('CUSTOMER não cria processo em nome de outro cliente', async () => { const { service } = mkService(); @@ -365,29 +390,58 @@ describe('ProcessesService.createOnBehalfOfClient', () => { expect(data.notes).toContain('Consultoria'); }); - it('permite consultoria em nome do cliente mesmo com processo ativo anterior', async () => { + it('rejeita consultoria em nome do cliente quando há processo ativo mesmo com appointment concluído', async () => { const { service, appointmentCreate, tx } = mkService(); - tx.process.findFirst.mockResolvedValue({ id: 'active-process-1' }); - - await service.createOnBehalfOfClient({ - ...base, - product_id: undefined, - actorLabel: 'consultor', - }); - - expect(tx.process.findFirst).not.toHaveBeenCalled(); - expect(tx.appointment.findFirst).toHaveBeenCalledWith({ - where: { + tx.process.findFirst.mockResolvedValue({ + id: 'active-process-1', + client_id: clientId, + appointment: { + id: 'completed-appointment-1', client_id: clientId, - specialist_id: specialistId, - product_type: null, - product_id: null, - status: { - in: [StatusAgendamento.PENDING, StatusAgendamento.SCHEDULED], - }, + status: StatusAgendamento.COMPLETED, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date('2026-01-01T10:00:00.000Z'), }, }); - expect(appointmentCreate).toHaveBeenCalled(); + + await expect( + service.createOnBehalfOfClient({ + ...base, + product_id: undefined, + actorLabel: 'consultor', + }), + ).rejects.toThrow(ConflictException); + + expect(tx.process.findFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ + client_id: clientId, + specialist_id: specialistId, + product_type: null, + status: { in: expect.arrayContaining([ProcessStatus.SCHEDULING]) }, + }), + }), + ); + expect(appointmentCreate).not.toHaveBeenCalled(); + }); + + it('rejeita consultoria em nome do cliente diante de processo ativo legado sem appointment', async () => { + const { service, appointmentCreate, tx } = mkService(); + tx.process.findFirst.mockResolvedValue({ + id: 'legacy-active-process-1', + client_id: clientId, + appointment: null, + }); + + await expect( + service.createOnBehalfOfClient({ + ...base, + product_id: undefined, + actorLabel: 'consultor', + }), + ).rejects.toThrow(ConflictException); + + expect(appointmentCreate).not.toHaveBeenCalled(); }); it('rejeita consultoria duplicada em nome do cliente', async () => { @@ -701,7 +755,7 @@ describe('ProcessesService — snapshot de entrada na negociação', () => { }; } - it('grava snapshot USD na transição manual para negociação', async () => { + it('adquire agenda → produto e congela o snapshot na entrada em negociação', async () => { const processUpdate = jest.fn().mockImplementation(({ data }) => Promise.resolve({ ...baseProcess(), @@ -738,6 +792,7 @@ describe('ProcessesService — snapshot de entrada na negociação', () => { expect.objectContaining({ where: { id: 'process-1', + removed_at: null, status: ProcessStatus.SCHEDULING, updated_at: new Date('2026-01-01T00:00:00.000Z'), }, @@ -749,8 +804,93 @@ describe('ProcessesService — snapshot de entrada na negociação', () => { }), ); expect(processUpdate).not.toHaveBeenCalled(); - expect(tx.$queryRaw).toHaveBeenCalledTimes(1); - expect(tx.$queryRaw.mock.calls[0][1]).toBe('product-money:CAR:product-1'); + expect(tx.$queryRaw.mock.calls.map((call) => call[1])).toEqual([ + 'appointment-schedule:specialist-1', + 'product-money:CAR:product-1', + ]); + // leitura inicial, releituras após agenda/produto e leitura final do CAS + expect(tx.process.findUniqueOrThrow).toHaveBeenCalledTimes(4); + }); + + it('conflita se o especialista mudar depois do lock de agenda', async () => { + const originalProcess = baseProcess(); + const movedProcess = baseProcess({ specialist_id: 'specialist-2' }); + const processUpdateMany = jest.fn(); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + process: { + findUniqueOrThrow: jest + .fn() + .mockResolvedValueOnce(originalProcess) + .mockResolvedValueOnce(movedProcess), + updateMany: processUpdateMany, + }, + processStatusHistory: { + create: jest.fn(), + findMany: jest.fn(), + }, + }; + const prisma = { + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const service = new ProcessesService(prisma, {} as any); + + await expect( + service.update( + 'process-1', + { status: ProcessStatus.NEGOTIATION }, + 'admin-1', + UserRole.ADMIN, + ), + ).rejects.toBeInstanceOf(ConflictException); + + expect(tx.$queryRaw.mock.calls.map((call) => call[1])).toEqual([ + 'appointment-schedule:specialist-1', + ]); + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('conflita se o produto mudar depois do lock monetário', async () => { + const originalProcess = baseProcess(); + const movedProcess = baseProcess({ + car_id: 'product-2', + car: { ...usdProduct, id: 'product-2' }, + }); + const processUpdateMany = jest.fn(); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + process: { + findUniqueOrThrow: jest + .fn() + .mockResolvedValueOnce(originalProcess) + .mockResolvedValueOnce(originalProcess) + .mockResolvedValueOnce(movedProcess), + updateMany: processUpdateMany, + }, + processStatusHistory: { + create: jest.fn(), + findMany: jest.fn(), + }, + }; + const prisma = { + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const service = new ProcessesService(prisma, {} as any); + + await expect( + service.update( + 'process-1', + { status: ProcessStatus.NEGOTIATION }, + 'admin-1', + UserRole.ADMIN, + ), + ).rejects.toBeInstanceOf(ConflictException); + + expect(tx.$queryRaw.mock.calls.map((call) => call[1])).toEqual([ + 'appointment-schedule:specialist-1', + 'product-money:CAR:product-1', + ]); + expect(processUpdateMany).not.toHaveBeenCalled(); }); it('returns conflict and creates no history when the manual transition loses its CAS claim', async () => { @@ -761,10 +901,15 @@ describe('ProcessesService — snapshot de entrada na negociação', () => { updated_at: new Date('2026-01-02T00:00:00.000Z'), }); const processUpdateMany = jest.fn().mockResolvedValue({ count: 0 }); + const negotiatedProcess = baseProcess({ + status: ProcessStatus.NEGOTIATION, + negotiation_currency: ProductCurrency.USD, + negotiation_product_value: new Prisma.Decimal('120000.00'), + }); const tx = { $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), process: { - findUniqueOrThrow: jest.fn().mockResolvedValue(baseProcess()), + findUniqueOrThrow: jest.fn().mockResolvedValue(negotiatedProcess), update: processUpdate, updateMany: processUpdateMany, }, @@ -781,7 +926,7 @@ describe('ProcessesService — snapshot de entrada na negociação', () => { await expect( service.update( 'process-1', - { status: ProcessStatus.NEGOTIATION, notes: 'Negociando' }, + { status: ProcessStatus.DOCUMENTATION, notes: 'Documentação' }, 'admin-1', UserRole.ADMIN, ), @@ -791,7 +936,8 @@ describe('ProcessesService — snapshot de entrada na negociação', () => { expect.objectContaining({ where: { id: 'process-1', - status: ProcessStatus.SCHEDULING, + removed_at: null, + status: ProcessStatus.NEGOTIATION, updated_at: new Date('2026-01-01T00:00:00.000Z'), }, }), @@ -1001,6 +1147,7 @@ describe('ProcessesService — snapshot de entrada na negociação', () => { expect.objectContaining({ where: { id: 'process-1', + removed_at: null, status: ProcessStatus.SCHEDULING, product_type: null, car_id: null, @@ -1074,6 +1221,10 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { status: StatusAgendamento.PENDING, appointment_datetime: null, scheduling_method: 'EMAIL', + confirmed_at: null, + confirmed_by_id: null, + specialist_rescheduled_at: null, + specialist_rescheduled_from: null, ...appointmentOverrides, }; const process = { @@ -1081,6 +1232,7 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { specialist_id: specialistId, client_id: clientId, status: ProcessStatus.SCHEDULING, + appointment_id: appointment.id, notes: null, updated_at: new Date('2026-01-01T00:00:00.000Z'), appointment, @@ -1100,9 +1252,11 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { boat: null, aircraft: null, }; - const appointmentUpdate = jest.fn().mockResolvedValue({ - ...appointment, - status: StatusAgendamento.SCHEDULED, + let stored = structuredClone(process); + let working = stored; + const appointmentUpdate = jest.fn().mockImplementation(({ data }) => { + Object.assign(working.appointment, data); + return Promise.resolve(structuredClone(working.appointment)); }); const tx = { $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), @@ -1112,13 +1266,28 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { update: appointmentUpdate, }, process: { - findUnique: jest.fn().mockResolvedValue(process), - updateMany: jest.fn().mockResolvedValue({ count: processClaimCount }), + findUnique: jest + .fn() + .mockImplementation(() => Promise.resolve(structuredClone(working))), + updateMany: jest.fn().mockImplementation(({ data }) => { + if (processClaimCount === 1) Object.assign(working, data); + return Promise.resolve({ count: processClaimCount }); + }), }, + processStatusHistory: { create: jest.fn() }, }; const prisma = { - process: { findUnique: jest.fn().mockResolvedValue(process) }, - $transaction: jest.fn(async (callback: any) => callback(tx)), + process: { + findUnique: jest + .fn() + .mockImplementation(() => Promise.resolve(structuredClone(stored))), + }, + $transaction: jest.fn(async (callback: any) => { + working = structuredClone(stored); + const result = await callback(tx); + stored = working; + return result; + }), } as any; const notifications = { sendAppointmentConfirmedEmail: jest.fn().mockResolvedValue(undefined), @@ -1127,6 +1296,10 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { service: new ProcessesService(prisma, notifications), tx, appointmentUpdate, + prisma, + notifications, + stored: () => structuredClone(stored), + mutate: (change: (value: typeof process) => void) => change(stored), }; } @@ -1139,15 +1312,25 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { expect(appointmentUpdate).not.toHaveBeenCalled(); }); - it('requires an explicit datetime for EMAIL even when legacy data has one', async () => { - const { service, appointmentUpdate } = makeService({ + it('confirms the stored EMAIL proposal without requiring a second datetime', async () => { + const { service, stored } = makeService({ appointment_datetime: new Date(futureIso), }); await expect( - (service.confirmAppointment as any)('process-1', specialistId, undefined), - ).rejects.toThrow(BadRequestException); - expect(appointmentUpdate).not.toHaveBeenCalled(); + service.confirmAppointment('process-1', specialistId), + ).resolves.toMatchObject({ + status: ProcessStatus.SCHEDULING, + appointment_status: StatusAgendamento.SCHEDULED, + appointment_datetime: new Date(futureIso), + }); + expect(stored().status).toBe(ProcessStatus.SCHEDULING); + expect(stored().appointment).toMatchObject({ + confirmed_by_id: specialistId, + confirmed_at: expect.anything(), + specialist_rescheduled_at: null, + specialist_rescheduled_from: null, + }); }); it('stores the initial datetime without consuming the definitive change', async () => { @@ -1175,14 +1358,22 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { expect.objectContaining({ where: { id: 'process-1', + removed_at: null, status: ProcessStatus.SCHEDULING, updated_at: new Date('2026-01-01T00:00:00.000Z'), + specialist_id: specialistId, + client_id: clientId, + appointment_id: 'appointment-1', + notes: null, }, }), ); const updateData = appointmentUpdate.mock.calls[0][0].data; expect(updateData).not.toHaveProperty('specialist_rescheduled_at'); expect(updateData).not.toHaveProperty('specialist_rescheduled_from'); + expect(tx.process.updateMany.mock.invocationCallOrder[0]).toBeLessThan( + appointmentUpdate.mock.invocationCallOrder[0], + ); }); it('rejects a past datetime before writing', async () => { @@ -1199,11 +1390,290 @@ describe('ProcessesService.confirmAppointment — horário acordado', () => { }); it('aborts when the process changes during confirmation', async () => { - const { service } = makeService({}, 0); + const { service, stored } = makeService({}, 0); + const before = stored(); await expect( (service.confirmAppointment as any)('process-1', specialistId, futureIso), ).rejects.toThrow(ConflictException); + expect(stored()).toEqual(before); + }); + + it('appends the original proposal and changed confirmed instant without reschedule audit', async () => { + const proposed = new Date('2099-01-01T10:00:00.000Z'); + const { service, stored, mutate, tx } = makeService({ + appointment_datetime: proposed, + }); + mutate((process) => { + process.notes = 'Nota anterior' as any; + }); + await service.confirmAppointment('process-1', specialistId, futureIso); + expect(stored().notes).toContain('Nota anterior'); + expect(stored().notes).toContain(proposed.toISOString()); + expect(stored().notes).toContain(futureIso); + expect(stored().appointment).toMatchObject({ + appointment_datetime: new Date(futureIso), + specialist_rescheduled_at: null, + specialist_rescheduled_from: null, + }); + expect(tx.processStatusHistory.create).not.toHaveBeenCalled(); + }); + + it('returns the same confirmation on double submission without new notes or emails', async () => { + const { service, stored, appointmentUpdate, notifications, tx } = + makeService(); + const first = await service.confirmAppointment( + 'process-1', + specialistId, + futureIso, + ); + await new Promise((resolve) => setImmediate(resolve)); + const afterFirst = stored(); + const second = await service.confirmAppointment( + 'process-1', + specialistId, + futureIso, + ); + await new Promise((resolve) => setImmediate(resolve)); + expect(second).toEqual(first); + expect(stored()).toEqual(afterFirst); + expect(appointmentUpdate).toHaveBeenCalledTimes(1); + expect(tx.process.updateMany).toHaveBeenCalledTimes(1); + expect(notifications.sendAppointmentConfirmedEmail).toHaveBeenCalledTimes( + 1, + ); + }); + + it('accepts the identical retry after the confirmed instant has passed', async () => { + const { service, stored, appointmentUpdate } = makeService(); + const first = await service.confirmAppointment( + 'process-1', + specialistId, + futureIso, + ); + await new Promise((resolve) => setImmediate(resolve)); + const before = stored(); + jest.useFakeTimers({ now: new Date('2100-01-01T00:00:00Z') }); + try { + await expect( + service.confirmAppointment('process-1', specialistId, futureIso), + ).resolves.toEqual(first); + expect(stored()).toEqual(before); + expect(appointmentUpdate).toHaveBeenCalledTimes(1); + } finally { + jest.useRealTimers(); + } + }); + + it('uses a single confirmation timestamp in the appointment and appended note', async () => { + const { service, stored } = makeService(); + await service.confirmAppointment('process-1', specialistId, futureIso); + expect(stored().notes).toContain( + (stored().appointment.confirmed_at as unknown as Date).toISOString(), + ); + }); + + it('notifies the participant snapshot reread under the schedule lock', async () => { + const { service, tx, stored, mutate, notifications } = makeService(); + tx.$queryRaw.mockImplementation(async () => { + mutate((process) => { + process.client.email = 'current-client@example.com'; + }); + tx.process.findUnique.mockImplementation(async () => stored()); + return [{ locked: null }]; + }); + await service.confirmAppointment('process-1', specialistId, futureIso); + await new Promise((resolve) => setImmediate(resolve)); + expect(notifications.sendAppointmentConfirmedEmail).toHaveBeenCalledWith( + expect.objectContaining({ clientEmail: 'current-client@example.com' }), + ); + }); + + it('rolls back a claimed process when updating the appointment fails', async () => { + const { service, tx, stored, notifications } = makeService(); + const before = stored(); + tx.appointment.update.mockRejectedValue(new Error('storage failure')); + await expect( + service.confirmAppointment('process-1', specialistId, futureIso), + ).rejects.toThrow('storage failure'); + expect(stored()).toEqual(before); + await new Promise((resolve) => setImmediate(resolve)); + expect(notifications.sendAppointmentConfirmedEmail).not.toHaveBeenCalled(); + }); + + it('never treats a different datetime as an idempotent confirmation', async () => { + const { service, stored } = makeService(); + await service.confirmAppointment('process-1', specialistId, futureIso); + const before = stored(); + await expect( + service.confirmAppointment( + 'process-1', + specialistId, + '2099-01-02T13:00:00Z', + ), + ).rejects.toThrow(BadRequestException); + expect(stored()).toEqual(before); + }); + + it.each([undefined, '2099-01-01T10:00:00-03:00'])( + 'accepts an identical retry with omitted/equivalent-offset datetime %s', + async (datetime) => { + const { service, stored, appointmentUpdate } = makeService(); + const first = await service.confirmAppointment( + 'process-1', + specialistId, + futureIso, + ); + const before = stored(); + await expect( + service.confirmAppointment('process-1', specialistId, datetime), + ).resolves.toEqual(first); + expect(stored()).toEqual(before); + expect(appointmentUpdate).toHaveBeenCalledTimes(1); + }, + ); + + it.each([ + [StatusAgendamento.COMPLETED, specialistId, new Date()], + [StatusAgendamento.CANCELLED, specialistId, new Date()], + [StatusAgendamento.SCHEDULED, null, null], + [StatusAgendamento.SCHEDULED, 'another-specialist', new Date()], + ])( + 'does not treat status %s with confirmation actor %s as an initial confirmation retry', + async (status, actor, at) => { + const { service, stored } = makeService({ + status, + confirmed_by_id: actor, + confirmed_at: at, + appointment_datetime: new Date(futureIso), + }); + const before = stored(); + await expect( + service.confirmAppointment('process-1', specialistId, futureIso), + ).rejects.toThrow(BadRequestException); + expect(stored()).toEqual(before); + }, + ); + + it.each(['owner', 'status', 'appointment-client', 'appointment-owner'])( + 'rejects %s changed before the transactional reread', + async (change) => { + const { service, tx, stored, mutate } = makeService(); + tx.$queryRaw.mockImplementation(async () => { + mutate((process) => { + if (change === 'owner') process.specialist_id = 'other-specialist'; + if (change === 'status') + process.status = ProcessStatus.REJECTED as any; + if (change === 'appointment-client') + process.appointment.client_id = 'other-client'; + if (change === 'appointment-owner') + process.appointment.specialist_id = 'other-specialist'; + }); + tx.process.findUnique.mockImplementation(async () => stored()); + return [{ locked: null }]; + }); + await expect( + service.confirmAppointment('process-1', specialistId, futureIso), + ).rejects.toThrow( + change === 'owner' ? ForbiddenException : BadRequestException, + ); + expect(tx.process.updateMany).not.toHaveBeenCalled(); + expect(tx.appointment.update).not.toHaveBeenCalled(); + }, + ); + + it('rejects an instant equal to now after rereading without writes', async () => { + const { service, tx } = makeService(); + jest.useFakeTimers({ now: new Date(futureIso) }); + try { + await expect( + service.confirmAppointment('process-1', specialistId, futureIso), + ).rejects.toThrow(BadRequestException); + expect(tx.process.updateMany).not.toHaveBeenCalled(); + expect(tx.appointment.update).not.toHaveBeenCalled(); + } finally { + jest.useRealTimers(); + } + }); + + it.each([ + 'not-a-date', + '2020-01-01T13:00:00Z', + '2099-02-30T13:00:00Z', + '2099-01-01', + '2099-01-01T13:00:00', + ])( + 'rejects invalid or ambiguous instant %s before writes', + async (datetime) => { + const { service, stored, appointmentUpdate } = makeService(); + const before = stored(); + await expect( + service.confirmAppointment('process-1', specialistId, datetime), + ).rejects.toThrow(BadRequestException); + expect(stored()).toEqual(before); + expect(appointmentUpdate).not.toHaveBeenCalled(); + }, + ); + + it.each([clientId, 'other-specialist', 'admin-user'])( + 'rejects confirmation by unassigned actor %s before locking', + async (actorId) => { + const { service, tx } = makeService(); + await expect( + service.confirmAppointment('process-1', actorId, futureIso), + ).rejects.toThrow(ForbiddenException); + expect(tx.$queryRaw).not.toHaveBeenCalled(); + }, + ); + + it('rejects an appointment whose client is inconsistent with its process', async () => { + const { service, stored } = makeService({ client_id: 'other-client' }); + const before = stored(); + await expect( + service.confirmAppointment('process-1', specialistId, futureIso), + ).rejects.toThrow(BadRequestException); + expect(stored()).toEqual(before); + }); + + it('uses the appointment reread after the lock for the stored proposal', async () => { + const { service, tx, stored, mutate } = makeService({ + appointment_datetime: new Date(futureIso), + }); + tx.$queryRaw.mockImplementation(async () => { + mutate((process) => { + process.appointment.appointment_datetime = new Date( + '2020-01-01T10:00:00Z', + ) as any; + }); + tx.process.findUnique.mockImplementation(async () => stored()); + return [{ locked: null }]; + }); + await expect( + service.confirmAppointment('process-1', specialistId), + ).rejects.toThrow(BadRequestException); + expect(tx.appointment.update).not.toHaveBeenCalled(); + }); + + it('rolls back all state and returns no competing identities on a schedule conflict', async () => { + const { service, stored, tx, notifications } = makeService({ + appointment_datetime: new Date(futureIso), + }); + tx.appointment.findFirst.mockResolvedValue({ + id: 'competing-appointment', + client_id: 'competing-client', + process: { id: 'competing-process' }, + }); + const before = stored(); + const error = await service + .confirmAppointment('process-1', specialistId, futureIso) + .catch((error) => error); + expect(error).toBeInstanceOf(ConflictException); + expect(JSON.stringify(error.getResponse())).not.toMatch(/competing-/); + expect(stored()).toEqual(before); + expect(tx.appointment.update).not.toHaveBeenCalled(); + expect(tx.process.updateMany).not.toHaveBeenCalled(); + await new Promise((resolve) => setImmediate(resolve)); + expect(notifications.sendAppointmentConfirmedEmail).not.toHaveBeenCalled(); }); }); @@ -1247,6 +1717,7 @@ describe('ProcessesService — telefone da contraparte após confirmação', () const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ + role: UserRole.CUSTOMER, consultant_id: 'consultant-1', }), }, @@ -1290,29 +1761,80 @@ describe('ProcessesService — telefone da contraparte após confirmação', () }, ); - it.each([ - [StatusAgendamento.PENDING, null], - [StatusAgendamento.SCHEDULED, clientPhone], - [StatusAgendamento.COMPLETED, clientPhone], - [StatusAgendamento.CANCELLED, null], - [null, null], - ])( - 'especialista recebe telefone do cliente em %s: %s', - async (status, expected) => { - const service = listService(status); - const result = await service.getBySpecialistIdWithFilters( - specialistId, - { page: 1, perPage: 20 }, - { id: specialistId, role: UserRole.SPECIALIST }, - ); - - expect(result.processes[0].client.phone).toBe(expected); - }, - ); + it('aplica o mesmo escopo do especialista atribuído em findMany e count da lista por cliente', async () => { + const service = listService(StatusAgendamento.SCHEDULED); - it('detalhe oculta o telefone do cliente para especialista em PENDING', async () => { - const result = await detailService(StatusAgendamento.PENDING).getById( - 'process-1', + await service.getByClientId( + clientId, + { page: 1, perPage: 20 } as any, + specialistId, + UserRole.SPECIALIST, + ); + + const processDelegate = (service as any).prismaService.process; + const expectedWhere = { + client_id: clientId, + removed_at: null, + specialist_id: specialistId, + }; + expect(processDelegate.findMany).toHaveBeenCalledWith( + expect.objectContaining({ where: expectedWhere }), + ); + expect(processDelegate.count).toHaveBeenCalledWith({ + where: expectedWhere, + }); + }); + + it('mantém o vínculo do consultor no where de findMany e count', async () => { + const service = listService(StatusAgendamento.SCHEDULED); + + await service.getByClientId( + clientId, + { page: 1, perPage: 20 } as any, + 'consultant-1', + UserRole.CONSULTANT, + ); + + const processDelegate = (service as any).prismaService.process; + const expectedWhere = { + client_id: clientId, + removed_at: null, + client: { + role: UserRole.CUSTOMER, + consultant_id: 'consultant-1', + }, + }; + expect(processDelegate.findMany).toHaveBeenCalledWith( + expect.objectContaining({ where: expectedWhere }), + ); + expect(processDelegate.count).toHaveBeenCalledWith({ + where: expectedWhere, + }); + }); + + it.each([ + [StatusAgendamento.PENDING, null], + [StatusAgendamento.SCHEDULED, clientPhone], + [StatusAgendamento.COMPLETED, clientPhone], + [StatusAgendamento.CANCELLED, null], + [null, null], + ])( + 'especialista recebe telefone do cliente em %s: %s', + async (status, expected) => { + const service = listService(status); + const result = await service.getBySpecialistIdWithFilters( + specialistId, + { page: 1, perPage: 20 }, + { id: specialistId, role: UserRole.SPECIALIST }, + ); + + expect(result.processes[0].client.phone).toBe(expected); + }, + ); + + it('detalhe oculta o telefone do cliente para especialista em PENDING', async () => { + const result = await detailService(StatusAgendamento.PENDING).getById( + 'process-1', specialistId, UserRole.SPECIALIST, ); @@ -1336,9 +1858,11 @@ describe('ProcessesService — telefone da contraparte após confirmação', () ])( 'detalhe não expõe telefones para %s mesmo após confirmação', async (role, requesterId) => { - const result = await detailService( - StatusAgendamento.SCHEDULED, - ).getById('process-1', requesterId, role); + const result = await detailService(StatusAgendamento.SCHEDULED).getById( + 'process-1', + requesterId, + role, + ); expect(result.client.phone).toBeNull(); expect(result.specialist.phone).toBeNull(); @@ -1397,3 +1921,1214 @@ describe('ProcessesService — telefone da contraparte após confirmação', () expect(result.processes[0].client.phone).toBeNull(); }); }); + +describe('ProcessesService — matriz de contatos do cliente', () => { + const contact = { email: 'cliente@example.com', phone: '11987654321' }; + const cases = [ + [ + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + true, + ], + [ + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.CALENDLY, + ProcessStatus.SCHEDULING, + false, + ], + [StatusAgendamento.PENDING, null, ProcessStatus.SCHEDULING, false], + [ + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.REJECTED, + false, + ], + [ + StatusAgendamento.SCHEDULED, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + true, + ], + [ + StatusAgendamento.COMPLETED, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.NEGOTIATION, + true, + ], + [ + StatusAgendamento.CANCELLED, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + false, + ], + ] as const; + + function makeService( + status: StatusAgendamento, + method: AppointmentSchedulingMethod | null, + processStatus: ProcessStatus, + ) { + const process = { + id: 'process-1', + status: processStatus, + client_id: clientId, + specialist_id: specialistId, + product_type: null, + client: { + id: clientId, + name: 'Cliente', + consultant_id: 'consultant-1', + ...contact, + }, + specialist: { + id: specialistId, + name: 'Especialista', + phone: '11911112222', + speciality: ProductType.CAR, + }, + appointment: { + status, + scheduling_method: method, + appointment_datetime: new Date('2099-01-01T13:00:00Z'), + }, + car: null, + boat: null, + aircraft: null, + notes: null, + created_at: new Date(), + }; + const prisma = { + user: { + findUnique: jest.fn().mockResolvedValue({ + role: UserRole.CUSTOMER, + consultant_id: 'consultant-1', + }), + }, + process: { + findUniqueOrThrow: jest.fn().mockResolvedValue(process), + findMany: jest.fn().mockResolvedValue([process]), + findFirst: jest.fn().mockResolvedValue({ id: process.id }), + count: jest.fn().mockResolvedValue(1), + groupBy: jest.fn().mockResolvedValue([]), + }, + $transaction: jest.fn((operations) => Promise.all(operations)), + } as any; + return new ProcessesService(prisma, {} as any); + } + + it.each(cases)( + 'assigned specialist list and detail expose contacts for %s/%s/%s: %s', + async (status, method, processStatus, visible) => { + const service = makeService(status, method, processStatus); + const detail = await service.getById( + 'process-1', + specialistId, + UserRole.SPECIALIST, + ); + const list = await service.getBySpecialistIdWithFilters( + specialistId, + {}, + { id: specialistId, role: UserRole.SPECIALIST }, + ); + const generic = await service.getAll({ + page: 1, + perPage: 20, + requester: { id: specialistId, role: UserRole.SPECIALIST }, + }); + for (const result of [detail, list.processes[0], generic.processes[0]]) { + if (visible) { + expect(result.client).toMatchObject(contact); + } else { + expect(result.client).not.toHaveProperty('email'); + expect(result.client.phone).toBeNull(); + } + } + }, + ); + + it.each([ + [UserRole.ADMIN, 'admin-1'], + [UserRole.CONSULTANT, 'consultant-1'], + [UserRole.OFFICE, 'office-1'], + [UserRole.SPECIALIST, 'other-specialist'], + [UserRole.CUSTOMER, clientId], + ] as const)( + 'specialist list gives %s no client contacts even after confirmation', + async (role, id) => { + for (const status of [ + StatusAgendamento.PENDING, + StatusAgendamento.SCHEDULED, + StatusAgendamento.COMPLETED, + ]) { + const result = await makeService( + status, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getBySpecialistIdWithFilters(specialistId, {}, { role, id }); + expect(result.processes[0].client).not.toHaveProperty('email'); + expect(result.processes[0].client.phone).toBeNull(); + } + }, + ); + + it.each([ + [UserRole.ADMIN, 'admin-1'], + [UserRole.CONSULTANT, 'consultant-1'], + [UserRole.CUSTOMER, clientId], + ] as const)('detail gives %s no client contacts', async (role, id) => { + const result = await makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getById('process-1', id, role); + expect(result.client).not.toHaveProperty('email'); + expect(result.client.phone).toBeNull(); + expect(result.specialist.phone).toBeNull(); + }); + + it('detail denies an unidentified actor', async () => { + await expect( + makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getById('process-1', undefined, undefined), + ).rejects.toThrow(ForbiddenException); + }); + + it.each([ + [UserRole.SPECIALIST, 'other-specialist'], + [UserRole.OFFICE, 'office-1'], + ] as const)('unassigned %s cannot read the detail', async (role, id) => { + await expect( + makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getById('process-1', id, role), + ).rejects.toThrow(ForbiddenException); + }); + + it('an actor with the specialist ID but another role cannot read the detail', async () => { + await expect( + makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getById('process-1', specialistId, UserRole.CONSULTANT), + ).rejects.toThrow(ForbiddenException); + }); + + it('client list and unscoped legacy specialist projection contain no client contacts', async () => { + const service = makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ); + const client = await service.getByClientId( + clientId, + { page: 1, perPage: 20 }, + clientId, + UserRole.CUSTOMER, + ); + const legacy = await service.getBySpecialistId(specialistId, { + page: 1, + perPage: 20, + }); + for (const result of [client.processes[0], legacy.processes[0]]) { + expect(result.client).not.toHaveProperty('email'); + expect(result.client.phone ?? null).toBeNull(); + } + }); + + it.each([ + UserRole.ADMIN, + UserRole.CONSULTANT, + UserRole.OFFICE, + UserRole.CUSTOMER, + ])('generic list gives %s no early client contacts', async (role) => { + const result = await makeService( + StatusAgendamento.PENDING, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ).getAll({ + page: 1, + perPage: 20, + requester: { id: 'actor', role, companyId: 'company-1' }, + }); + expect(result.processes[0].client).not.toHaveProperty('email'); + expect(result.processes[0].client.phone).toBeNull(); + }); + + it.each([UserRole.ADMIN, UserRole.CONSULTANT, UserRole.SPECIALIST])( + 'client list gives unassigned %s no client contacts', + async (role) => { + const service = makeService( + StatusAgendamento.SCHEDULED, + AppointmentSchedulingMethod.EMAIL, + ProcessStatus.SCHEDULING, + ); + const result = await service.getByClientId( + clientId, + { page: 1, perPage: 20 }, + role === UserRole.CONSULTANT ? 'consultant-1' : 'unassigned-actor', + role, + ); + expect(result.processes[0].client).not.toHaveProperty('email'); + expect(result.processes[0].client.phone).toBeNull(); + }, + ); +}); + +describe('ProcessesService — autorização centralizada de processos', () => { + const ownerClientId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; + const assignedSpecialistId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'; + const outsiderId = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc'; + const consultantId = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd'; + const clientCompanyId = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee'; + const otherCompanyId = 'ffffffff-ffff-4fff-8fff-ffffffffffff'; + + function protectedProcess(overrides: Record = {}) { + return { + id: '99999999-9999-4999-8999-999999999999', + client_id: ownerClientId, + specialist_id: assignedSpecialistId, + status: ProcessStatus.SCHEDULING, + appointment_id: null, + updated_at: new Date('2026-01-01T00:00:00.000Z'), + notes: null, + product_type: null, + active_contract_id: 'contract-1', + created_at: new Date('2026-01-01T00:00:00.000Z'), + client: { + id: ownerClientId, + email: 'cliente@example.com', + name: 'Cliente', + surname: 'Teste', + consultant_id: consultantId, + company_id: null, + consultant: { company_id: clientCompanyId }, + }, + specialist: { + id: assignedSpecialistId, + email: 'especialista@example.com', + name: 'Especialista', + surname: 'Teste', + }, + car: null, + boat: null, + aircraft: null, + appointment: null, + meeting_session: null, + ...overrides, + }; + } + + function updateService(process = protectedProcess()) { + const processUpdateMany = jest.fn().mockResolvedValue({ count: 1 }); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + process: { + findUniqueOrThrow: jest.fn().mockResolvedValue(process), + updateMany: processUpdateMany, + }, + processStatusHistory: { + create: jest.fn().mockResolvedValue({}), + findMany: jest.fn().mockResolvedValue([]), + }, + }; + const prisma = { + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + return { + service: new ProcessesService(prisma, { + sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined), + } as any), + processUpdateMany, + tx, + }; + } + + function rejectionService(process = protectedProcess(), claimCount = 1) { + const rejectedProcess = { + ...process, + status: ProcessStatus.REJECTED, + updated_at: new Date('2026-01-02T00:00:00.000Z'), + }; + const processUpdate = jest.fn(); + const processUpdateMany = jest + .fn() + .mockResolvedValue({ count: claimCount }); + const processFindUniqueOrThrow = jest + .fn() + .mockResolvedValueOnce(process) + .mockResolvedValueOnce(process) + .mockResolvedValueOnce(rejectedProcess); + const historyCreate = jest.fn().mockResolvedValue({}); + const rejectionCreate = jest.fn().mockResolvedValue({}); + const meetingSessionDeleteMany = jest.fn().mockResolvedValue({ count: 1 }); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + process: { + findUniqueOrThrow: processFindUniqueOrThrow, + update: processUpdate, + updateMany: processUpdateMany, + }, + processStatusHistory: { + create: historyCreate, + findMany: jest.fn().mockResolvedValue([]), + }, + processRejection: { create: rejectionCreate }, + meetingSession: { deleteMany: meetingSessionDeleteMany }, + }; + const prisma = { + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + return { + service: new ProcessesService(prisma, { + sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined), + } as any), + processUpdate, + processUpdateMany, + processFindUniqueOrThrow, + historyCreate, + rejectionCreate, + meetingSessionDeleteMany, + tx, + }; + } + + it.each([ + ProcessStatus.NEGOTIATION, + ProcessStatus.DOCUMENTATION, + ProcessStatus.COMPLETED, + ])('CUSTOMER não pode avançar seu processo para %s', async (nextStatus) => { + const { service, processUpdateMany } = updateService(); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: nextStatus, notes: 'tentativa indevida' }, + ownerClientId, + UserRole.CUSTOMER, + ), + ).rejects.toThrow(ForbiddenException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('OFFICE de outra empresa não pode alterar status', async () => { + const { service, processUpdateMany } = updateService(); + + await expect( + (service.update as any)( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.NEGOTIATION }, + 'office-1', + UserRole.OFFICE, + otherCompanyId, + ), + ).rejects.toThrow(ForbiddenException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('especialista atribuído não pode pular de SCHEDULING para COMPLETED', async () => { + const { service, processUpdateMany } = updateService(); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.COMPLETED }, + assignedSpecialistId, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(BadRequestException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('especialista atribuído congela o produto ao entrar em NEGOTIATION', async () => { + const process = protectedProcess({ + product_type: ProductType.CAR, + car_id: productId, + negotiation_currency: null, + negotiation_product_value: null, + car: { + id: productId, + valor: new Prisma.Decimal('120000.00'), + currency: ProductCurrency.USD, + }, + }); + const { service, processUpdateMany } = updateService(process); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.NEGOTIATION }, + assignedSpecialistId, + UserRole.SPECIALIST, + ), + ).resolves.toBeDefined(); + + expect(processUpdateMany).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + status: ProcessStatus.NEGOTIATION, + negotiation_currency: ProductCurrency.USD, + negotiation_product_value: new Prisma.Decimal('120000.00'), + }), + }), + ); + }); + + it('OFFICE da empresa do cliente usa a mesma entrada serializada em NEGOTIATION', async () => { + const process = protectedProcess({ + product_type: ProductType.CAR, + car_id: productId, + negotiation_currency: null, + negotiation_product_value: null, + car: { + id: productId, + valor: new Prisma.Decimal('120000.00'), + currency: ProductCurrency.USD, + }, + }); + const { service, processUpdateMany } = updateService(process); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.NEGOTIATION }, + 'office-1', + UserRole.OFFICE, + clientCompanyId, + ), + ).resolves.toBeDefined(); + + expect(processUpdateMany).toHaveBeenCalledTimes(1); + }); + + it('não promove consultoria sem produto/snapshot de NEGOTIATION para DOCUMENTATION', async () => { + const { service, processUpdateMany } = updateService( + protectedProcess({ status: ProcessStatus.NEGOTIATION }), + ); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.DOCUMENTATION }, + assignedSpecialistId, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(BadRequestException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('permite apenas NEGOTIATION para DOCUMENTATION com produto e snapshot', async () => { + const process = protectedProcess({ + status: ProcessStatus.NEGOTIATION, + product_type: ProductType.CAR, + car_id: productId, + negotiation_currency: ProductCurrency.USD, + negotiation_product_value: new Prisma.Decimal('120000.00'), + car: { id: productId, marca: 'Porsche', modelo: '911' }, + }); + const { service, processUpdateMany } = updateService(process); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.DOCUMENTATION }, + assignedSpecialistId, + UserRole.SPECIALIST, + ), + ).resolves.toBeDefined(); + + expect(processUpdateMany).toHaveBeenCalledTimes(1); + }); + + it('revalida a transição após adquirir o lock e reler o processo', async () => { + const negotiableProcess = protectedProcess({ + status: ProcessStatus.NEGOTIATION, + product_type: ProductType.CAR, + car_id: productId, + negotiation_currency: ProductCurrency.USD, + negotiation_product_value: new Prisma.Decimal('120000.00'), + car: { id: productId, marca: 'Porsche', modelo: '911' }, + }); + const rejectedProcess = { + ...negotiableProcess, + status: ProcessStatus.REJECTED, + }; + const { service, processUpdateMany, tx } = updateService(); + tx.process.findUniqueOrThrow + .mockResolvedValueOnce(negotiableProcess) + .mockResolvedValueOnce(rejectedProcess); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.DOCUMENTATION }, + assignedSpecialistId, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(BadRequestException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('revalida a autorização após adquirir o lock e reler o processo', async () => { + const initiallyAuthorized = protectedProcess({ + status: ProcessStatus.NEGOTIATION, + }); + const movedToOtherCompany = protectedProcess({ + status: ProcessStatus.NEGOTIATION, + client: { + ...protectedProcess().client, + company_id: otherCompanyId, + consultant: { company_id: otherCompanyId }, + }, + }); + const { service, processUpdateMany, tx } = updateService(); + tx.process.findUniqueOrThrow + .mockResolvedValueOnce(initiallyAuthorized) + .mockResolvedValueOnce(movedToOtherCompany); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.DOCUMENTATION }, + 'office-1', + UserRole.OFFICE, + clientCompanyId, + ), + ).rejects.toThrow(ForbiddenException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('não conclui DOCUMENTATION manualmente sem o webhook de contrato', async () => { + const { service, processUpdateMany } = updateService( + protectedProcess({ status: ProcessStatus.DOCUMENTATION }), + ); + + await expect( + service.update( + '99999999-9999-4999-8999-999999999999', + { status: ProcessStatus.COMPLETED }, + assignedSpecialistId, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(BadRequestException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('outsider não pode rejeitar processo alheio', async () => { + const { service, processUpdate, tx } = rejectionService(); + + await expect( + (service.rejectProcess as any)( + '99999999-9999-4999-8999-999999999999', + outsiderId, + undefined, + UserRole.CUSTOMER, + null, + ), + ).rejects.toThrow(ForbiddenException); + + expect(processUpdate).not.toHaveBeenCalled(); + expect(tx.$queryRaw).not.toHaveBeenCalled(); + }); + + it.each([ + [ + 'cliente', + StatusAgendamento.PENDING, + ownerClientId, + UserRole.CUSTOMER, + 'Cancele o agendamento pelo fluxo próprio', + ], + [ + 'especialista', + StatusAgendamento.PENDING, + assignedSpecialistId, + UserRole.SPECIALIST, + 'Cancele o agendamento pelo fluxo próprio', + ], + [ + 'cliente', + StatusAgendamento.SCHEDULED, + ownerClientId, + UserRole.CUSTOMER, + 'Cancele o agendamento pelo fluxo próprio', + ], + [ + 'especialista', + StatusAgendamento.SCHEDULED, + assignedSpecialistId, + UserRole.SPECIALIST, + 'Cancele o agendamento pelo fluxo próprio', + ], + ])( + '%s não rejeita processo com appointment %s', + async (_label, appointmentStatus, actorId, actorRole, expectedMessage) => { + const { service, processUpdateMany, historyCreate, rejectionCreate, tx } = + rejectionService( + protectedProcess({ + appointment_id: 'abababab-abab-4bab-8bab-abababababab', + appointment: { + id: 'abababab-abab-4bab-8bab-abababababab', + client_id: ownerClientId, + specialist_id: assignedSpecialistId, + status: appointmentStatus, + }, + }), + ); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + actorId, + undefined, + actorRole, + ), + ).rejects.toThrow(expectedMessage); + + expect(tx.$queryRaw).toHaveBeenCalledTimes(1); + expect(processUpdateMany).not.toHaveBeenCalled(); + expect(historyCreate).not.toHaveBeenCalled(); + expect(rejectionCreate).not.toHaveBeenCalled(); + }, + ); + + it.each([ + ['cliente', ownerClientId, UserRole.CUSTOMER], + ['especialista', assignedSpecialistId, UserRole.SPECIALIST], + ])( + '%s não rejeita processo com reunião ativa', + async (_label, actorId, actorRole) => { + const { service, processUpdateMany, historyCreate, rejectionCreate } = + rejectionService( + protectedProcess({ + meeting_session: { ended_at: null }, + }), + ); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + actorId, + undefined, + actorRole, + ), + ).rejects.toThrow(BadRequestException); + + expect(processUpdateMany).not.toHaveBeenCalled(); + expect(historyCreate).not.toHaveBeenCalled(); + expect(rejectionCreate).not.toHaveBeenCalled(); + }, + ); + + it('remove claim de inicialização vencido sob lock e permite rejeitar', async () => { + const { service, meetingSessionDeleteMany, processUpdateMany, tx } = + rejectionService( + protectedProcess({ + meeting_session: { + id: 'dddddddd-dddd-4ddd-8ddd-dddddddddddd', + calendar_event_id: 'meeting-init:claim-vencido', + started_at: new Date(Date.now() - 3 * 60 * 1000), + ended_at: null, + }, + }), + ); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + ownerClientId, + 'Não tenho mais interesse', + UserRole.CUSTOMER, + ), + ).resolves.toEqual( + expect.objectContaining({ status: ProcessStatus.REJECTED }), + ); + + expect(tx.$queryRaw).toHaveBeenCalledTimes(1); + expect(meetingSessionDeleteMany).toHaveBeenCalledWith({ + where: { + id: 'dddddddd-dddd-4ddd-8ddd-dddddddddddd', + calendar_event_id: 'meeting-init:claim-vencido', + }, + }); + expect(meetingSessionDeleteMany.mock.invocationCallOrder[0]).toBeLessThan( + processUpdateMany.mock.invocationCallOrder[0], + ); + }); + + it('mantém claim de inicialização recente e bloqueia rejeição', async () => { + const { service, meetingSessionDeleteMany, processUpdateMany } = + rejectionService( + protectedProcess({ + meeting_session: { + id: 'dddddddd-dddd-4ddd-8ddd-dddddddddddd', + calendar_event_id: 'meeting-init:claim-recente', + started_at: new Date(), + ended_at: null, + }, + }), + ); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + ownerClientId, + undefined, + UserRole.CUSTOMER, + ), + ).rejects.toThrow(BadRequestException); + + expect(meetingSessionDeleteMany).not.toHaveBeenCalled(); + expect(processUpdateMany).not.toHaveBeenCalled(); + }); + + it('cliente pode rejeitar o próprio processo sem appointment', async () => { + const { service, processUpdate, processUpdateMany, tx } = + rejectionService(); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + ownerClientId, + 'Não tenho mais interesse', + UserRole.CUSTOMER, + ), + ).resolves.toEqual( + expect.objectContaining({ status: ProcessStatus.REJECTED }), + ); + + expect(tx.$queryRaw).toHaveBeenCalledWith( + expect.anything(), + `appointment-schedule:${assignedSpecialistId}`, + ); + expect(processUpdateMany).toHaveBeenCalledWith({ + where: expect.objectContaining({ + id: '99999999-9999-4999-8999-999999999999', + status: ProcessStatus.SCHEDULING, + updated_at: new Date('2026-01-01T00:00:00.000Z'), + }), + data: expect.objectContaining({ status: ProcessStatus.REJECTED }), + }); + expect(processUpdate).not.toHaveBeenCalled(); + }); + + it('especialista pode rejeitar processo com appointment cancelado e reunião encerrada', async () => { + const appointmentId = 'abababab-abab-4bab-8bab-abababababab'; + const { service, processUpdateMany } = rejectionService( + protectedProcess({ + appointment_id: appointmentId, + appointment: { + id: appointmentId, + client_id: ownerClientId, + specialist_id: assignedSpecialistId, + status: StatusAgendamento.CANCELLED, + }, + meeting_session: { ended_at: new Date('2026-01-01T12:00:00.000Z') }, + }), + ); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + assignedSpecialistId, + undefined, + UserRole.SPECIALIST, + ), + ).resolves.toEqual( + expect.objectContaining({ status: ProcessStatus.REJECTED }), + ); + + expect(processUpdateMany).toHaveBeenCalledTimes(1); + }); + + it.each([ + ['cliente', ownerClientId, UserRole.CUSTOMER, null], + [ + 'especialista', + assignedSpecialistId, + UserRole.SPECIALIST, + { ended_at: new Date('2026-01-01T12:00:00.000Z') }, + ], + ])( + '%s pode rejeitar processo pós-reunião com appointment concluído', + async (_label, actorId, actorRole, meetingSession) => { + const appointmentId = 'abababab-abab-4bab-8bab-abababababab'; + const { service, processUpdateMany } = rejectionService( + protectedProcess({ + status: ProcessStatus.NEGOTIATION, + appointment_id: appointmentId, + appointment: { + id: appointmentId, + client_id: ownerClientId, + specialist_id: assignedSpecialistId, + status: StatusAgendamento.COMPLETED, + }, + meeting_session: meetingSession, + }), + ); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + actorId, + undefined, + actorRole, + ), + ).resolves.toEqual( + expect.objectContaining({ status: ProcessStatus.REJECTED }), + ); + + expect(processUpdateMany).toHaveBeenCalledTimes(1); + }, + ); + + it.each([ + [ + 'id', + { + appointment_id: 'abababab-abab-4bab-8bab-abababababab', + appointment: { + id: 'cdcdcdcd-cdcd-4dcd-8dcd-cdcdcdcdcdcd', + client_id: ownerClientId, + specialist_id: assignedSpecialistId, + status: StatusAgendamento.CANCELLED, + }, + }, + ], + [ + 'cliente', + { + appointment_id: 'abababab-abab-4bab-8bab-abababababab', + appointment: { + id: 'abababab-abab-4bab-8bab-abababababab', + client_id: outsiderId, + specialist_id: assignedSpecialistId, + status: StatusAgendamento.CANCELLED, + }, + }, + ], + [ + 'especialista', + { + appointment_id: 'abababab-abab-4bab-8bab-abababababab', + appointment: { + id: 'abababab-abab-4bab-8bab-abababababab', + client_id: ownerClientId, + specialist_id: outsiderId, + status: StatusAgendamento.CANCELLED, + }, + }, + ], + ])( + 'não rejeita quando o %s do appointment diverge do processo', + async (_field, overrides) => { + const { service, processUpdateMany, historyCreate, rejectionCreate } = + rejectionService(protectedProcess(overrides)); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + assignedSpecialistId, + undefined, + UserRole.SPECIALIST, + ), + ).rejects.toThrow('Agendamento não corresponde aos participantes'); + + expect(processUpdateMany).not.toHaveBeenCalled(); + expect(historyCreate).not.toHaveBeenCalled(); + expect(rejectionCreate).not.toHaveBeenCalled(); + }, + ); + + it('rejeição perde a CAS sem criar histórico nem motivo', async () => { + const { service, historyCreate, rejectionCreate, processUpdateMany } = + rejectionService(protectedProcess(), 0); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + assignedSpecialistId, + undefined, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(ConflictException); + + expect(processUpdateMany).toHaveBeenCalledTimes(1); + expect(historyCreate).not.toHaveBeenCalled(); + expect(rejectionCreate).not.toHaveBeenCalled(); + }); + + it('não permite rejeitar processo já concluído', async () => { + const { service, processUpdate } = rejectionService( + protectedProcess({ status: ProcessStatus.COMPLETED }), + ); + + await expect( + service.rejectProcess( + '99999999-9999-4999-8999-999999999999', + assignedSpecialistId, + undefined, + UserRole.SPECIALIST, + ), + ).rejects.toThrow(BadRequestException); + + expect(processUpdate).not.toHaveBeenCalled(); + }); + + it.each([ + ['completion reason', 'getProcessCompletionReason'], + ['active contract', 'getByIdWithActiveContract'], + ])('outsider não pode ler %s', async (_label, method) => { + const prisma = { + process: { findUnique: jest.fn().mockResolvedValue(protectedProcess()) }, + processStatusHistory: { + findFirst: jest.fn().mockResolvedValue({ reason: 'CONTRACT_SIGNED' }), + }, + contract: { + findUnique: jest.fn().mockResolvedValue({ id: 'contract-1' }), + }, + } as any; + const service = new ProcessesService(prisma, {} as any); + + await expect( + (service[method] as any)('99999999-9999-4999-8999-999999999999', { + id: outsiderId, + role: UserRole.CUSTOMER, + companyId: null, + }), + ).rejects.toThrow(ForbiddenException); + }); + + it.each([ + ['completion reason', 'getProcessCompletionReason'], + ['active contract', 'getByIdWithActiveContract'], + ])('OFFICE de outra empresa não pode ler %s', async (_label, method) => { + const prisma = { + process: { findUnique: jest.fn().mockResolvedValue(protectedProcess()) }, + processStatusHistory: { + findFirst: jest.fn().mockResolvedValue({ reason: 'CONTRACT_SIGNED' }), + }, + contract: { + findUnique: jest.fn().mockResolvedValue({ id: 'contract-1' }), + }, + } as any; + const service = new ProcessesService(prisma, {} as any); + + await expect( + (service[method] as any)('99999999-9999-4999-8999-999999999999', { + id: 'office-1', + role: UserRole.OFFICE, + companyId: otherCompanyId, + }), + ).rejects.toThrow(ForbiddenException); + }); + + it.each([ + [UserRole.CONSULTANT, consultantId, null], + [UserRole.OFFICE, 'office-1', clientCompanyId], + ])( + '%s vinculado ao cliente pode ler contrato ativo', + async (role, id, companyId) => { + const prisma = { + process: { + findUnique: jest.fn().mockResolvedValue(protectedProcess()), + }, + contract: { + findUnique: jest.fn().mockResolvedValue({ id: 'contract-1' }), + }, + } as any; + const service = new ProcessesService(prisma, {} as any); + + await expect( + service.getByIdWithActiveContract( + '99999999-9999-4999-8999-999999999999', + { id, role, companyId }, + ), + ).resolves.toEqual( + expect.objectContaining({ id: protectedProcess().id }), + ); + }, + ); + + it('OFFICE mantém acesso quando o consultor é da empresa, mesmo com vínculo direto legado diferente', async () => { + const process = protectedProcess({ + client: { + id: ownerClientId, + consultant_id: consultantId, + company_id: otherCompanyId, + consultant: { company_id: clientCompanyId }, + }, + }); + const prisma = { + process: { findUnique: jest.fn().mockResolvedValue(process) }, + contract: { + findUnique: jest.fn().mockResolvedValue({ id: 'contract-1' }), + }, + } as any; + const service = new ProcessesService(prisma, {} as any); + + await expect( + service.getByIdWithActiveContract(process.id, { + id: 'office-1', + role: UserRole.OFFICE, + companyId: clientCompanyId, + }), + ).resolves.toEqual(expect.objectContaining({ id: process.id })); + }); +}); + +describe('ProcessesService.cancelAppointment — serialização canônica', () => { + it('adquire o lock da agenda e revalida processo/appointment dentro da transação', async () => { + const process = { + id: 'process-1', + client_id: clientId, + specialist_id: specialistId, + status: ProcessStatus.SCHEDULING, + updated_at: new Date('2026-01-01T00:00:00.000Z'), + product_type: ProductType.CAR, + appointment_id: 'appointment-1', + appointment: { + id: 'appointment-1', + client_id: clientId, + specialist_id: specialistId, + status: StatusAgendamento.SCHEDULED, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + }, + client: { + id: clientId, + name: 'Cliente', + surname: 'Teste', + email: 'cliente@example.com', + }, + specialist: { + id: specialistId, + name: 'Especialista', + surname: 'Teste', + email: 'especialista@example.com', + }, + car: { marca: 'Porsche', modelo: '911' }, + boat: null, + aircraft: null, + }; + const historyDelete = jest.fn().mockResolvedValue({ count: 1 }); + const processClaim = jest.fn().mockResolvedValue({ count: 1 }); + const processDelete = jest.fn().mockResolvedValue(process); + const appointmentDelete = jest.fn().mockResolvedValue(process.appointment); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + process: { + findUnique: jest.fn().mockResolvedValue(process), + updateMany: processClaim, + delete: processDelete, + }, + appointment: { delete: appointmentDelete }, + processStatusHistory: { deleteMany: historyDelete }, + }; + const prisma = { + process: { + findUnique: jest.fn().mockResolvedValue(process), + }, + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const notifications = { + sendAppointmentCancelledEmail: jest.fn().mockResolvedValue(undefined), + }; + const service = new ProcessesService(prisma, notifications as any); + + await service.cancelAppointment(process.id, clientId); + + expect(tx.$queryRaw).toHaveBeenCalledWith( + expect.anything(), + `appointment-schedule:${specialistId}`, + ); + expect(tx.process.findUnique).toHaveBeenCalledWith( + expect.objectContaining({ where: { id: process.id, removed_at: null } }), + ); + expect(historyDelete).toHaveBeenCalledWith({ + where: { processId: process.id }, + }); + expect(processClaim).toHaveBeenCalledWith({ + where: { + id: process.id, + removed_at: null, + status: ProcessStatus.SCHEDULING, + updated_at: process.updated_at, + }, + data: { updated_at: expect.any(Date) }, + }); + expect(processClaim.mock.invocationCallOrder[0]).toBeLessThan( + historyDelete.mock.invocationCallOrder[0], + ); + expect(processDelete).toHaveBeenCalledWith({ + where: { id: process.id }, + }); + expect(appointmentDelete).toHaveBeenCalledWith({ + where: { id: process.appointment.id }, + }); + }); + + it('não apaga processo SCHEDULING quando o appointment já está COMPLETED', async () => { + const process = { + id: 'process-1', + client_id: clientId, + specialist_id: specialistId, + status: ProcessStatus.SCHEDULING, + updated_at: new Date('2026-01-01T00:00:00.000Z'), + appointment_id: 'appointment-1', + appointment: { + id: 'appointment-1', + client_id: clientId, + specialist_id: specialistId, + status: StatusAgendamento.COMPLETED, + }, + client: { id: clientId }, + specialist: { id: specialistId }, + car: null, + boat: null, + aircraft: null, + }; + const processClaim = jest.fn(); + const processDelete = jest.fn(); + const appointmentDelete = jest.fn(); + const historyDelete = jest.fn(); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + process: { + findUnique: jest.fn().mockResolvedValue(process), + updateMany: processClaim, + delete: processDelete, + }, + appointment: { delete: appointmentDelete }, + processStatusHistory: { deleteMany: historyDelete }, + }; + const prisma = { + process: { findUnique: jest.fn().mockResolvedValue(process) }, + $transaction: jest.fn(async (callback) => callback(tx)), + } as any; + const service = new ProcessesService(prisma, {} as any); + + await expect( + service.cancelAppointment(process.id, clientId), + ).rejects.toThrow( + 'Apenas agendamentos pendentes ou agendados podem ser cancelados', + ); + + expect(processClaim).not.toHaveBeenCalled(); + expect(historyDelete).not.toHaveBeenCalled(); + expect(processDelete).not.toHaveBeenCalled(); + expect(appointmentDelete).not.toHaveBeenCalled(); + }); +}); diff --git a/backend/src/features/processes/processes.service.ts b/backend/src/features/processes/processes.service.ts index 81f21813..c5ca8946 100644 --- a/backend/src/features/processes/processes.service.ts +++ b/backend/src/features/processes/processes.service.ts @@ -7,6 +7,7 @@ import { Logger, ForbiddenException, HttpException, + Optional, } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { CreateProcessDTO } from './dto/create-process.dto'; @@ -18,8 +19,11 @@ import { import { QueryDto } from 'src/shared/dto/query.dto'; import { AppointmentSchedulingMethod, + Prisma, ProcessStatus, + ProductCurrency, ProductType, + ProviderStatus, StatusAgendamento, UserRole, } from '@prisma/client'; @@ -35,13 +39,19 @@ import { import { validateSpecialistProductAssociation } from '../products/product-association-validator'; import { acquireActiveProcessDedupLock, + assertNoActiveProcess, lockAndAssertNoActiveProcess, } from './process-dedup-lock'; import { parseDate, isFutureDate } from 'src/shared/utils/date.utils'; +import { isISO8601 } from 'class-validator'; +import { PENDING_APPOINTMENT_DATETIME_PATTERN } from '../appointments/dto'; import { acquireSpecialistScheduleLock, assertSpecialistScheduleAvailable, } from '../appointments/appointment-schedule-lock'; +import { isStaleMeetingInitializationClaim } from '../meetings/meeting-initialization-claim'; +import { ActorContext } from 'src/shared/actor-context/actor-context.service'; +import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service'; /** * Quem está pedindo a operação. `companyId` só é usado por OFFICE. @@ -52,6 +62,31 @@ export type ProcessesRequester = { companyId?: string | null; }; +type ProcessAccessAction = 'read' | 'update-status' | 'reject'; + +type ProcessAccessRecord = { + client_id: string; + specialist_id: string; + removed_at?: Date | null; + client?: { + consultant_id?: string | null; + company_id?: string | null; + consultant?: { company_id?: string | null } | null; + } | null; +}; + +const PROCESS_STATUS_TRANSITIONS: Record< + ProcessStatus, + readonly ProcessStatus[] +> = { + [ProcessStatus.SCHEDULING]: [ProcessStatus.NEGOTIATION], + [ProcessStatus.NEGOTIATION]: [ProcessStatus.DOCUMENTATION], + [ProcessStatus.PROCESSING_CONTRACT]: [], + [ProcessStatus.DOCUMENTATION]: [], + [ProcessStatus.COMPLETED]: [], + [ProcessStatus.REJECTED]: [], +}; + /** * Dados para abrir um processo em nome de um cliente. * @@ -75,8 +110,173 @@ export class ProcessesService { constructor( private readonly prismaService: PrismaService, private readonly notificationService: NotificationService, + @Optional() + private readonly delegatedAudit?: DelegatedActionAuditService, ) {} + async getAdminClientOptions(search?: string) { + const normalizedSearch = search?.trim(); + return this.prismaService.user.findMany({ + where: { + role: UserRole.CUSTOMER, + is_active: true, + ...(normalizedSearch + ? { + OR: [ + { name: { contains: normalizedSearch, mode: 'insensitive' } }, + { + surname: { contains: normalizedSearch, mode: 'insensitive' }, + }, + { email: { contains: normalizedSearch, mode: 'insensitive' } }, + ], + } + : {}), + }, + select: { id: true, name: true, surname: true, email: true }, + orderBy: [{ name: 'asc' }, { surname: 'asc' }], + take: 50, + }); + } + + private assertRepresentedSpecialist( + context: ActorContext | undefined, + specialistId: string, + ): void { + if (context && context.specialistId !== specialistId) { + throw new ForbiddenException( + 'O processo não pertence ao especialista representado.', + ); + } + } + + /** + * Política única de acesso a um processo. Todo papel desconhecido e toda + * combinação de ação/vínculo não declarada são negados por padrão. + */ + private assertProcessAccess( + process: ProcessAccessRecord, + requester: ProcessesRequester, + action: ProcessAccessAction, + ): void { + if ( + process.removed_at && + (action !== 'read' || requester.role !== UserRole.ADMIN) + ) { + throw new NotFoundException('Processo não encontrado'); + } + const isAssignedSpecialist = + requester.role === UserRole.SPECIALIST && + process.specialist_id === requester.id; + const isClient = + requester.role === UserRole.CUSTOMER && + process.client_id === requester.id; + const isClientConsultant = + requester.role === UserRole.CONSULTANT && + process.client?.consultant_id === requester.id; + const isClientOffice = + requester.role === UserRole.OFFICE && + !!requester.companyId && + (process.client?.company_id === requester.companyId || + process.client?.consultant?.company_id === requester.companyId); + + const allowed = + requester.role === UserRole.ADMIN || + (action === 'read' && + (isAssignedSpecialist || + isClient || + isClientConsultant || + isClientOffice)) || + (action === 'update-status' && + (isAssignedSpecialist || isClientOffice)) || + (action === 'reject' && (isAssignedSpecialist || isClient)); + + if (!allowed) { + this.logger.warn( + `[process-access] negado action=${action} role=${requester.role} user=${requester.id}`, + ); + throw new ForbiddenException( + 'Você não tem permissão para acessar este processo', + ); + } + } + + private assertStatusTransition( + currentStatus: ProcessStatus, + nextStatus: ProcessStatus, + ): void { + if (!PROCESS_STATUS_TRANSITIONS[currentStatus]?.includes(nextStatus)) { + throw new BadRequestException( + `Transição de ${currentStatus} para ${nextStatus} não permitida`, + ); + } + } + + private assertManualStatusPreconditions( + process: ProcessWithProducts & { + negotiation_currency?: ProductCurrency | null; + negotiation_product_value?: Prisma.Decimal | null; + }, + nextStatus: ProcessStatus, + ): void { + if (nextStatus !== ProcessStatus.DOCUMENTATION) return; + + const hasNegotiationProduct = + !!process.product_type && + !!this.getProductId(process) && + !!this.buildProduct(process); + const hasNegotiationSnapshot = + process.negotiation_currency != null && + process.negotiation_product_value != null; + + if (!hasNegotiationProduct || !hasNegotiationSnapshot) { + throw new BadRequestException( + 'O processo precisa de produto e snapshot de negociação antes da documentação', + ); + } + } + + private throwStatusTransitionConflict(processId: string): never { + throw new ConflictException({ + success: false, + error: { + code: 'PROCESS_STATUS_TRANSITION_CONFLICT', + message: + 'O processo foi alterado por outra operação. Recarregue e tente novamente.', + details: { process_id: processId }, + }, + }); + } + + private async assertNoPendingProposalBeforeDocumentation( + tx: Prisma.TransactionClient, + processId: string, + ): Promise { + const lockKey = `proposal-process:${processId}`; + await tx.$queryRaw` + SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))::text AS locked + `; + const pendingRows = await tx.$queryRaw>` + SELECT "id"::text AS "id" + FROM "NegotiationProposal" + WHERE "process_id" = ${processId}::uuid + AND "status" = 'PENDING'::"ProposalStatus" + LIMIT 1 + FOR UPDATE + `; + const pending = pendingRows.find((row) => typeof row.id === 'string'); + if (pending) { + throw new ConflictException({ + success: false, + error: { + code: 'PENDING_PROPOSAL_BLOCKS_DOCUMENTATION', + message: + 'Responda a proposta pendente antes de avançar para documentação.', + details: { proposal_id: pending.id }, + }, + }); + } + } + /** * Cria um objeto "product" de acordo com o processo enviado * @@ -144,6 +344,26 @@ export class ProcessesService { ); } + private projectClientContacts( + process: any, + requester?: { id?: string; role?: string }, + ): ProcessResponse['client'] { + const visible = + requester?.role === UserRole.SPECIALIST && + requester.id === process.specialist_id && + (this.isAppointmentContactVisible(process.appointment?.status) || + (process.status === ProcessStatus.SCHEDULING && + process.appointment?.status === StatusAgendamento.PENDING && + process.appointment?.scheduling_method === + AppointmentSchedulingMethod.EMAIL)); + return { + id: process.client_id, + name: process.client?.name ?? '', + ...(visible ? { email: process.client?.email ?? '' } : {}), + phone: visible ? (process.client?.phone ?? null) : null, + }; + } + /** * Helper: Retorna descrição formatada do produto para emails * @@ -229,9 +449,9 @@ export class ProcessesService { * Antes disso o endpoint aceitava qualquer `client_id` de qualquer usuário * autenticado: dava para abrir processo em nome de um cliente alheio. * - * O especialista não é restringido a clientes com quem já tem relação — - * abrir o primeiro processo de um cliente novo é justamente o caso de uso - * da tela dele. O que se exige é que ele seja o especialista do processo. + * Especialistas não usam esta rota genérica: o fluxo legítimo parte de um + * pedido autenticado do cliente, ou das rotas delegadas de consultor/escritório. + * Assim, um client_id arbitrário nunca vira um oráculo de dados pessoais. * * @throws {ForbiddenException} - Sem vínculo com o cliente informado */ @@ -257,11 +477,13 @@ export class ProcessesService { case UserRole.ADMIN: return; - case UserRole.SPECIALIST: - if (dto.specialist_id !== requester.id) { - deny('especialista só cria processo para si mesmo'); - } - return; + case UserRole.SPECIALIST: { + // O fluxo legítimo começa pelo pedido autenticado do próprio cliente. + // Esta rota genérica devolve dados do cliente criado; permitir que o + // especialista forneça client_id a transformaria em um oráculo de PII. + deny('especialista deve partir de um pedido do cliente'); + break; + } case UserRole.CUSTOMER: if (dto.client_id !== requester.id) { @@ -316,12 +538,14 @@ export class ProcessesService { async create( createProcessDto: CreateProcessDTO, requester: ProcessesRequester, + context?: ActorContext, ): Promise { this.logger.log( `[create] Iniciando criação de processo para cliente ${createProcessDto.client_id}`, ); await this.assertCanCreateFor(requester, createProcessDto); + this.assertRepresentedSpecialist(context, createProcessDto.specialist_id); const { product_id, client_id, specialist_id, ...dataToSave } = createProcessDto; @@ -379,8 +603,34 @@ export class ProcessesService { productId: hasProduct ? createProcessDto.product_id : null, }); + let appointmentId: string | undefined; + if (context?.actorRole === UserRole.ADMIN) { + const pendingExpiresAt = new Date(); + pendingExpiresAt.setDate(pendingExpiresAt.getDate() + 7); + const appointment = await tx.appointment.create({ + data: { + client_id, + specialist_id, + product_type: hasProduct ? createProcessDto.product_type : null, + product_id: hasProduct ? createProcessDto.product_id : null, + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + user_clicked_at: new Date(), + pending_expires_at: pendingExpiresAt, + notes: 'Criado por administrador em nome do especialista.', + }, + }); + appointmentId = appointment.id; + } + const process = await tx.process.create({ - data: { specialist_id, client_id, ...dataToSave, ...finalProduct }, + data: { + specialist_id, + client_id, + ...dataToSave, + ...finalProduct, + ...(appointmentId ? { appointment_id: appointmentId } : {}), + }, include, }); @@ -388,10 +638,24 @@ export class ProcessesService { data: { processId: process.id, status: process.status, + changed_by: requester.id, changed_at: new Date(), }, }); + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'PROCESS_CREATE', + resourceType: 'PROCESS', + resourceId: process.id, + metadata: { appointmentId: appointmentId ?? null }, + }, + tx, + ); + } + return process; }); @@ -461,6 +725,7 @@ export class ProcessesService { if (isConsultancy) { await acquireActiveProcessDedupLock(tx, processScope); + await assertNoActiveProcess(tx, processScope); const existingAppointment = await tx.appointment.findFirst({ where: { client_id: input.client_id, @@ -651,7 +916,7 @@ export class ProcessesService { // O status fica de fora daqui de propósito: o sumário existe para mostrar // quantos processos há em CADA status, então filtrar por um deles zeraria // os demais e o contador das abas iria a zero ao selecionar uma. - const scopedWhere: any = {}; + const scopedWhere: any = { removed_at: null }; // Filtro de visibilidade por papel. Vai em AND porque a busca textual // abaixo ocupa o OR do nível raiz — se o escopo fosse escrito ali, a busca @@ -771,11 +1036,7 @@ export class ProcessesService { process.appointment?.specialist_rescheduled_from ?? null, product_type: process.product_type, product_id: this.getProductId(process), - client: { - id: process.client_id, - email: process.client?.email, - name: process.client?.name, - }, + client: this.projectClientContacts(process, requester), specialist: { especialidade: process.specialist.speciality, id: process.specialist.id, @@ -804,13 +1065,21 @@ export class ProcessesService { async getById( processId: string, userId?: string, - userRole?: string, + userRole?: UserRole, + companyId?: string | null, ): Promise { try { const process = await this.prismaService.process.findUniqueOrThrow({ - where: { id: processId }, + where: { + id: processId, + ...(userRole === UserRole.ADMIN ? {} : { removed_at: null }), + }, include: { - client: true, + client: { + include: { + consultant: { select: { company_id: true } }, + }, + }, car: true, boat: true, aircraft: true, @@ -827,31 +1096,22 @@ export class ProcessesService { }, }); - if (userId && userRole !== 'ADMIN') { - const isParticipant = - process.client_id === userId || - process.specialist_id === userId || - process.client?.consultant_id === userId; - - if (!isParticipant) { - throw new ForbiddenException({ - success: false, - error: { - code: 403, - message: 'Você não é participante deste processo', - details: { user_id: userId, process_id: processId }, - }, - }); - } - } + this.assertProcessAccess( + process, + { + id: userId ?? '', + role: userRole as UserRole, + companyId, + }, + 'read', + ); const contactVisible = this.isAppointmentContactVisible( process.appointment?.status, ); const isClient = userId === process.client_id; - const isSpecialist = userId === process.specialist_id; - const canSeeClientPhone = isSpecialist && contactVisible; - const canSeeSpecialistPhone = isClient && contactVisible; + const canSeeSpecialistPhone = + userRole === UserRole.CUSTOMER && isClient && contactVisible; return { id: process.id, @@ -867,12 +1127,10 @@ export class ProcessesService { process.appointment?.specialist_rescheduled_from ?? null, product_type: process.product_type, product_id: this.getProductId(process), - client: { - id: process.client_id, - email: process.client?.email || '', - name: process.client?.name || '', - phone: canSeeClientPhone ? (process.client?.phone ?? null) : null, - }, + client: this.projectClientContacts(process, { + id: userId, + role: userRole, + }), specialist: { especialidade: process.specialist.speciality, id: process.specialist.id, @@ -886,7 +1144,10 @@ export class ProcessesService { notes: process.notes, }; } catch (err) { - if (err instanceof ForbiddenException) { + if ( + err instanceof ForbiddenException || + err instanceof NotFoundException + ) { throw err; } if (err.code === 'P2025') { @@ -920,6 +1181,7 @@ export class ProcessesService { this.prismaService.process.findMany({ where: { specialist_id: specialistId, // CRUCIAL FILTER + removed_at: null, }, include: { client: true, @@ -944,6 +1206,7 @@ export class ProcessesService { this.prismaService.process.count({ where: { specialist_id: specialistId, + removed_at: null, }, }), ]); @@ -964,11 +1227,7 @@ export class ProcessesService { process.appointment?.specialist_rescheduled_from ?? null, product_type: process.product_type, product_id: this.getProductId(process), - client: { - id: process.client_id, - email: process.client?.email, - name: process.client?.name, - }, + client: this.projectClientContacts(process), specialist: { especialidade: process.specialist.speciality, id: process.specialist.id, @@ -1013,12 +1272,11 @@ export class ProcessesService { const skip = (pageNum - 1) * perPageNum; const sortBy = options.sortBy || 'created_at'; const order = options.order || 'desc'; - const canSeeClientPhone = - requester.role === UserRole.SPECIALIST && requester.id === specialistId; // Build where clause const where: any = { specialist_id: specialistId, + removed_at: null, }; // Add status filter @@ -1088,16 +1346,7 @@ export class ProcessesService { process.appointment?.specialist_rescheduled_from ?? null, product_type: process.product_type, product_id: this.getProductId(process), - client: { - id: process.client_id, - email: process.client?.email, - name: process.client?.name, - phone: - canSeeClientPhone && - this.isAppointmentContactVisible(process.appointment?.status) - ? (process.client?.phone ?? null) - : null, - }, + client: this.projectClientContacts(process, requester), specialist: { especialidade: process.specialist.speciality, id: process.specialist.id, @@ -1130,6 +1379,8 @@ export class ProcessesService { updateProcessDto: UpdateProcessDto, callerId?: string, callerRole?: UserRole, + callerCompanyId?: string | null, + context?: ActorContext, ): Promise { try { // Transction para atualizar o processo, adicionar mais uma linha sobre o histórico de status do processo, e obter o histórico atualizado @@ -1140,7 +1391,14 @@ export class ProcessesService { where: { id: processId }, include: { client: { - select: { email: true, name: true, surname: true }, + select: { + email: true, + name: true, + surname: true, + consultant_id: true, + company_id: true, + consultant: { select: { company_id: true } }, + }, }, specialist: { select: { email: true, name: true, surname: true }, @@ -1151,33 +1409,99 @@ export class ProcessesService { }, }); - // Autorização: apenas participantes do processo (cliente ou especialista) - // ou staff (ADMIN/OFFICE) podem alterar o status. Evita que qualquer - // usuário autenticado dirija um processo alheio. - const isStaff = - callerRole === UserRole.ADMIN || callerRole === UserRole.OFFICE; - const isParticipant = - !!callerId && - (existingProcess.client_id === callerId || - existingProcess.specialist_id === callerId); - if (!isStaff && !isParticipant) { - throw new ForbiddenException( - 'Você não tem permissão para alterar este processo', + this.assertProcessAccess( + existingProcess, + { + id: callerId ?? '', + role: callerRole as UserRole, + companyId: callerCompanyId, + }, + 'update-status', + ); + this.assertRepresentedSpecialist( + context, + existingProcess.specialist_id, + ); + + const lockedSpecialistId = existingProcess.specialist_id; + await acquireSpecialistScheduleLock(tx, lockedSpecialistId); + existingProcess = await tx.process.findUniqueOrThrow({ + where: { id: processId }, + include: { + client: { + select: { + email: true, + name: true, + surname: true, + consultant_id: true, + company_id: true, + consultant: { select: { company_id: true } }, + }, + }, + specialist: { + select: { email: true, name: true, surname: true }, + }, + car: true, + boat: true, + aircraft: true, + }, + }); + if (existingProcess.specialist_id !== lockedSpecialistId) { + this.throwStatusTransitionConflict(processId); + } + if (updateProcessDto.status === ProcessStatus.DOCUMENTATION) { + await this.assertNoPendingProposalBeforeDocumentation( + tx, + processId, ); } + this.assertProcessAccess( + existingProcess, + { + id: callerId ?? '', + role: callerRole as UserRole, + companyId: callerCompanyId, + }, + 'update-status', + ); + this.assertRepresentedSpecialist( + context, + existingProcess.specialist_id, + ); //Verificar se ele já está com o status atualizado if (existingProcess.status === updateProcessDto.status) { throw new BadRequestException(); } + this.assertStatusTransition( + existingProcess.status, + updateProcessDto.status, + ); + this.assertManualStatusPreconditions( + existingProcess, + updateProcessDto.status, + ); + if (updateProcessDto.status === ProcessStatus.NEGOTIATION) { + // Ordem global: agenda → produto → deduplicação. O lock da agenda + // já foi adquirido antes da releitura acima; congelar o preço só + // depois dele mantém a ordem compatível com confirmPending. + const lockedProductType = existingProcess.product_type; + const lockedProductId = this.getProductId(existingProcess); await lockNegotiationProductMoney(tx, existingProcess); existingProcess = await tx.process.findUniqueOrThrow({ where: { id: processId }, include: { client: { - select: { email: true, name: true, surname: true }, + select: { + email: true, + name: true, + surname: true, + consultant_id: true, + company_id: true, + consultant: { select: { company_id: true } }, + }, }, specialist: { select: { email: true, name: true, surname: true }, @@ -1187,15 +1511,39 @@ export class ProcessesService { aircraft: true, }, }); + if ( + existingProcess.product_type !== lockedProductType || + this.getProductId(existingProcess) !== lockedProductId + ) { + this.throwStatusTransitionConflict(processId); + } + this.assertProcessAccess( + existingProcess, + { + id: callerId ?? '', + role: callerRole as UserRole, + companyId: callerCompanyId, + }, + 'update-status', + ); if (existingProcess.status === updateProcessDto.status) { throw new BadRequestException(); } + this.assertStatusTransition( + existingProcess.status, + updateProcessDto.status, + ); + this.assertManualStatusPreconditions( + existingProcess, + updateProcessDto.status, + ); } const snapshotData = updateProcessDto.status === ProcessStatus.NEGOTIATION ? buildNegotiationSnapshotUpdate(existingProcess) : {}; + const nextUpdatedAt = new Date(); const claim = await tx.process.updateMany({ data: { @@ -1206,21 +1554,14 @@ export class ProcessesService { }, where: { id: processId, + removed_at: null, status: existingProcess.status, updated_at: existingProcess.updated_at, }, }); if (claim.count !== 1) { - throw new ConflictException({ - success: false, - error: { - code: 'PROCESS_STATUS_TRANSITION_CONFLICT', - message: - 'O processo foi alterado por outra operação. Recarregue e tente novamente.', - details: { process_id: processId }, - }, - }); + this.throwStatusTransitionConflict(processId); } const process = await tx.process.findUniqueOrThrow({ @@ -1230,9 +1571,25 @@ export class ProcessesService { data: { processId, status: updateProcessDto.status, + changed_by: callerId, changed_at: nextUpdatedAt, }, }); + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'PROCESS_STATUS_UPDATE', + resourceType: 'PROCESS', + resourceId: processId, + metadata: { + from: existingProcess.status, + to: updateProcessDto.status, + }, + }, + tx, + ); + } const statusHistory = await tx.processStatusHistory.findMany({ where: { processId }, }); @@ -1291,6 +1648,7 @@ export class ProcessesService { dto: { product_type: string; product_id: string }, userId: string, userRole: string, + context?: ActorContext, ): Promise { this.logger.log( `[assignProduct] Iniciando associação de produto ao processo ${processId}`, @@ -1298,7 +1656,7 @@ export class ProcessesService { // 1. Buscar processo const process = await this.prismaService.process.findUnique({ - where: { id: processId }, + where: { id: processId, removed_at: null }, include: { client: true, specialist: true, @@ -1320,7 +1678,11 @@ export class ProcessesService { } // 2. Verificar permissão: apenas especialista do processo ou ADMIN - if (process.specialist_id !== userId && userRole !== 'ADMIN') { + const representedSpecialistId = context?.specialistId ?? userId; + if ( + process.specialist_id !== representedSpecialistId || + (userRole !== 'ADMIN' && process.specialist_id !== userId) + ) { throw new ForbiddenException({ success: false, error: { @@ -1390,7 +1752,7 @@ export class ProcessesService { }); const processForAssignment = await tx.process.findUniqueOrThrow({ - where: { id: processId }, + where: { id: processId, removed_at: null }, include: { client: true, specialist: true, @@ -1399,6 +1761,10 @@ export class ProcessesService { aircraft: true, }, }); + this.assertRepresentedSpecialist( + context, + processForAssignment.specialist_id, + ); const assignmentStateChanged = (processForAssignment.status !== ProcessStatus.SCHEDULING && @@ -1545,6 +1911,7 @@ export class ProcessesService { const claim = await tx.process.updateMany({ where: { id: processId, + removed_at: null, status: processForAssignment.status, product_type: null, car_id: null, @@ -1589,6 +1956,22 @@ export class ProcessesService { }); } + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'PROCESS_ASSIGN_PRODUCT', + resourceType: 'PROCESS', + resourceId: processId, + metadata: { + productType, + productId: dto.product_id, + }, + }, + tx, + ); + } + return tx.process.findUniqueOrThrow({ where: { id: processId }, include: { @@ -1611,7 +1994,9 @@ export class ProcessesService { previousStatus: process.status, currentStatus: updatedProcess.status, changedByName: - `${process.specialist.name} ${process.specialist.surname || ''}`.trim(), + context?.delegated && context.actor + ? `${context.actor.name} ${context.actor.surname}`.trim() + : `${process.specialist.name} ${process.specialist.surname || ''}`.trim(), reason: 'Produto associado ao processo após confirmação da reunião', productDetails: this.getProductDetails(updatedProcess), client: process.client, @@ -1648,18 +2033,35 @@ export class ProcessesService { * @returns {Promise} - Razão de conclusão ou null * @throws {NotFoundException} - Processo não encontrado */ - async getProcessCompletionReason(processId: string): Promise { + async getProcessCompletionReason( + processId: string, + requester: ProcessesRequester, + ): Promise { const process = await this.prismaService.process.findUnique({ where: { id: processId }, - select: { id: true }, + select: { + id: true, + client_id: true, + specialist_id: true, + removed_at: true, + client: { + select: { + consultant_id: true, + company_id: true, + consultant: { select: { company_id: true } }, + }, + }, + }, }); - if (!process) { + if (!process || (process.removed_at && requester.role !== UserRole.ADMIN)) { throw new NotFoundException( `Processo com id ${processId} não encontrado`, ); } + this.assertProcessAccess(process, requester, 'read'); + const statusHistory = await this.prismaService.processStatusHistory.findFirst({ where: { processId }, @@ -1677,22 +2079,32 @@ export class ProcessesService { * @returns {Promise} - Processo com contrato ativo * @throws {NotFoundException} - Processo não encontrado */ - async getByIdWithActiveContract(processId: string): Promise { + async getByIdWithActiveContract( + processId: string, + requester: ProcessesRequester, + ): Promise { const process = await this.prismaService.process.findUnique({ where: { id: processId }, include: { car: true, boat: true, aircraft: true, + client: { + include: { + consultant: { select: { company_id: true } }, + }, + }, }, }); - if (!process) { + if (!process || (process.removed_at && requester.role !== UserRole.ADMIN)) { throw new NotFoundException( `Processo com id ${processId} não encontrado`, ); } + this.assertProcessAccess(process, requester, 'read'); + // Se houver contrato ativo, buscar seus dados completos let activeContract = null; if (process.active_contract_id) { @@ -1740,31 +2152,52 @@ export class ProcessesService { processes: (ProcessResponse & { rejection_reason?: string | null })[]; count: number; }> { - if (userId && userRole !== 'ADMIN' && userId !== clientId) { - const client = await this.prismaService.user.findUnique({ - where: { id: clientId }, - select: { consultant_id: true }, + const deny = (): never => { + throw new ForbiddenException({ + success: false, + error: { + code: 403, + message: 'Você não tem acesso a este cliente', + details: { user_id: userId, client_id: clientId }, + }, }); + }; + if (!userId || !userRole) deny(); - const isConsultantOfClient = - userRole === 'CONSULTANT' && client?.consultant_id === userId; - const isSpecialistWithProcess = - userRole === 'SPECIALIST' && - (await this.prismaService.process.findFirst({ - where: { client_id: clientId, specialist_id: userId }, - select: { id: true }, - })); - - if (!isConsultantOfClient && !isSpecialistWithProcess) { - throw new ForbiddenException({ - success: false, - error: { - code: 403, - message: 'Você não tem acesso a este cliente', - details: { user_id: userId, client_id: clientId }, - }, + const where: Prisma.ProcessWhereInput = { + client_id: clientId, + removed_at: null, + }; + switch (userRole) { + case UserRole.ADMIN: + break; + case UserRole.CUSTOMER: + if (userId !== clientId) deny(); + break; + case UserRole.SPECIALIST: + where.specialist_id = userId; + break; + case UserRole.CONSULTANT: { + const client = await this.prismaService.user.findUnique({ + where: { id: clientId }, + select: { role: true, consultant_id: true }, }); + if ( + client?.role !== UserRole.CUSTOMER || + client.consultant_id !== userId + ) + deny(); + // Repete a capability no próprio filtro de dados. Se o vínculo for + // revogado depois da checagem acima, findMany e count deixam de ler o + // cliente em vez de depender de uma autorização já obsoleta. + where.client = { + role: UserRole.CUSTOMER, + consultant_id: userId, + }; + break; } + default: + deny(); } const pageNum = Number(page) || 1; @@ -1775,9 +2208,7 @@ export class ProcessesService { const [processes, count] = await Promise.all([ this.prismaService.process.findMany({ - where: { - client_id: clientId, - }, + where, include: { client: true, car: true, @@ -1802,11 +2233,7 @@ export class ProcessesService { skip, take: perPageNum, }), - this.prismaService.process.count({ - where: { - client_id: clientId, - }, - }), + this.prismaService.process.count({ where }), ]); const processEntities = processes.map((process: any) => ({ @@ -1823,11 +2250,10 @@ export class ProcessesService { process.appointment?.specialist_rescheduled_from ?? null, product_type: process.product_type, product_id: this.getProductId(process), - client: { - id: process.client_id, - email: process.client?.email, - name: process.client?.name, - }, + client: this.projectClientContacts(process, { + id: userId, + role: userRole, + }), specialist: { especialidade: process.specialist.speciality, id: process.specialist.id, @@ -1867,16 +2293,57 @@ export class ProcessesService { processId: string, rejectedById: string, rejectionReason?: string, + requesterRole?: UserRole, + requesterCompanyId?: string | null, + context?: ActorContext, ): Promise { try { const [updatedProcess, updatedStatusHistory] = await this.prismaService.$transaction(async (tx) => { - // Verificar se o processo existe + const candidate = await tx.process.findUniqueOrThrow({ + where: { id: processId }, + select: { + id: true, + client_id: true, + specialist_id: true, + removed_at: true, + client: { + select: { + consultant_id: true, + company_id: true, + consultant: { select: { company_id: true } }, + }, + }, + }, + }); + this.assertProcessAccess( + candidate, + { + id: rejectedById ?? '', + role: requesterRole as UserRole, + companyId: requesterCompanyId, + }, + 'reject', + ); + this.assertRepresentedSpecialist(context, candidate.specialist_id); + + // Mesma ordem de cancelamento/avanço: agenda do especialista, + // releitura do processo e só então a reivindicação CAS. + await acquireSpecialistScheduleLock(tx, candidate.specialist_id); + const existingProcess = await tx.process.findUniqueOrThrow({ where: { id: processId }, include: { client: { - select: { id: true, email: true, name: true, surname: true }, + select: { + id: true, + email: true, + name: true, + surname: true, + consultant_id: true, + company_id: true, + consultant: { select: { company_id: true } }, + }, }, specialist: { select: { id: true, email: true, name: true, surname: true }, @@ -1884,31 +2351,159 @@ export class ProcessesService { car: true, boat: true, aircraft: true, + appointment: { + select: { + id: true, + client_id: true, + specialist_id: true, + status: true, + }, + }, + meeting_session: { + select: { + id: true, + calendar_event_id: true, + started_at: true, + ended_at: true, + }, + }, + active_contract: { + select: { + id: true, + provider_id: true, + provider_status: true, + }, + }, }, }); + this.assertProcessAccess( + existingProcess, + { + id: rejectedById ?? '', + role: requesterRole as UserRole, + companyId: requesterCompanyId, + }, + 'reject', + ); + this.assertRepresentedSpecialist( + context, + existingProcess.specialist_id, + ); + // Verificar se já está rejeitado if (existingProcess.status === 'REJECTED') { throw new BadRequestException('Processo já está rejeitado'); } + if (existingProcess.status === ProcessStatus.COMPLETED) { + throw new BadRequestException( + 'Processo concluído não pode ser rejeitado', + ); + } + if ( + existingProcess.active_contract?.provider_id && + !new Set([ + ProviderStatus.DECLINED, + ProviderStatus.VOIDED, + ProviderStatus.TIMEDOUT, + ProviderStatus.ERROR, + ]).has( + existingProcess.active_contract.provider_status as ProviderStatus, + ) + ) { + throw new BadRequestException( + 'O contrato ativo ainda possui um envelope DocuSign vigente. Anule e reconcilie o envelope antes de rejeitar o processo.', + ); + } + if ( + Boolean(existingProcess.appointment) !== + Boolean(existingProcess.appointment_id) || + (existingProcess.appointment && + (existingProcess.appointment.id !== + existingProcess.appointment_id || + existingProcess.appointment.client_id !== + existingProcess.client_id || + existingProcess.appointment.specialist_id !== + existingProcess.specialist_id)) + ) { + throw new BadRequestException( + 'Agendamento não corresponde aos participantes do processo', + ); + } + if ( + existingProcess.appointment && + (existingProcess.appointment.status === StatusAgendamento.PENDING || + existingProcess.appointment.status === + StatusAgendamento.SCHEDULED) + ) { + throw new BadRequestException( + 'Cancele o agendamento pelo fluxo próprio antes de rejeitar o processo', + ); + } + if ( + existingProcess.meeting_session && + !existingProcess.meeting_session.ended_at + ) { + if ( + isStaleMeetingInitializationClaim(existingProcess.meeting_session) + ) { + const staleClaimCleanup = await tx.meetingSession.deleteMany({ + where: { + id: existingProcess.meeting_session.id, + calendar_event_id: + existingProcess.meeting_session.calendar_event_id, + }, + }); + if (staleClaimCleanup.count !== 1) { + throw new ConflictException( + 'A inicialização da reunião mudou. Recarregue e tente novamente.', + ); + } + } else { + throw new BadRequestException( + 'Encerre a reunião antes de rejeitar o processo', + ); + } + } - // Atualizar status para REJECTED - const process = await tx.process.update({ + const rejectedAt = new Date(); + const claim = await tx.process.updateMany({ data: { - status: 'REJECTED', - updated_at: new Date(), + status: ProcessStatus.REJECTED, + updated_at: rejectedAt, }, where: { id: processId, + removed_at: null, + client_id: existingProcess.client_id, + specialist_id: existingProcess.specialist_id, + status: existingProcess.status, + updated_at: existingProcess.updated_at, }, }); + if (claim.count !== 1) { + throw new ConflictException({ + success: false, + error: { + code: 'PROCESS_REJECTION_CONFLICT', + message: + 'O processo foi alterado por outra operação. Recarregue e tente novamente.', + details: { process_id: processId }, + }, + }); + } + + const process = await tx.process.findUniqueOrThrow({ + where: { id: processId }, + }); // Criar registro de histórico await tx.processStatusHistory.create({ data: { processId, - status: 'REJECTED', - changed_at: process.updated_at, + status: ProcessStatus.REJECTED, + changed_by: rejectedById, + changed_at: rejectedAt, }, }); @@ -1922,6 +2517,21 @@ export class ProcessesService { }, }); } + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'PROCESS_REJECT', + resourceType: 'PROCESS', + resourceId: processId, + metadata: { + from: existingProcess.status, + reason: rejectionReason ?? null, + }, + }, + tx, + ); + } // Buscar histórico atualizado const statusHistory = await tx.processStatusHistory.findMany({ @@ -1929,11 +2539,13 @@ export class ProcessesService { }); const changedByName = - rejectedById === existingProcess.client?.id - ? `${existingProcess.client?.name || ''} ${existingProcess.client?.surname || ''}`.trim() - : rejectedById === existingProcess.specialist?.id - ? `${existingProcess.specialist?.name || ''} ${existingProcess.specialist?.surname || ''}`.trim() - : undefined; + context?.delegated && context.actor + ? `${context.actor.name} ${context.actor.surname}`.trim() + : rejectedById === existingProcess.client?.id + ? `${existingProcess.client?.name || ''} ${existingProcess.client?.surname || ''}`.trim() + : rejectedById === existingProcess.specialist?.id + ? `${existingProcess.specialist?.name || ''} ${existingProcess.specialist?.surname || ''}`.trim() + : undefined; this.notifyProcessStatusChange({ processId, @@ -1957,6 +2569,9 @@ export class ProcessesService { status_history: updatedStatusHistory, }; } catch (err) { + if (err instanceof HttpException) { + throw err; + } if (err.code === 'P2025') { throw new NotFoundException('Processo não encontrado'); } @@ -1984,26 +2599,16 @@ export class ProcessesService { processId: string, userId: string, appointmentDatetime?: string, + context?: ActorContext, ): Promise { this.logger.log( `[confirmAppointment] Confirmando agendamento do processo ${processId}`, ); - // Buscar processo com appointment, client, specialist e produtos + // A leitura inicial identifica apenas o especialista para o lock. const process = await this.prismaService.process.findUnique({ - where: { id: processId }, - include: { - appointment: true, - client: { - select: { id: true, email: true, name: true, surname: true }, - }, - specialist: { - select: { id: true, email: true, name: true, surname: true }, - }, - car: true, - boat: true, - aircraft: true, - }, + where: { id: processId, removed_at: null }, + select: { id: true, specialist_id: true }, }); if (!process) { @@ -2011,66 +2616,37 @@ export class ProcessesService { } // Verificar se o usuário é o especialista - if (process.specialist_id !== userId) { + const representedSpecialistId = context?.specialistId ?? userId; + if (process.specialist_id !== representedSpecialistId) { throw new ForbiddenException( 'Apenas o especialista pode confirmar o agendamento', ); } - // Verificar se está em status SCHEDULING - if (process.status !== 'SCHEDULING') { - throw new BadRequestException( - 'Apenas processos em status SCHEDULING podem ter o agendamento confirmado', - ); - } - - // Verificar se tem appointment - if (!process.appointment) { - throw new NotFoundException( - 'Agendamento não encontrado para este processo', - ); - } - - if ( - process.appointment.status === StatusAgendamento.SCHEDULED || - process.appointment.status === StatusAgendamento.COMPLETED - ) { - throw new BadRequestException('Agendamento já foi confirmado'); - } - - if ( - process.appointment.scheduling_method === - AppointmentSchedulingMethod.EMAIL && - !appointmentDatetime - ) { - throw new BadRequestException( - 'Informe uma data e hora futura para confirmar o agendamento', - ); - } - - const requestedDate = parseDate( - appointmentDatetime ?? - process.appointment.appointment_datetime ?? - undefined, - ); - if (!requestedDate || !isFutureDate(requestedDate)) { - throw new BadRequestException( - 'Informe uma data e hora futura para confirmar o agendamento', - ); - } - // Confirmar appointment em transação (sem alterar status do processo) - const confirmedDate = await this.prismaService.$transaction(async (tx) => { + const confirmation = await this.prismaService.$transaction(async (tx) => { await acquireSpecialistScheduleLock(tx, process.specialist_id); const lockedProcess = await tx.process.findUnique({ - where: { id: processId }, - include: { appointment: true }, + where: { id: processId, removed_at: null }, + include: { + appointment: true, + client: { + select: { id: true, email: true, name: true, surname: true }, + }, + specialist: { + select: { id: true, email: true, name: true, surname: true }, + }, + car: true, + boat: true, + aircraft: true, + }, }); if (!lockedProcess) { throw new NotFoundException('Processo não encontrado'); } - if (lockedProcess.specialist_id !== userId) { + this.assertRepresentedSpecialist(context, lockedProcess.specialist_id); + if (lockedProcess.specialist_id !== representedSpecialistId) { throw new ForbiddenException( 'Apenas o especialista pode confirmar o agendamento', ); @@ -2085,14 +2661,21 @@ export class ProcessesService { 'Agendamento não encontrado para este processo', ); } - if (lockedProcess.appointment.status !== StatusAgendamento.PENDING) { - throw new BadRequestException('Agendamento já foi confirmado'); + if ( + lockedProcess.appointment.specialist_id !== + lockedProcess.specialist_id || + lockedProcess.appointment.client_id !== lockedProcess.client_id || + lockedProcess.appointment.id !== lockedProcess.appointment_id + ) { + throw new BadRequestException( + 'Agendamento não corresponde aos participantes do processo', + ); } - if ( - lockedProcess.appointment.scheduling_method === - AppointmentSchedulingMethod.EMAIL && - !appointmentDatetime + appointmentDatetime !== undefined && + (typeof appointmentDatetime !== 'string' || + !PENDING_APPOINTMENT_DATETIME_PATTERN.test(appointmentDatetime) || + !isISO8601(appointmentDatetime, { strict: true })) ) { throw new BadRequestException( 'Informe uma data e hora futura para confirmar o agendamento', @@ -2104,6 +2687,26 @@ export class ProcessesService { lockedProcess.appointment.appointment_datetime ?? undefined, ); + const appointment = lockedProcess.appointment; + if ( + appointment.status === StatusAgendamento.SCHEDULED && + appointment.confirmed_by_id === userId && + appointment.confirmed_at && + lockedConfirmedDate && + appointment.appointment_datetime?.getTime() === + lockedConfirmedDate.getTime() + ) { + return { + changed: false, + confirmedDate: lockedConfirmedDate, + process: lockedProcess, + }; + } + if (appointment.status !== StatusAgendamento.PENDING) { + throw new BadRequestException( + 'Agendamento já foi confirmado ou cancelado', + ); + } if (!lockedConfirmedDate || !isFutureDate(lockedConfirmedDate)) { throw new BadRequestException( 'Informe uma data e hora futura para confirmar o agendamento', @@ -2117,28 +2720,28 @@ export class ProcessesService { lockedProcess.appointment.id, ); - // Atualizar appointment para SCHEDULED - await tx.appointment.update({ - where: { id: lockedProcess.appointment.id }, - data: { - status: StatusAgendamento.SCHEDULED, - appointment_datetime: lockedConfirmedDate, - confirmed_at: new Date(), - confirmed_by_id: userId, - }, - }); - - // Manter process em SCHEDULING e apenas registrar no histórico/notas + const confirmedAt = new Date(); + const proposal = + appointment.appointment_datetime?.toISOString() ?? + 'sem horário definido'; + const note = `Agendamento confirmado pelo especialista (${confirmedAt.toISOString()}); proposta: ${proposal}; horário confirmado: ${lockedConfirmedDate.toISOString()}`; + // Reivindicar Process antes de Appointment mantém a ordem de cancelamento. const processClaim = await tx.process.updateMany({ where: { id: processId, + removed_at: null, status: ProcessStatus.SCHEDULING, updated_at: lockedProcess.updated_at, + specialist_id: lockedProcess.specialist_id, + client_id: lockedProcess.client_id, + appointment_id: appointment.id, + notes: lockedProcess.notes, }, data: { notes: lockedProcess.notes - ? `${lockedProcess.notes}\n\nAgendamento confirmado pelo especialista (${new Date().toISOString()})` - : `Agendamento confirmado pelo especialista (${new Date().toISOString()})`, + ? `${lockedProcess.notes}\n\n${note}` + : note, + updated_at: confirmedAt, }, }); if (processClaim.count !== 1) { @@ -2147,7 +2750,34 @@ export class ProcessesService { ); } - return lockedConfirmedDate; + await tx.appointment.update({ + where: { id: appointment.id }, + data: { + status: StatusAgendamento.SCHEDULED, + appointment_datetime: lockedConfirmedDate, + confirmed_at: confirmedAt, + confirmed_by_id: userId, + }, + }); + + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'APPOINTMENT_CONFIRM', + resourceType: 'APPOINTMENT', + resourceId: appointment.id, + metadata: { processId, appointmentDatetime: lockedConfirmedDate }, + }, + tx, + ); + } + + return { + changed: true, + confirmedDate: lockedConfirmedDate, + process: lockedProcess, + }; }); this.logger.log( @@ -2155,32 +2785,34 @@ export class ProcessesService { ); // Fire-and-forget email notification (async, non-blocking) - setImmediate(() => { - this.notificationService - .sendAppointmentConfirmedEmail({ - clientEmail: process.client.email, - clientName: - `${process.client.name} ${process.client.surname || ''}`.trim(), - specialistName: - `${process.specialist.name} ${process.specialist.surname || ''}`.trim(), - appointmentDate: confirmedDate, - productDetails: this.getProductDetails(process), - processId, - }) - .catch((err) => { - this.logger.error('Notification failed (non-critical)', { - method: 'confirmAppointment', + if (confirmation.changed) + setImmediate(() => { + const process = confirmation.process; + this.notificationService + .sendAppointmentConfirmedEmail({ + clientEmail: process.client.email, + clientName: + `${process.client.name} ${process.client.surname || ''}`.trim(), + specialistName: + `${process.specialist.name} ${process.specialist.surname || ''}`.trim(), + appointmentDate: confirmation.confirmedDate, + productDetails: this.getProductDetails(process), processId, - error: err.message, + }) + .catch((err) => { + this.logger.error('Notification failed (non-critical)', { + method: 'confirmAppointment', + processId, + error: err.message, + }); }); - }); - }); + }); return { processId, status: 'SCHEDULING', appointment_status: StatusAgendamento.SCHEDULED, - appointment_datetime: confirmedDate, + appointment_datetime: confirmation.confirmedDate, }; } @@ -2196,35 +2828,29 @@ export class ProcessesService { * @throws {ForbiddenException} - Usuário não autorizado * @throws {BadRequestException} - Processo não está em status SCHEDULING */ - async cancelAppointment(processId: string, userId: string): Promise { + async cancelAppointment( + processId: string, + userId: string, + context?: ActorContext, + reason?: string, + ): Promise { this.logger.log( `[cancelAppointment] Cancelando agendamento do processo ${processId}`, ); - // Buscar processo com appointment, client, specialist e produtos - const process = await this.prismaService.process.findUnique({ - where: { id: processId }, - include: { - appointment: true, - client: { - select: { id: true, email: true, name: true, surname: true }, - }, - specialist: { - select: { id: true, email: true, name: true, surname: true }, - }, - car: true, - boat: true, - aircraft: true, - }, + const candidate = await this.prismaService.process.findUnique({ + where: { id: processId, removed_at: null }, + select: { id: true, client_id: true, specialist_id: true }, }); - if (!process) { + if (!candidate) { throw new NotFoundException('Processo não encontrado'); } // Verificar se o usuário é o cliente ou especialista - const isClient = process.client_id === userId; - const isSpecialist = process.specialist_id === userId; + const isClient = candidate.client_id === userId; + const representedSpecialistId = context?.specialistId ?? userId; + const isSpecialist = candidate.specialist_id === representedSpecialistId; if (!isClient && !isSpecialist) { throw new ForbiddenException( @@ -2232,22 +2858,92 @@ export class ProcessesService { ); } - // Verificar se está em status SCHEDULING - if (process.status !== 'SCHEDULING') { - throw new BadRequestException( - 'Apenas processos em status SCHEDULING podem ter o agendamento cancelado', - ); - } + // Serializar com a confirmação e revalidar toda a relação sob lock. + const process = await this.prismaService.$transaction(async (tx) => { + await acquireSpecialistScheduleLock(tx, candidate.specialist_id); + const lockedProcess = await tx.process.findUnique({ + where: { id: processId, removed_at: null }, + include: { + appointment: true, + client: { + select: { id: true, email: true, name: true, surname: true }, + }, + specialist: { + select: { id: true, email: true, name: true, surname: true }, + }, + car: true, + boat: true, + aircraft: true, + }, + }); + if (!lockedProcess) { + throw new NotFoundException('Processo não encontrado'); + } + if ( + lockedProcess.client_id !== userId && + lockedProcess.specialist_id !== representedSpecialistId + ) { + throw new ForbiddenException( + 'Sem permissão para cancelar este agendamento', + ); + } + this.assertRepresentedSpecialist(context, lockedProcess.specialist_id); + if (lockedProcess.status !== ProcessStatus.SCHEDULING) { + throw new BadRequestException( + 'Apenas processos em status SCHEDULING podem ter o agendamento cancelado', + ); + } + if (!lockedProcess.appointment) { + throw new NotFoundException( + 'Agendamento não encontrado para este processo', + ); + } + if ( + lockedProcess.appointment.id !== lockedProcess.appointment_id || + lockedProcess.appointment.client_id !== lockedProcess.client_id || + lockedProcess.appointment.specialist_id !== lockedProcess.specialist_id + ) { + throw new BadRequestException( + 'Agendamento não corresponde aos participantes do processo', + ); + } + if ( + lockedProcess.appointment.status !== StatusAgendamento.PENDING && + lockedProcess.appointment.status !== StatusAgendamento.SCHEDULED + ) { + throw new BadRequestException( + 'Apenas agendamentos pendentes ou agendados podem ser cancelados', + ); + } - // Verificar se tem appointment - if (!process.appointment) { - throw new NotFoundException( - 'Agendamento não encontrado para este processo', - ); - } + const processClaim = await tx.process.updateMany({ + where: { + id: processId, + removed_at: null, + status: ProcessStatus.SCHEDULING, + updated_at: lockedProcess.updated_at, + }, + data: { updated_at: new Date() }, + }); + if (processClaim.count !== 1) { + throw new ConflictException( + 'O processo foi alterado enquanto o agendamento era cancelado', + ); + } + + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'APPOINTMENT_CANCEL', + resourceType: 'APPOINTMENT', + resourceId: lockedProcess.appointment.id, + metadata: { processId, reason: reason ?? null }, + }, + tx, + ); + } - // Deletar appointment e process em transação - await this.prismaService.$transaction(async (tx) => { // Deletar histórico do processo await tx.processStatusHistory.deleteMany({ where: { processId }, @@ -2260,8 +2956,10 @@ export class ProcessesService { // Deletar appointment await tx.appointment.delete({ - where: { id: process.appointment!.id }, + where: { id: lockedProcess.appointment.id }, }); + + return lockedProcess; }); this.logger.log( diff --git a/backend/src/features/product-import-jobs/dto/product-csv-import.dto.ts b/backend/src/features/product-import-jobs/dto/product-csv-import.dto.ts new file mode 100644 index 00000000..59d9dafe --- /dev/null +++ b/backend/src/features/product-import-jobs/dto/product-csv-import.dto.ts @@ -0,0 +1,21 @@ +import { Transform } from 'class-transformer'; +import { IsBoolean, IsIn, IsOptional, IsString, IsUUID } from 'class-validator'; + +export class ProductCsvImportDto { + @IsOptional() + @IsUUID() + specialist_id?: string; + + @IsOptional() + @IsIn(['ADDITIVE', 'SYNCHRONIZE']) + mode: 'ADDITIVE' | 'SYNCHRONIZE' = 'ADDITIVE'; + + @IsOptional() + @Transform(({ value }) => value === true || value === 'true') + @IsBoolean() + confirm_synchronize = false; + + @IsOptional() + @IsString() + synchronize_preview_token?: string; +} diff --git a/backend/src/features/product-import-jobs/product-import-jobs.controller.ts b/backend/src/features/product-import-jobs/product-import-jobs.controller.ts index ce6ea885..7853386c 100644 --- a/backend/src/features/product-import-jobs/product-import-jobs.controller.ts +++ b/backend/src/features/product-import-jobs/product-import-jobs.controller.ts @@ -1,19 +1,32 @@ -import { Controller, Get, Param } from '@nestjs/common'; +import { Controller, Get, Optional, Param, Query } from '@nestjs/common'; import { UserRole } from '@prisma/client'; import { UserEntity } from 'src/auth/entities/user.entity'; import { CurrentUser } from 'src/shared/decorators/current-user.decorator'; import { Roles } from 'src/shared/decorators/roles.decorator'; import { ProductImportJobsService } from './product-import-jobs.service'; +import { ActorContextService } from 'src/shared/actor-context/actor-context.service'; @Controller('product-import-jobs') export class ProductImportJobsController { constructor( private readonly productImportJobsService: ProductImportJobsService, + @Optional() private readonly actorContextService?: ActorContextService, ) {} @Get(':jobId') @Roles(UserRole.ADMIN, UserRole.SPECIALIST) - getJobStatus(@Param('jobId') jobId: string, @CurrentUser() user: UserEntity) { - return this.productImportJobsService.getJobStatus(jobId, user); + async getJobStatus( + @Param('jobId') jobId: string, + @CurrentUser() user: UserEntity, + @Query('target_specialist_id') targetSpecialistId?: string, + ) { + const context = this.actorContextService + ? await this.actorContextService.resolve(user, targetSpecialistId) + : undefined; + return this.productImportJobsService.getJobStatus( + jobId, + user, + context?.specialistId, + ); } } diff --git a/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts b/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts index 75efd7a9..b4eae2d6 100644 --- a/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts +++ b/backend/src/features/product-import-jobs/product-import-jobs.service.spec.ts @@ -2,6 +2,49 @@ import { ProductImportJobsService } from './product-import-jobs.service'; import { Prisma, ProductCurrency, ProductType } from '@prisma/client'; describe('ProductImportJobsService', () => { + beforeEach(() => { + jest + .spyOn(ProductImportJobsService.prototype as any, 'claimJob') + .mockResolvedValue('unit-test-lease'); + jest + .spyOn(ProductImportJobsService.prototype as any, 'releaseJobLease') + .mockResolvedValue(undefined); + jest + .spyOn(ProductImportJobsService.prototype as any, 'pauseIneligibleJob') + .mockResolvedValue(undefined); + jest + .spyOn(ProductImportJobsService.prototype as any, 'checkpointProductUpsert') + .mockImplementation(function (job: any, _item: any, payload: any) { + return (this as any).upsertProductFromRow( + job.product_type, + payload, + job.specialist_id, + ); + }); + jest + .spyOn(ProductImportJobsService.prototype as any, 'finalizeUnsynchronizedJob') + .mockImplementation(function (jobId: string, summary: any) { + return (this as any).refreshJobCounters(jobId, summary); + }); + jest + .spyOn(ProductImportJobsService.prototype as any, 'updateImportItemWithLease') + .mockImplementation(function ( + _jobId: string, + _leaseToken: string, + itemId: string, + data: any, + ) { + return (this as any).prisma.productImportJobItem.update({ + where: { id: itemId }, + data, + }); + }); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + const validCarRow = { marca: 'Ferrari', modelo: 'Roma', @@ -11,6 +54,25 @@ describe('ProductImportJobsService', () => { ano: '2024', }; + it('repete uma transação serializável abortada por P2034', async () => { + const transaction = jest + .fn() + .mockRejectedValueOnce({ code: 'P2034' }) + .mockImplementationOnce(async (callback: any) => callback({ ok: true })); + const service = new ProductImportJobsService( + { $transaction: transaction } as any, + {} as any, + {} as any, + ); + const operation = jest.fn().mockResolvedValue('done'); + + await expect( + (service as any).runSerializableWithRetry(operation), + ).resolves.toBe('done'); + expect(transaction).toHaveBeenCalledTimes(2); + expect(operation).toHaveBeenCalledWith({ ok: true }); + }); + it.each([ ['identificador', '-', 'Identificador do veículo faltando'], ['marca', ' - ', 'Marca do veículo faltando'], @@ -107,6 +169,15 @@ describe('ProductImportJobsService', () => { }, } as any; const service = new ProductImportJobsService(prisma, {} as any, {} as any); + jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({ + mode: 'SYNCHRONIZE', + syncConfirmed: true, + syncPreviewSnapshot: { candidateIds: [], csvDigest: 'csv-digest' }, + specialistIsEligible: true, + }); + jest + .spyOn(service as any, 'assertSynchronizationSnapshotCurrent') + .mockResolvedValue(undefined); const deactivateMissingProducts = jest .spyOn(service as any, 'deactivateMissingProducts') .mockResolvedValue(['stale-product']); @@ -130,6 +201,551 @@ describe('ProductImportJobsService', () => { }); }); + it('reconstrói produtos vistos ao retomar sincronização parcialmente concluída', async () => { + const specialistId = '00000000-0000-4000-8000-000000000001'; + const productA = '11111111-1111-4111-8111-111111111111'; + const productB = '22222222-2222-4222-8222-222222222222'; + const prisma = { + productImportJob: { + findUnique: jest.fn().mockResolvedValue({ + id: 'job-resume', + product_type: ProductType.CAR, + specialist_id: specialistId, + status: 'PROCESSING', + started_at: new Date('2026-10-23T12:00:00.000Z'), + items: [ + { + id: 'item-a', + status: 'COMPLETED', + product_id: productA, + payload: validCarRow, + folder_url: null, + }, + { + id: 'item-b', + status: 'PENDING', + product_id: null, + payload: { + ...validCarRow, + identificador: 'FERRARI-ROMA-2', + }, + folder_url: null, + }, + ], + }), + update: jest.fn().mockResolvedValue({}), + }, + productImportJobItem: { + update: jest.fn().mockResolvedValue({}), + }, + } as any; + const service = new ProductImportJobsService(prisma, {} as any, {} as any); + jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({ + mode: 'SYNCHRONIZE', + syncConfirmed: true, + syncPreviewSnapshot: { candidateIds: [], csvDigest: 'csv-digest' }, + specialistIsEligible: true, + }); + jest + .spyOn(service as any, 'assertSynchronizationSnapshotCurrent') + .mockResolvedValue(undefined); + jest.spyOn(service as any, 'upsertProductFromRow').mockResolvedValue({ + productId: productB, + action: 'UPDATED', + }); + const finalizeSynchronizedJob = jest + .spyOn(service as any, 'finalizeSynchronizedJob') + .mockResolvedValue(undefined); + + await (service as any).processJob('job-resume'); + + expect(finalizeSynchronizedJob).toHaveBeenCalledWith( + 'job-resume', + { + productType: ProductType.CAR, + specialistId, + seenProductIds: new Set([productA, productB]), + snapshot: { candidateIds: [], csvDigest: 'csv-digest' }, + }, + 0, + 'unit-test-lease', + ); + }); + + it('leva o snapshot confirmado para a revalidação transacional antes de desativar', async () => { + const snapshot = { + candidateIds: ['22222222-2222-4222-8222-222222222222'], + csvDigest: 'csv-digest', + }; + const prisma = { + productImportJob: { + findUnique: jest.fn().mockResolvedValue({ + id: 'job-snapshot', + product_type: ProductType.CAR, + specialist_id: '00000000-0000-4000-8000-000000000001', + status: 'PROCESSING', + started_at: new Date(), + items: [ + { + id: 'item-seen', + status: 'COMPLETED', + product_id: '11111111-1111-4111-8111-111111111111', + payload: validCarRow, + folder_url: null, + }, + ], + }), + update: jest.fn().mockResolvedValue({}), + }, + } as any; + const service = new ProductImportJobsService(prisma, {} as any, {} as any); + jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({ + mode: 'SYNCHRONIZE', + syncConfirmed: true, + syncPreviewSnapshot: snapshot, + specialistIsEligible: true, + }); + jest + .spyOn(service as any, 'assertSynchronizationSnapshotCurrent') + .mockResolvedValue(undefined); + const finalizeSynchronizedJob = jest + .spyOn(service as any, 'finalizeSynchronizedJob') + .mockResolvedValue(undefined); + + await (service as any).processJob('job-snapshot'); + + expect(finalizeSynchronizedJob).toHaveBeenCalledWith( + 'job-snapshot', + { + productType: ProductType.CAR, + specialistId: '00000000-0000-4000-8000-000000000001', + seenProductIds: new Set(['11111111-1111-4111-8111-111111111111']), + snapshot, + }, + 0, + 'unit-test-lease', + ); + }); + + it('reprocessa item PROCESSING de forma idempotente após upsert sem checkpoint', async () => { + const existingProductId = '11111111-1111-4111-8111-111111111111'; + const itemUpdate = jest.fn().mockResolvedValue({}); + const prisma = { + productImportJob: { + findUnique: jest.fn().mockResolvedValue({ + id: 'job-interrupted', + product_type: ProductType.CAR, + specialist_id: '00000000-0000-4000-8000-000000000001', + status: 'PROCESSING', + started_at: new Date(), + items: [ + { + id: 'item-processing', + status: 'PROCESSING', + product_id: null, + payload: validCarRow, + folder_url: null, + }, + ], + }), + update: jest.fn().mockResolvedValue({}), + }, + productImportJobItem: { update: itemUpdate }, + } as any; + const service = new ProductImportJobsService(prisma, {} as any, {} as any); + jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({ + mode: 'ADDITIVE', + syncConfirmed: false, + syncPreviewSnapshot: null, + specialistIsEligible: true, + }); + const upsert = jest + .spyOn(service as any, 'upsertProductFromRow') + .mockResolvedValue({ + productId: existingProductId, + action: 'UPDATED', + }); + jest + .spyOn(service as any, 'refreshJobCounters') + .mockResolvedValue(undefined); + + await (service as any).processJob('job-interrupted'); + + expect(upsert).toHaveBeenCalledTimes(1); + expect(itemUpdate).toHaveBeenLastCalledWith({ + where: { id: 'item-processing' }, + data: expect.objectContaining({ + status: 'COMPLETED', + product_id: existingProductId, + action: 'UPDATED', + }), + }); + }); + + it('não inativa produtos ausentes no modo aditivo', async () => { + const prisma = { + productImportJob: { + findUnique: jest.fn().mockResolvedValue({ + id: 'job-additive', + product_type: ProductType.CAR, + specialist_id: '00000000-0000-4000-8000-000000000001', + status: 'PENDING', + started_at: null, + items: [], + }), + update: jest.fn().mockResolvedValue({}), + }, + } as any; + const service = new ProductImportJobsService(prisma, {} as any, {} as any); + jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({ + mode: 'ADDITIVE', + syncConfirmed: false, + specialistIsEligible: true, + }); + const deactivateMissingProducts = jest + .spyOn(service as any, 'deactivateMissingProducts') + .mockResolvedValue(['stale-product']); + const refreshJobCounters = jest + .spyOn(service as any, 'refreshJobCounters') + .mockResolvedValue(undefined); + + await (service as any).processJob('job-additive'); + + expect(deactivateMissingProducts).not.toHaveBeenCalled(); + expect(refreshJobCounters).toHaveBeenCalledWith('job-additive', { + deactivatedIds: [], + reactivatedCount: 0, + }); + }); + + it('mantém o job pendente quando o especialista-alvo foi desativado', async () => { + const prisma = { + productImportJob: { + findUnique: jest.fn().mockResolvedValue({ + id: 'job-inactive', + product_type: ProductType.CAR, + specialist_id: '00000000-0000-4000-8000-000000000001', + status: 'PENDING', + started_at: null, + items: [], + }), + update: jest.fn().mockResolvedValue({}), + }, + } as any; + const service = new ProductImportJobsService(prisma, {} as any, {} as any); + jest.spyOn(service as any, 'getJobExecutionContext').mockResolvedValue({ + mode: 'ADDITIVE', + syncConfirmed: false, + specialistIsEligible: false, + }); + + await (service as any).processJob('job-inactive'); + + expect((service as any).pauseIneligibleJob).toHaveBeenCalledWith( + 'job-inactive', + 'unit-test-lease', + ); + }); + + it('exige confirmação explícita para sincronizar', async () => { + const xlsxImportService = { + parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }), + validateStructure: jest.fn().mockReturnValue({ valid: true }), + } as any; + const service = new ProductImportJobsService( + {} as any, + xlsxImportService, + {} as any, + ); + + await expect( + service.createJobFromCsv( + Buffer.from('csv'), + { id: 'admin-1', role: 'ADMIN' } as any, + ProductType.CAR, + { + mode: 'SYNCHRONIZE', + confirmSynchronize: false, + context: { + actorId: 'admin-1', + actorRole: 'ADMIN', + specialistId: '00000000-0000-4000-8000-000000000001', + specialist: {} as any, + delegated: true, + }, + }, + ), + ).rejects.toThrow('confirmação explícita'); + }); + + it('rejeita identificadores duplicados no mesmo CSV', async () => { + const xlsxImportService = { + parseCsv: jest.fn().mockReturnValue({ + rows: [validCarRow, { ...validCarRow, modelo: 'Duplicado' }], + }), + validateStructure: jest.fn().mockReturnValue({ valid: true }), + } as any; + const service = new ProductImportJobsService( + {} as any, + xlsxImportService, + {} as any, + ); + + await expect( + service.previewCsvImport( + Buffer.from('csv-duplicado'), + ProductType.CAR, + '00000000-0000-4000-8000-000000000001', + 'SYNCHRONIZE', + ), + ).rejects.toThrow('identificadores duplicados'); + }); + + it('exige token da prévia mesmo quando a sincronização foi confirmada', async () => { + const xlsxImportService = { + parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }), + validateStructure: jest.fn().mockReturnValue({ valid: true }), + } as any; + const prisma = { + car: { findMany: jest.fn().mockResolvedValue([]) }, + $transaction: jest.fn(async (callback) => + callback({ + productImportJob: { + create: jest.fn().mockResolvedValue({ + id: 'job-unsafe', + status: 'PENDING', + total_items: 1, + product_type: ProductType.CAR, + }), + }, + $executeRaw: jest.fn(), + }), + ), + } as any; + const service = new ProductImportJobsService( + prisma, + xlsxImportService, + {} as any, + ); + jest.spyOn(service as any, 'scheduleJob').mockImplementation(() => {}); + + await expect( + service.createJobFromCsv( + Buffer.from('csv'), + { id: 'admin-1', role: 'ADMIN' } as any, + ProductType.CAR, + { + mode: 'SYNCHRONIZE', + confirmSynchronize: true, + context: { + actorId: 'admin-1', + actorRole: 'ADMIN', + specialistId: '00000000-0000-4000-8000-000000000001', + specialist: {} as any, + delegated: true, + }, + }, + ), + ).rejects.toMatchObject({ + response: expect.objectContaining({ + code: 'SYNCHRONIZE_PREVIEW_REQUIRED', + }), + }); + }); + + it('calcula o impacto da sincronização antes de criar o job', async () => { + const xlsxImportService = { + parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }), + validateStructure: jest.fn().mockReturnValue({ valid: true }), + } as any; + const prisma = { + car: { + findMany: jest.fn().mockResolvedValue([ + { id: 'keep', identificador: 'FERRARI-ROMA-1' }, + { id: 'stale', identificador: 'FERRARI-OLD-1' }, + ]), + }, + } as any; + const service = new ProductImportJobsService( + prisma, + xlsxImportService, + {} as any, + ); + + const preview = await service.previewCsvImport( + Buffer.from('csv'), + ProductType.CAR, + '00000000-0000-4000-8000-000000000001', + 'SYNCHRONIZE', + ); + + expect(preview).toMatchObject({ + mode: 'SYNCHRONIZE', + targetSpecialistId: '00000000-0000-4000-8000-000000000001', + requiresExplicitConfirmation: true, + impact: { + incomingItems: 1, + activeItemsBefore: 2, + matchingItems: 1, + deactivationCandidates: 1, + }, + }); + expect(preview).toEqual( + expect.objectContaining({ synchronizePreviewToken: expect.any(String) }), + ); + }); + + it('deriva impacto e token da mesma leitura do catálogo', async () => { + const specialistId = '00000000-0000-4000-8000-000000000001'; + const productA = { + id: '11111111-1111-4111-8111-111111111111', + identificador: validCarRow.identificador, + }; + const productC = { + id: '33333333-3333-4333-8333-333333333333', + identificador: 'NEW-C', + }; + const catalogReads = [[productA], [productA, productC], [productA, productC]]; + const findMany = jest + .fn() + .mockImplementation(async () => + catalogReads.shift() ?? [productA, productC], + ); + const xlsxImportService = { + parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }), + validateStructure: jest.fn().mockReturnValue({ valid: true }), + } as any; + const prisma = { + car: { + findMany, + }, + $transaction: jest.fn(async (callback) => + callback({ + car: { findMany }, + productImportJob: { + create: jest.fn().mockResolvedValue({ + id: 'job-unsafe-preview', + status: 'PENDING', + total_items: 1, + product_type: ProductType.CAR, + }), + }, + $executeRaw: jest.fn(), + }), + ), + } as any; + const service = new ProductImportJobsService( + prisma, + xlsxImportService, + {} as any, + ); + jest.spyOn(service as any, 'scheduleJob').mockImplementation(() => {}); + const file = Buffer.from('preview-race-csv'); + + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + + expect(preview.impact.deactivationCandidates).toBe(0); + await expect( + service.createJobFromCsv( + file, + { id: 'admin-1', role: 'ADMIN' } as any, + ProductType.CAR, + { + mode: 'SYNCHRONIZE', + confirmSynchronize: true, + synchronizePreviewToken: preview.synchronizePreviewToken, + context: { + actorId: 'admin-1', + actorRole: 'ADMIN', + specialistId, + specialist: {} as any, + delegated: true, + }, + }, + ), + ).rejects.toMatchObject({ + response: expect.objectContaining({ code: 'SYNCHRONIZE_PREVIEW_STALE' }), + }); + expect(prisma.$transaction).toHaveBeenCalledTimes(1); + }); + + it('rejeita confirmação quando os candidatos mudam antes do POST', async () => { + const specialistId = '00000000-0000-4000-8000-000000000001'; + const activeProducts = [ + { id: '11111111-1111-4111-8111-111111111111', identificador: 'FERRARI-ROMA-1' }, + { id: '22222222-2222-4222-8222-222222222222', identificador: 'STALE-B' }, + ]; + const xlsxImportService = { + parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }), + validateStructure: jest.fn().mockReturnValue({ valid: true }), + } as any; + const findMany = jest.fn().mockImplementation(async () => [...activeProducts]); + const prisma = { + car: { + findMany, + }, + $transaction: jest.fn(async (callback) => + callback({ + car: { findMany }, + productImportJob: { + create: jest.fn().mockResolvedValue({ + id: 'job-stale', + status: 'PENDING', + total_items: 1, + product_type: ProductType.CAR, + }), + }, + $executeRaw: jest.fn(), + }), + ), + } as any; + const service = new ProductImportJobsService( + prisma, + xlsxImportService, + {} as any, + ); + jest.spyOn(service as any, 'scheduleJob').mockImplementation(() => {}); + const file = Buffer.from('csv-stable'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + activeProducts.push({ + id: '33333333-3333-4333-8333-333333333333', + identificador: 'NEW-C', + }); + + await expect( + service.createJobFromCsv( + file, + { id: 'admin-1', role: 'ADMIN' } as any, + ProductType.CAR, + { + mode: 'SYNCHRONIZE', + confirmSynchronize: true, + synchronizePreviewToken: preview.synchronizePreviewToken, + context: { + actorId: 'admin-1', + actorRole: 'ADMIN', + specialistId, + specialist: {} as any, + delegated: true, + }, + }, + ), + ).rejects.toMatchObject({ + response: expect.objectContaining({ code: 'SYNCHRONIZE_PREVIEW_STALE' }), + }); + expect(prisma.$transaction).toHaveBeenCalledTimes(1); + }); + it('relata a linha não importada com erro em linguagem natural', () => { const service = new ProductImportJobsService( {} as any, diff --git a/backend/src/features/product-import-jobs/product-import-jobs.service.ts b/backend/src/features/product-import-jobs/product-import-jobs.service.ts index 9559e357..9c78f0f8 100644 --- a/backend/src/features/product-import-jobs/product-import-jobs.service.ts +++ b/backend/src/features/product-import-jobs/product-import-jobs.service.ts @@ -1,11 +1,13 @@ import { BadRequestException, + ConflictException, ForbiddenException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit, + Optional, } from '@nestjs/common'; import { ProductImportItemStatus, @@ -38,16 +40,93 @@ import { CreateBoatDto } from '../boats/dto/create-boat.dto'; import { CreateAircraftDto } from '../aircrafts/dto/create-aircraft.dto'; import { DriveImportService } from '../drive-import/drive-import.service'; import { - acquireProductMonetaryLock, updateProductWithMonetaryLock, } from '../products/product-monetary-lock'; +import { ActorContext } from 'src/shared/actor-context/actor-context.service'; +import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service'; +import { + createHash, + createHmac, + randomUUID, + timingSafeEqual, +} from 'node:crypto'; + +export type ProductImportMode = 'ADDITIVE' | 'SYNCHRONIZE'; + +export type ProductImportOptions = { + context?: ActorContext; + mode?: ProductImportMode | string; + confirmSynchronize?: boolean | string; + synchronizePreviewToken?: string; +}; + +type SynchronizePreviewClaims = { + version: 2; + csvDigest: string; + specialistId: string; + productType: ProductType; + mode: 'SYNCHRONIZE'; + candidateDigest: string; + catalogDigest: string; + expiresAt: number; +}; + +type CatalogProductSnapshot = { + id: string; + identificador: string; + isActive: boolean; + updatedAt: string; + rowVersion: string; +}; + +type SynchronizePreviewSnapshot = { + candidateIds: string[]; + csvDigest: string; + catalogDigest: string; + catalogProducts: CatalogProductSnapshot[]; +}; + +type ImportImpact = { + incomingItems: number; + activeItemsBefore: number; + matchingItems: number; + newOrReactivatedItems: number; + deactivationCandidates: number; +}; + +type SynchronizationCatalogSnapshot = { + candidateIds: string[]; + catalogDigest: string; + catalogProducts: CatalogProductSnapshot[]; + impact: ImportImpact; +}; type UpsertResult = { productId: string; action: 'CREATED' | 'UPDATED'; reactivated?: boolean; + updatedAt?: string; +}; + +type ProductImportEffect = { + productId: string; + action: 'CREATED' | 'UPDATED'; + rowVersion: string; + updatedAt?: string; + reactivated?: boolean; +}; + +type ImportItemPayload = ImportParsedRow & { + __productImportEffect?: ProductImportEffect; }; +class ProductImportJobLeaseLostError extends Error { + constructor() { + super('Lease do job de importação perdido para outro worker.'); + this.name = 'ProductImportJobLeaseLostError'; + } +} + const REQUIRED_PRODUCT_FIELDS = [ { key: 'identificador', label: 'Identificador do veículo' }, { key: 'marca', label: 'Marca do veículo' }, @@ -61,12 +140,15 @@ const REQUIRED_PRODUCT_FIELDS = [ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(ProductImportJobsService.name); private readonly runningJobs = new Set(); + private readonly lostJobLeases = new Set(); private recoveryTimer?: NodeJS.Timeout; constructor( private readonly prisma: PrismaService, private readonly xlsxImportService: XlsxImportService, private readonly driveImportService: DriveImportService, + @Optional() + private readonly delegatedAudit?: DelegatedActionAuditService, ) {} private isMissingImportJobsTableError(error: unknown): boolean { @@ -77,6 +159,33 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { ); } + private isSerializationFailure(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + 'code' in error && + error.code === 'P2034' + ); + } + + private async runSerializableWithRetry( + operation: (tx: Prisma.TransactionClient) => Promise, + maxAttempts = 3, + ): Promise { + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + try { + return await this.prisma.$transaction(operation, { + isolationLevel: Prisma.TransactionIsolationLevel.Serializable, + }); + } catch (error) { + if (!this.isSerializationFailure(error) || attempt === maxAttempts) { + throw error; + } + } + } + throw new Error('Unreachable serializable transaction retry state'); + } + onModuleInit() { this.recoverPendingJobs().catch((error) => { this.logger.error('Falha ao recuperar jobs pendentes', error); @@ -99,7 +208,30 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { fileBuffer: Buffer, user: UserEntity, productType: ProductType, + options: ProductImportOptions = {}, ) { + const mode = `${options.mode ?? 'ADDITIVE'}`.toUpperCase(); + if (mode !== 'ADDITIVE' && mode !== 'SYNCHRONIZE') { + throw new BadRequestException( + 'Modo de importação inválido. Use ADDITIVE ou SYNCHRONIZE.', + ); + } + const syncConfirmed = + options.confirmSynchronize === true || + `${options.confirmSynchronize}`.toLowerCase() === 'true'; + if (mode === 'SYNCHRONIZE' && !syncConfirmed) { + throw new BadRequestException( + 'A sincronização exige confirmação explícita do alvo, tipo e impacto.', + ); + } + if (mode === 'SYNCHRONIZE' && !options.synchronizePreviewToken) { + throw new BadRequestException({ + code: 'SYNCHRONIZE_PREVIEW_REQUIRED', + message: + 'A sincronização exige uma prévia válida. Gere uma nova prévia e confirme novamente.', + }); + } + const { rows } = this.xlsxImportService.parseCsv(fileBuffer); const structureValidation = this.xlsxImportService.validateStructure( @@ -117,31 +249,87 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { } const normalizedRows = rows.map((row) => this.normalizeProductRow(row)); - - let createdJob; + this.validateUniqueIdentifiers(normalizedRows); + const specialistId = options.context?.specialistId ?? user.id; + let creationResult; try { - createdJob = await this.prisma.productImportJob.create({ - data: { - product_type: productType, - specialist_id: user.id, - status: ProductImportJobStatus.PENDING, - total_items: normalizedRows.length, - items: { - createMany: { - data: normalizedRows.map((row, index) => ({ - row_number: index + 2, - payload: row, - folder_url: row.folder_url?.trim() || null, - })), + creationResult = await this.runSerializableWithRetry(async (tx) => { + if (mode === 'SYNCHRONIZE') { + await this.lockProductCatalogForSnapshot(tx, productType); + } + const validatedSynchronization = + mode === 'SYNCHRONIZE' + ? await this.validateSynchronizePreviewToken( + options.synchronizePreviewToken!, + fileBuffer, + productType, + specialistId, + normalizedRows, + tx, + ) + : null; + const synchronizeSnapshot: SynchronizePreviewSnapshot | null = + validatedSynchronization + ? { + candidateIds: validatedSynchronization.candidateIds, + csvDigest: validatedSynchronization.csvDigest, + catalogDigest: validatedSynchronization.catalogDigest, + catalogProducts: validatedSynchronization.catalogProducts, + } + : null; + const impact = + validatedSynchronization?.impact ?? + (await this.estimateImportImpact( + productType, + specialistId, + normalizedRows, + mode, + tx, + )); + const job = await tx.productImportJob.create({ + data: { + product_type: productType, + specialist_id: specialistId, + status: ProductImportJobStatus.PENDING, + total_items: normalizedRows.length, + items: { + createMany: { + data: normalizedRows.map((row, index) => ({ + row_number: index + 2, + payload: row, + folder_url: row.folder_url?.trim() || null, + })), + }, }, }, - }, - select: { - id: true, - status: true, - total_items: true, - product_type: true, - }, + select: { + id: true, + status: true, + total_items: true, + product_type: true, + }, + }); + await tx.$executeRaw` + UPDATE "ProductImportJob" + SET "mode" = ${mode}, + "sync_confirmed" = ${syncConfirmed}, + "created_by_id" = ${user.id}::uuid, + "sync_preview_snapshot" = ${synchronizeSnapshot ? JSON.stringify(synchronizeSnapshot) : null}::jsonb + WHERE "id" = ${job.id}::uuid + `; + if (options.context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context: options.context, + action: 'PRODUCT_IMPORT_CREATE', + resourceType: productType, + resourceId: job.id, + metadata: { mode, impact }, + }, + tx, + ); + } + return { job, impact }; }); } catch (error) { if (this.isMissingImportJobsTableError(error)) { @@ -152,6 +340,8 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { throw error; } + const { job: createdJob, impact } = creationResult; + this.scheduleJob(createdJob.id); return { @@ -159,12 +349,241 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { status: createdJob.status, productType: createdJob.product_type, totalItems: createdJob.total_items, + targetSpecialistId: specialistId, + mode, + synchronizeConfirmed: syncConfirmed, + impact, pollIntervalMs: 2000, message: 'Importação recebida e iniciada em segundo plano.', }; } - async getJobStatus(jobId: string, user: UserEntity) { + async previewCsvImport( + fileBuffer: Buffer, + productType: ProductType, + specialistId: string, + requestedMode: ProductImportMode | string = 'ADDITIVE', + ) { + const mode = `${requestedMode}`.toUpperCase(); + if (mode !== 'ADDITIVE' && mode !== 'SYNCHRONIZE') { + throw new BadRequestException( + 'Modo de importação inválido. Use ADDITIVE ou SYNCHRONIZE.', + ); + } + const { rows } = this.xlsxImportService.parseCsv(fileBuffer); + const structureValidation = this.xlsxImportService.validateStructure( + rows, + this.getColumnsForType(productType), + ); + if (!structureValidation.valid) { + throw new BadRequestException({ + message: 'Estrutura do CSV inválida', + errors: structureValidation.errors, + missingRequired: structureValidation.missingRequired, + unknownColumns: structureValidation.unknownColumns, + }); + } + const normalizedRows = rows.map((row) => this.normalizeProductRow(row)); + this.validateUniqueIdentifiers(normalizedRows); + const catalogSnapshot = await this.getSynchronizationCatalogSnapshot( + productType, + specialistId, + normalizedRows, + ); + const impact = + mode === 'SYNCHRONIZE' + ? catalogSnapshot.impact + : this.deriveImportImpact( + catalogSnapshot.impact.activeItemsBefore, + catalogSnapshot.impact.matchingItems, + normalizedRows, + 0, + ); + const synchronizePreviewToken = + mode === 'SYNCHRONIZE' + ? this.createSynchronizePreviewToken( + fileBuffer, + productType, + specialistId, + catalogSnapshot, + ) + : undefined; + return { + productType, + targetSpecialistId: specialistId, + mode, + requiresExplicitConfirmation: mode === 'SYNCHRONIZE', + impact, + synchronizePreviewToken, + }; + } + + private createSynchronizePreviewToken( + fileBuffer: Buffer, + productType: ProductType, + specialistId: string, + snapshot: SynchronizationCatalogSnapshot, + ): string { + const claims: SynchronizePreviewClaims = { + version: 2, + csvDigest: this.sha256(fileBuffer), + specialistId, + productType, + mode: 'SYNCHRONIZE', + candidateDigest: this.sha256(snapshot.candidateIds.join(',')), + catalogDigest: snapshot.catalogDigest, + expiresAt: Date.now() + 15 * 60 * 1000, + }; + const payload = Buffer.from(JSON.stringify(claims)).toString('base64url'); + const signature = createHmac('sha256', this.getPreviewSecret()) + .update(payload) + .digest('base64url'); + return `${payload}.${signature}`; + } + + private async validateSynchronizePreviewToken( + token: string, + fileBuffer: Buffer, + productType: ProductType, + specialistId: string, + rows: ImportParsedRow[], + client: PrismaService | Prisma.TransactionClient = this.prisma, + ): Promise<{ + candidateIds: string[]; + csvDigest: string; + catalogDigest: string; + catalogProducts: CatalogProductSnapshot[]; + impact: ImportImpact; + }> { + try { + const [payload, providedSignature, extra] = token.split('.'); + if (!payload || !providedSignature || extra) { + throw new Error('token malformado'); + } + const expectedSignature = createHmac('sha256', this.getPreviewSecret()) + .update(payload) + .digest(); + const providedSignatureBuffer = Buffer.from( + providedSignature, + 'base64url', + ); + if ( + providedSignatureBuffer.length !== expectedSignature.length || + !timingSafeEqual(providedSignatureBuffer, expectedSignature) + ) { + throw new Error('assinatura inválida'); + } + + const claims = JSON.parse( + Buffer.from(payload, 'base64url').toString('utf8'), + ) as SynchronizePreviewClaims; + const catalogSnapshot = await this.getSynchronizationCatalogSnapshot( + productType, + specialistId, + rows, + client, + ); + const { candidateIds, catalogDigest, catalogProducts, impact } = + catalogSnapshot; + const csvDigest = this.sha256(fileBuffer); + const scopeMatches = + claims.version === 2 && + claims.mode === 'SYNCHRONIZE' && + claims.productType === productType && + claims.specialistId === specialistId && + claims.csvDigest === csvDigest && + claims.candidateDigest === this.sha256(candidateIds.join(',')) && + claims.catalogDigest === catalogDigest && + claims.expiresAt >= Date.now(); + if (!scopeMatches) { + throw new Error('escopo ou snapshot divergente'); + } + return { + candidateIds, + csvDigest, + catalogDigest, + catalogProducts, + impact, + }; + } catch { + throw new ConflictException({ + code: 'SYNCHRONIZE_PREVIEW_STALE', + message: + 'A prévia de sincronização expirou ou o catálogo/CSV mudou. Gere uma nova prévia antes de confirmar.', + }); + } + } + + private async getSynchronizationCatalogSnapshot( + productType: ProductType, + specialistId: string, + rows: ImportParsedRow[], + client: PrismaService | Prisma.TransactionClient = this.prisma, + ): Promise { + const incomingIdentifiers = new Set( + rows.map((row) => row.identificador?.trim()).filter(Boolean), + ); + const catalogProducts = await this.getCatalogProductsByType( + productType, + specialistId, + client, + ); + const activeProducts = catalogProducts.filter((product) => product.isActive); + const matchingItems = activeProducts.filter((product) => + incomingIdentifiers.has(product.identificador), + ).length; + const candidateIds = activeProducts + .filter((product) => !incomingIdentifiers.has(product.identificador)) + .map((product) => product.id) + .sort(); + return { + candidateIds, + catalogDigest: this.catalogDigest(catalogProducts), + catalogProducts, + impact: this.deriveImportImpact( + activeProducts.length, + matchingItems, + rows, + candidateIds.length, + ), + }; + } + + private sha256(value: Buffer | string): string { + return createHash('sha256').update(value).digest('hex'); + } + + private catalogDigest(products: CatalogProductSnapshot[]): string { + const canonical = [...products].sort((left, right) => + left.id.localeCompare(right.id), + ).map((product) => [ + product.id, + product.identificador, + product.isActive, + product.updatedAt, + product.rowVersion, + ]); + return this.sha256(JSON.stringify(canonical)); + } + + private getPreviewSecret(): string { + const secret = + process.env.PRODUCT_IMPORT_PREVIEW_SECRET ?? + process.env.JWT_SECRET_ACCESS; + if (secret) return secret; + if (process.env.NODE_ENV === 'test') { + return 'product-import-preview-test-secret'; + } + throw new Error( + 'PRODUCT_IMPORT_PREVIEW_SECRET ou JWT_SECRET_ACCESS deve estar configurado.', + ); + } + + async getJobStatus( + jobId: string, + user: UserEntity, + representedSpecialistId?: string, + ) { let job; try { job = await this.prisma.productImportJob.findUnique({ @@ -202,6 +621,15 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { 'Sem permissão para visualizar este job de importação', ); } + if ( + user.role === UserRole.ADMIN && + representedSpecialistId && + job.specialist_id !== representedSpecialistId + ) { + throw new ForbiddenException( + 'O job não pertence ao especialista representado.', + ); + } const response = this.buildImportResponse(job.items, { deactivatedIds: Array.isArray(job.deactivated_product_ids) @@ -209,6 +637,12 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { : [], reactivatedCount: job.reactivated_items, }); + if ( + job.status === ProductImportJobStatus.COMPLETED_WITH_ERRORS && + job.error_message + ) { + response.message = job.error_message; + } return { jobId: job.id, @@ -282,6 +716,165 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { } private async processJob(jobId: string) { + const leaseToken = await this.claimJob(jobId); + if (!leaseToken) return; + const leaseKey = this.jobLeaseKey(jobId, leaseToken); + const heartbeat = setInterval(() => { + this.renewJobLease(jobId, leaseToken) + .then((renewed) => { + if (!renewed) this.lostJobLeases.add(leaseKey); + }) + .catch((error) => { + // Falha de transporte deixa a posse desconhecida; o próximo fence + // consulta o PostgreSQL. Somente UPDATE 0 prova perda definitiva. + this.logger.error(`Falha ao renovar lease do job ${jobId}`, error); + }); + }, 15000); + heartbeat.unref?.(); + try { + await this.processClaimedJob(jobId, leaseToken); + } finally { + clearInterval(heartbeat); + await this.releaseJobLease(jobId, leaseToken); + this.lostJobLeases.delete(leaseKey); + } + } + + private jobLeaseKey(jobId: string, leaseToken: string): string { + return `${jobId}:${leaseToken}`; + } + + private throwIfJobLeaseLost(jobId: string, leaseToken: string): void { + if (this.lostJobLeases.has(this.jobLeaseKey(jobId, leaseToken))) { + throw new ProductImportJobLeaseLostError(); + } + } + + private async claimJob(jobId: string): Promise { + const leaseToken = randomUUID(); + const claimed = await this.prisma.$queryRaw>` + UPDATE "ProductImportJob" + SET "status" = ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus", + "started_at" = COALESCE("started_at", NOW()), + "error_message" = NULL, + "processing_lease_token" = ${leaseToken}::uuid, + "processing_lease_expires_at" = NOW() + INTERVAL '5 minutes', + "updated_at" = NOW() + WHERE "id" = ${jobId}::uuid + AND "status" IN ( + ${ProductImportJobStatus.PENDING}::"ProductImportJobStatus", + ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus" + ) + AND ( + "status" = ${ProductImportJobStatus.PENDING}::"ProductImportJobStatus" + OR "processing_lease_token" IS NULL + OR "processing_lease_expires_at" <= NOW() + ) + RETURNING "id" + `; + return claimed.length === 1 ? leaseToken : null; + } + + private async renewJobLease( + jobId: string, + leaseToken: string, + ): Promise { + const updated = await this.prisma.$executeRaw` + UPDATE "ProductImportJob" + SET "processing_lease_expires_at" = GREATEST( + "processing_lease_expires_at", + NOW() + INTERVAL '5 minutes' + ), + "updated_at" = NOW() + WHERE "id" = ${jobId}::uuid + AND "processing_lease_token" = ${leaseToken}::uuid + AND "status" = ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus" + AND "processing_lease_expires_at" > NOW() + `; + return updated === 1; + } + + private async extendJobLeaseForExternalEffect( + jobId: string, + leaseToken: string, + ): Promise { + this.throwIfJobLeaseLost(jobId, leaseToken); + const updated = await this.prisma.$executeRaw` + UPDATE "ProductImportJob" + SET "processing_lease_expires_at" = GREATEST( + "processing_lease_expires_at", + NOW() + INTERVAL '30 minutes' + ), + "updated_at" = NOW() + WHERE "id" = ${jobId}::uuid + AND "processing_lease_token" = ${leaseToken}::uuid + AND "status" = ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus" + AND "processing_lease_expires_at" > NOW() + `; + if (updated !== 1) { + this.lostJobLeases.add(this.jobLeaseKey(jobId, leaseToken)); + throw new ProductImportJobLeaseLostError(); + } + } + + private async assertJobLeaseOwned( + tx: Prisma.TransactionClient, + jobId: string, + leaseToken: string, + ): Promise { + this.throwIfJobLeaseLost(jobId, leaseToken); + const owned = await tx.$queryRaw>` + SELECT "id" + FROM "ProductImportJob" + WHERE "id" = ${jobId}::uuid + AND "processing_lease_token" = ${leaseToken}::uuid + AND "status" = ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus" + AND "processing_lease_expires_at" > NOW() + FOR UPDATE + `; + if (owned.length !== 1) { + this.lostJobLeases.add(this.jobLeaseKey(jobId, leaseToken)); + throw new ProductImportJobLeaseLostError(); + } + } + + private isJobLeaseLost(error: unknown): boolean { + return error instanceof ProductImportJobLeaseLostError; + } + + private async releaseJobLease( + jobId: string, + leaseToken: string, + ): Promise { + await this.prisma.$executeRaw` + UPDATE "ProductImportJob" + SET "processing_lease_token" = NULL, + "processing_lease_expires_at" = NULL, + "updated_at" = NOW() + WHERE "id" = ${jobId}::uuid + AND "processing_lease_token" = ${leaseToken}::uuid + AND "processing_lease_expires_at" > NOW() + `; + } + + private async pauseIneligibleJob( + jobId: string, + leaseToken: string, + ): Promise { + await this.prisma.$executeRaw` + UPDATE "ProductImportJob" + SET "status" = ${ProductImportJobStatus.PENDING}::"ProductImportJobStatus", + "error_message" = 'Job pausado: especialista-alvo inativo ou incompatível com o tipo do produto.', + "processing_lease_token" = NULL, + "processing_lease_expires_at" = NULL, + "updated_at" = NOW() + WHERE "id" = ${jobId}::uuid + AND "processing_lease_token" = ${leaseToken}::uuid + AND "processing_lease_expires_at" > NOW() + `; + } + + private async processClaimedJob(jobId: string, leaseToken: string) { const job = await this.prisma.productImportJob.findUnique({ where: { id: jobId }, include: { @@ -303,23 +896,63 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { return; } - await this.prisma.productImportJob.update({ - where: { id: jobId }, - data: { - status: ProductImportJobStatus.PROCESSING, - started_at: job.started_at ?? new Date(), - error_message: null, - }, - }); + const executionContext = await this.getJobExecutionContext(job); + if (!executionContext.specialistIsEligible) { + await this.pauseIneligibleJob(jobId, leaseToken); + return; + } + if ( + executionContext.mode === 'SYNCHRONIZE' && + executionContext.syncConfirmed + ) { + try { + await this.assertSynchronizationSnapshotCurrent( + job, + executionContext.syncPreviewSnapshot, + ); + } catch (error) { + if (await this.jobHasPersistedEffects(job)) { + await this.markSynchronizationPartial(jobId, 0, leaseToken); + } else { + await this.markJobFailedUnlessTerminal( + jobId, + error?.message || 'Prévia de sincronização desatualizada', + leaseToken, + ); + } + return; + } + } + + let reactivatedCount = job.items.filter( + (item) => + (item.status === ProductImportItemStatus.COMPLETED || + item.status === ProductImportItemStatus.COMPLETED_WITH_WARNINGS) && + Boolean( + (item.payload as unknown as ImportItemPayload).__productImportEffect + ?.reactivated, + ), + ).length; try { - const seenProductIds = new Set(); - let reactivatedCount = 0; + const seenProductIds = new Set( + job.items + .filter( + (item) => + (item.status === ProductImportItemStatus.COMPLETED || + item.status === + ProductImportItemStatus.COMPLETED_WITH_WARNINGS || + item.status === ProductImportItemStatus.PROCESSING) && + item.product_id, + ) + .map((item) => item.product_id as string), + ); let hasFailedItems = job.items.some( (item) => item.status === ProductImportItemStatus.FAILED, ); for (const item of job.items) { + this.throwIfJobLeaseLost(jobId, leaseToken); if ( item.status !== ProductImportItemStatus.PENDING && item.status !== ProductImportItemStatus.PROCESSING @@ -327,21 +960,21 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { continue; } - await this.prisma.productImportJobItem.update({ - where: { id: item.id }, - data: { - status: ProductImportItemStatus.PROCESSING, - attempts: { increment: 1 }, - }, - }); - try { - const row = item.payload as unknown as ImportParsedRow; - const upsertResult = await this.upsertProductFromRow( - job.product_type, - row, - job.specialist_id, - ); + const payload = item.payload as unknown as ImportItemPayload; + const checkpointedEffect = payload.__productImportEffect; + const upsertResult = + item.status === ProductImportItemStatus.PROCESSING && + checkpointedEffect && + item.product_id === checkpointedEffect.productId && + item.action === checkpointedEffect.action + ? checkpointedEffect + : await this.checkpointProductUpsert( + job, + item, + payload, + leaseToken, + ); seenProductIds.add(upsertResult.productId); if (upsertResult.reactivated) { reactivatedCount += 1; @@ -352,11 +985,18 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { if (folderUrl) { try { + await this.extendJobLeaseForExternalEffect(jobId, leaseToken); const folderImportResult = await this.driveImportService.importImagesForProductFromFolder({ folder_url: folderUrl, product_type: job.product_type, product_id: upsertResult.productId, + assert_active: () => + this.extendJobLeaseForExternalEffect(jobId, leaseToken), + import_job_fence: { + job_id: jobId, + lease_token: leaseToken, + }, }); if ( @@ -366,71 +1006,534 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { warnings.push(...folderImportResult.warnings); } } catch (driveError: any) { + if (this.isJobLeaseLost(driveError)) throw driveError; warnings.push( `Aviso: falha ao importar imagens da pasta — ${driveError?.message || 'erro desconhecido'}`, ); } } - await this.prisma.productImportJobItem.update({ - where: { id: item.id }, - data: { - status: - warnings.length > 0 - ? ProductImportItemStatus.COMPLETED_WITH_WARNINGS - : ProductImportItemStatus.COMPLETED, - product_id: upsertResult.productId, - action: upsertResult.action, - warnings: warnings.length > 0 ? warnings : undefined, - error_message: null, - processed_at: new Date(), - }, + await this.updateImportItemWithLease(jobId, leaseToken, item.id, { + status: + warnings.length > 0 + ? ProductImportItemStatus.COMPLETED_WITH_WARNINGS + : ProductImportItemStatus.COMPLETED, + product_id: upsertResult.productId, + action: upsertResult.action, + warnings: warnings.length > 0 ? warnings : undefined, + error_message: null, + processed_at: new Date(), }); } catch (error) { + if (this.isJobLeaseLost(error)) throw error; hasFailedItems = true; - await this.prisma.productImportJobItem.update({ - where: { id: item.id }, - data: { - status: ProductImportItemStatus.FAILED, - error_message: - error?.message || 'Erro desconhecido no processamento da linha', - processed_at: new Date(), - }, + await this.updateImportItemWithLease(jobId, leaseToken, item.id, { + status: ProductImportItemStatus.FAILED, + attempts: { increment: 1 }, + error_message: + error?.message || 'Erro desconhecido no processamento da linha', + processed_at: new Date(), }); } } - const deactivatedIds = hasFailedItems - ? [] - : await this.deactivateMissingProducts( - job.product_type, - job.specialist_id, + const shouldSynchronize = + executionContext.mode === 'SYNCHRONIZE' && + executionContext.syncConfirmed && + !hasFailedItems; + if (shouldSynchronize) { + await this.finalizeSynchronizedJob( + jobId, + { + productType: job.product_type, + specialistId: job.specialist_id, seenProductIds, - job.id, - ); + snapshot: executionContext.syncPreviewSnapshot, + }, + reactivatedCount, + leaseToken, + ); + } else { + await this.finalizeUnsynchronizedJob( + jobId, + { deactivatedIds: [], reactivatedCount }, + leaseToken, + ); + } + } catch (error) { + if (this.isJobLeaseLost(error)) return; + if ( + executionContext.mode === 'SYNCHRONIZE' && + (this.isSynchronizationPreviewStale(error) || + this.isSerializationFailure(error)) + ) { + await this.markSynchronizationPartial( + jobId, + reactivatedCount, + leaseToken, + ); + return; + } + await this.markJobFailedUnlessTerminal( + jobId, + error?.message || 'Erro ao processar job de importação', + leaseToken, + ); + } + } - await this.refreshJobCounters(jobId, { - deactivatedIds, - reactivatedCount, + private async checkpointProductUpsert( + job: { id: string; product_type: ProductType; specialist_id: string }, + item: { id: string }, + payload: ImportItemPayload, + leaseToken: string, + ): Promise { + return this.prisma.$transaction(async (tx) => { + await this.assertJobLeaseOwned(tx, job.id, leaseToken); + await tx.productImportJobItem.update({ + where: { id: item.id }, + data: { + status: ProductImportItemStatus.PROCESSING, + attempts: { increment: 1 }, + }, }); - } catch (error) { - await this.prisma.productImportJob.update({ + const result = await this.upsertProductFromRow( + job.product_type, + payload, + job.specialist_id, + tx, + ); + const version = await this.getProductVersion( + job.product_type, + result.productId, + tx, + ); + const effect: ProductImportEffect = { + productId: result.productId, + action: result.action, + rowVersion: version.rowVersion, + updatedAt: version.updatedAt, + ...(result.reactivated !== undefined + ? { reactivated: result.reactivated } + : {}), + }; + await tx.productImportJobItem.update({ + where: { id: item.id }, + data: { + status: ProductImportItemStatus.PROCESSING, + product_id: effect.productId, + action: effect.action, + payload: { + ...payload, + __productImportEffect: effect, + }, + error_message: null, + }, + }); + return effect; + }); + } + + private async updateImportItemWithLease( + jobId: string, + leaseToken: string, + itemId: string, + data: Prisma.ProductImportJobItemUpdateInput, + ): Promise { + await this.prisma.$transaction(async (tx) => { + await this.assertJobLeaseOwned(tx, jobId, leaseToken); + await tx.productImportJobItem.update({ + where: { id: itemId }, + data, + }); + }); + } + + private async getProductVersion( + productType: ProductType, + productId: string, + client: Prisma.TransactionClient, + ): Promise<{ rowVersion: string; updatedAt: string }> { + type VersionRow = { rowVersion: string; updatedAt: Date }; + const rows = + productType === ProductType.CAR + ? await client.$queryRaw` + SELECT xmin::text AS "rowVersion", "updated_at" AS "updatedAt" + FROM "Car" WHERE "id" = ${productId}::uuid + ` + : productType === ProductType.BOAT + ? await client.$queryRaw` + SELECT xmin::text AS "rowVersion", "updated_at" AS "updatedAt" + FROM "Boat" WHERE "id" = ${productId}::uuid + ` + : await client.$queryRaw` + SELECT xmin::text AS "rowVersion", "updated_at" AS "updatedAt" + FROM "Aircraft" WHERE "id" = ${productId}::uuid + `; + if (rows.length !== 1) { + throw new NotFoundException('Produto importado não encontrado.'); + } + return { + rowVersion: rows[0].rowVersion, + updatedAt: rows[0].updatedAt.toISOString(), + }; + } + + private async markJobFailedUnlessTerminal( + jobId: string, + message: string, + leaseToken: string, + ): Promise { + await this.prisma.$executeRaw` + UPDATE "ProductImportJob" + SET "status" = ${ProductImportJobStatus.FAILED}::"ProductImportJobStatus", + "error_message" = ${message}, + "finished_at" = NOW(), + "updated_at" = NOW() + WHERE "id" = ${jobId}::uuid + AND "status" = ${ProductImportJobStatus.PROCESSING}::"ProductImportJobStatus" + AND "processing_lease_token" = ${leaseToken}::uuid + AND "processing_lease_expires_at" > NOW() + `; + } + + private async jobHasPersistedEffects(job: { + id: string; + product_type: ProductType; + specialist_id: string; + items: Array<{ + status: ProductImportItemStatus; + product_id: string | null; + payload: unknown; + }>; + }): Promise { + if ( + job.items.some( + (item) => + item.status === ProductImportItemStatus.COMPLETED || + item.status === ProductImportItemStatus.COMPLETED_WITH_WARNINGS || + (item.status === ProductImportItemStatus.PROCESSING && + Boolean(item.product_id) && + Boolean( + (item.payload as unknown as ImportItemPayload) + .__productImportEffect, + )), + ) + ) { + return true; + } + const deactivatedIds = await this.getProductsDeactivatedByJob( + job.product_type, + job.specialist_id, + job.id, + this.prisma, + ); + return deactivatedIds.length > 0; + } + + private isSynchronizationPreviewStale(error: unknown): boolean { + if (!(error instanceof ConflictException)) return false; + const response = error.getResponse(); + return ( + typeof response === 'object' && + response !== null && + 'code' in response && + response.code === 'SYNCHRONIZE_PREVIEW_STALE' + ); + } + + private async markSynchronizationPartial( + jobId: string, + reactivatedCount: number, + leaseToken: string, + ): Promise { + await this.prisma.$transaction(async (tx) => { + await this.assertJobLeaseOwned(tx, jobId, leaseToken); + const job = await tx.productImportJob.findUnique({ where: { id: jobId }, + select: { + status: true, + product_type: true, + specialist_id: true, + reactivated_items: true, + }, + }); + if ( + !job || + job.status === ProductImportJobStatus.COMPLETED || + job.status === ProductImportJobStatus.COMPLETED_WITH_ERRORS || + job.status === ProductImportJobStatus.FAILED + ) { + return; + } + await tx.productImportJobItem.updateMany({ + where: { + job_id: jobId, + status: ProductImportItemStatus.PROCESSING, + product_id: { not: null }, + }, data: { - status: ProductImportJobStatus.FAILED, + status: ProductImportItemStatus.COMPLETED_WITH_WARNINGS, + warnings: [ + 'O catálogo mudou após o checkpoint; confira a importação de imagens antes de gerar uma nova prévia.', + ], + processed_at: new Date(), + }, + }); + const items = await tx.productImportJobItem.findMany({ + where: { job_id: jobId }, + select: { + status: true, + action: true, + product_id: true, + }, + }); + const completed = items.filter( + (item) => + item.status === ProductImportItemStatus.COMPLETED || + item.status === ProductImportItemStatus.COMPLETED_WITH_WARNINGS || + (item.status === ProductImportItemStatus.PROCESSING && + Boolean(item.product_id)), + ); + const changedProductIds = completed + .map((item) => item.product_id) + .filter((id): id is string => Boolean(id)); + const insertedCount = completed.filter( + (item) => item.action === 'CREATED', + ).length; + const updatedCount = completed.filter( + (item) => item.action === 'UPDATED', + ).length; + const warningItems = completed.filter( + (item) => + item.status === ProductImportItemStatus.COMPLETED_WITH_WARNINGS, + ).length; + const failedItems = items.filter( + (item) => item.status === ProductImportItemStatus.FAILED, + ).length; + const deactivatedIds = await this.getProductsDeactivatedByJob( + job.product_type, + job.specialist_id, + jobId, + tx, + ); + const details = changedProductIds.length + ? ` Produtos alterados: ${changedProductIds.join(', ')}.` + : ''; + await tx.productImportJob.updateMany({ + where: { + id: jobId, + status: { + in: [ + ProductImportJobStatus.PENDING, + ProductImportJobStatus.PROCESSING, + ], + }, + }, + data: { + status: ProductImportJobStatus.COMPLETED_WITH_ERRORS, + total_items: items.length, + processed_items: completed.length + failedItems, + success_items: completed.length, + warning_items: warningItems, + failed_items: failedItems, + deactivated_items: deactivatedIds.length, + deactivated_product_ids: deactivatedIds, + reactivated_items: Math.max( + reactivatedCount, + job.reactivated_items, + ), error_message: - error?.message || 'Erro ao processar job de importação', + `Importação parcial: ${insertedCount} inserido(s), ${updatedCount} atualizado(s). ` + + `O catálogo mudou durante o processamento; nenhuma nova desativação foi aplicada` + + `${deactivatedIds.length ? ` e ${deactivatedIds.length} desativação(ões) anterior(es) do job foi(ram) preservada(s)` : ''}. ` + + `Gere uma nova prévia.${details}`, finished_at: new Date(), }, }); + }); + } + + private async getJobExecutionContext(job: { + id: string; + specialist_id: string; + product_type: ProductType; + }): Promise<{ + mode: ProductImportMode; + syncConfirmed: boolean; + syncPreviewSnapshot: SynchronizePreviewSnapshot | null; + specialistIsEligible: boolean; + }> { + const metadata = await this.prisma.$queryRaw< + Array<{ + mode: string; + sync_confirmed: boolean; + sync_preview_snapshot: SynchronizePreviewSnapshot | null; + }> + >` + SELECT "mode", "sync_confirmed", "sync_preview_snapshot" + FROM "ProductImportJob" + WHERE "id" = ${job.id}::uuid + `; + const specialist = await this.prisma.user.findUnique({ + where: { id: job.specialist_id }, + select: { role: true, is_active: true, speciality: true }, + }); + const row = metadata[0]; + return { + mode: row?.mode === 'SYNCHRONIZE' ? 'SYNCHRONIZE' : 'ADDITIVE', + syncConfirmed: row?.sync_confirmed === true, + syncPreviewSnapshot: row?.sync_preview_snapshot ?? null, + specialistIsEligible: + specialist?.role === UserRole.SPECIALIST && + specialist.is_active === true && + specialist.speciality === job.product_type, + }; + } + + private async estimateImportImpact( + productType: ProductType, + specialistId: string, + rows: ImportParsedRow[], + mode: ProductImportMode, + client: PrismaService | Prisma.TransactionClient = this.prisma, + ) { + const snapshot = await this.getSynchronizationCatalogSnapshot( + productType, + specialistId, + rows, + client, + ); + if (mode === 'SYNCHRONIZE') return snapshot.impact; + return { ...snapshot.impact, deactivationCandidates: 0 }; + } + + private deriveImportImpact( + activeItemsBefore: number, + matchingItems: number, + rows: ImportParsedRow[], + deactivationCandidates: number, + ): ImportImpact { + const incomingIdentifiers = new Set( + rows.map((row) => row.identificador?.trim()).filter(Boolean), + ); + return { + incomingItems: rows.length, + activeItemsBefore, + matchingItems, + newOrReactivatedItems: Math.max( + 0, + incomingIdentifiers.size - matchingItems, + ), + deactivationCandidates, + }; + } + + private async getCatalogProductsByType( + productType: ProductType, + specialistId: string, + client: PrismaService | Prisma.TransactionClient = this.prisma, + ): Promise { + type CatalogRow = { + id: string; + identificador: string; + isActive: boolean; + updatedAt: Date; + rowVersion: string; + }; + const rawClient = client as PrismaService; + if (typeof rawClient.$queryRaw === 'function') { + const rows = + productType === ProductType.CAR + ? await rawClient.$queryRaw` + SELECT "id"::text AS "id", "identificador", + COALESCE("is_active", true) AS "isActive", + "updated_at" AS "updatedAt", xmin::text AS "rowVersion" + FROM "Car" WHERE "specialist_id" = ${specialistId}::uuid + ` + : productType === ProductType.BOAT + ? await rawClient.$queryRaw` + SELECT "id"::text AS "id", "identificador", + COALESCE("is_active", true) AS "isActive", + "updated_at" AS "updatedAt", xmin::text AS "rowVersion" + FROM "Boat" WHERE "specialist_id" = ${specialistId}::uuid + ` + : await rawClient.$queryRaw` + SELECT "id"::text AS "id", "identificador", + COALESCE("is_active", true) AS "isActive", + "updated_at" AS "updatedAt", xmin::text AS "rowVersion" + FROM "Aircraft" WHERE "specialist_id" = ${specialistId}::uuid + `; + return rows.map((product) => ({ + id: product.id, + identificador: product.identificador, + isActive: product.isActive, + updatedAt: product.updatedAt.toISOString(), + rowVersion: product.rowVersion, + })); + } + + // Doubles unitários simples não expõem query raw. Em execução real, + // a consulta única acima captura dados e xmin no mesmo snapshot. + const query = { + where: { specialist_id: specialistId }, + select: { + id: true, + identificador: true, + is_active: true, + updated_at: true, + }, + }; + let products: Array<{ + id: string; + identificador: string; + is_active: boolean; + updated_at: Date; + }>; + if (productType === ProductType.CAR) { + products = await (client as PrismaService).car.findMany(query); + } else if (productType === ProductType.BOAT) { + products = await (client as PrismaService).boat.findMany(query); + } else { + products = await (client as PrismaService).aircraft.findMany(query); } + return products.map((product) => ({ + id: product.id, + identificador: product.identificador, + isActive: product.is_active ?? true, + updatedAt: + product.updated_at instanceof Date + ? product.updated_at.toISOString() + : '1970-01-01T00:00:00.000Z', + rowVersion: `test-double:${product.id}:${ + product.updated_at instanceof Date + ? product.updated_at.toISOString() + : 'unknown' + }`, + })); + } + + private async getActiveProductsByType( + productType: ProductType, + specialistId: string, + client: PrismaService | Prisma.TransactionClient = this.prisma, + ): Promise> { + const products = await this.getCatalogProductsByType( + productType, + specialistId, + client, + ); + return products + .filter((product) => product.isActive) + .map(({ id, identificador }) => ({ id, identificador })); } private async refreshJobCounters( jobId: string, syncSummary?: { deactivatedIds: string[]; reactivatedCount: number }, + client: PrismaService | Prisma.TransactionClient = this.prisma, ) { - const items = await this.prisma.productImportJobItem.findMany({ + const items = await (client as PrismaService).productImportJobItem.findMany({ where: { job_id: jobId }, select: { status: true, @@ -468,7 +1571,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { finalStatus = ProductImportJobStatus.FAILED; } - await this.prisma.productImportJob.update({ + await (client as PrismaService).productImportJob.update({ where: { id: jobId }, data: { status: finalStatus, @@ -485,20 +1588,263 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { }); } + private async finalizeUnsynchronizedJob( + jobId: string, + syncSummary: { deactivatedIds: string[]; reactivatedCount: number }, + leaseToken: string, + ): Promise { + await this.prisma.$transaction(async (tx) => { + await this.assertJobLeaseOwned(tx, jobId, leaseToken); + await this.refreshJobCounters(jobId, syncSummary, tx); + }); + } + + private async finalizeSynchronizedJob( + jobId: string, + input: { + productType: ProductType; + specialistId: string; + seenProductIds: Set; + snapshot: SynchronizePreviewSnapshot | null; + }, + reactivatedCount: number, + leaseToken: string, + ): Promise { + await this.runSerializableWithRetry(async (tx) => { + await this.assertJobLeaseOwned(tx, jobId, leaseToken); + await this.lockProductCatalogForSnapshot(tx, input.productType); + const items = await tx.productImportJobItem.findMany({ + where: { job_id: jobId }, + select: { + status: true, + action: true, + product_id: true, + payload: true, + }, + }); + await this.assertLogicalCatalogMatches( + input.productType, + input.specialistId, + jobId, + input.snapshot, + items, + tx, + ); + const deactivatedIds = await this.deactivateMissingProducts( + input.productType, + input.specialistId, + input.seenProductIds, + jobId, + input.snapshot, + tx, + ); + await this.refreshJobCounters( + jobId, + { deactivatedIds, reactivatedCount }, + tx, + ); + }); + } + + private async lockProductCatalogForSnapshot( + tx: Prisma.TransactionClient, + productType: ProductType, + ): Promise { + if (productType === ProductType.CAR) { + await tx.$executeRaw`LOCK TABLE "Car" IN SHARE ROW EXCLUSIVE MODE`; + } else if (productType === ProductType.BOAT) { + await tx.$executeRaw`LOCK TABLE "Boat" IN SHARE ROW EXCLUSIVE MODE`; + } else { + await tx.$executeRaw`LOCK TABLE "Aircraft" IN SHARE ROW EXCLUSIVE MODE`; + } + } + + private async assertSynchronizationSnapshotCurrent( + job: { + id: string; + product_type: ProductType; + specialist_id: string; + items: Array<{ + payload: unknown; + status: ProductImportItemStatus; + action: string | null; + product_id: string | null; + }>; + }, + snapshot: SynchronizePreviewSnapshot | null, + ): Promise { + if (!snapshot) { + throw this.synchronizePreviewStale(); + } + const incomingIdentifiers = new Set( + job.items + .map((item) => { + const row = item.payload as unknown as ImportParsedRow; + return row.identificador?.trim(); + }) + .filter(Boolean), + ); + await this.runSerializableWithRetry(async (tx) => { + await this.assertLogicalCatalogMatches( + job.product_type, + job.specialist_id, + job.id, + snapshot, + job.items, + tx, + ); + const activeProducts = await this.getActiveProductsByType( + job.product_type, + job.specialist_id, + tx, + ); + const alreadyDeactivatedIds = await this.getProductsDeactivatedByJob( + job.product_type, + job.specialist_id, + job.id, + tx, + ); + const currentCandidateIds = [ + ...activeProducts + .filter( + (product) => !incomingIdentifiers.has(product.identificador), + ) + .map((product) => product.id), + ...alreadyDeactivatedIds, + ].sort(); + this.assertCandidateIdsMatch( + currentCandidateIds, + snapshot.candidateIds, + ); + }); + } + + private async assertLogicalCatalogMatches( + productType: ProductType, + specialistId: string, + jobId: string, + snapshot: SynchronizePreviewSnapshot | null, + items: Array<{ + status: ProductImportItemStatus; + action: string | null; + product_id: string | null; + payload: unknown; + }>, + tx: Prisma.TransactionClient, + ): Promise { + if ( + !snapshot?.catalogDigest || + !Array.isArray(snapshot.catalogProducts) + ) { + throw this.synchronizePreviewStale(); + } + const currentCatalog = await this.getCatalogProductsByType( + productType, + specialistId, + tx, + ); + const originals = new Map( + snapshot.catalogProducts.map((product) => [product.id, product]), + ); + const checkpointedItems = items.filter( + (item) => + item.status === ProductImportItemStatus.COMPLETED || + item.status === ProductImportItemStatus.COMPLETED_WITH_WARNINGS || + item.status === ProductImportItemStatus.PROCESSING, + ); + const effects = new Map(); + for (const item of checkpointedItems) { + const effect = (item.payload as unknown as ImportItemPayload) + .__productImportEffect; + if ( + effect && + item.product_id === effect.productId && + item.action === effect.action + ) { + effects.set(effect.productId, effect); + } + } + const currentProducts = new Map( + currentCatalog.map((product) => [product.id, product]), + ); + for (const effect of effects.values()) { + if ( + effect.action === 'CREATED' && + (!currentProducts.has(effect.productId) || + currentProducts.get(effect.productId)?.rowVersion !== + effect.rowVersion) + ) { + // Produto criado pelo CSV removido/alterado depois do checkpoint não + // existia no snapshot original e, sem esta guarda, desapareceria do + // catálogo lógico sem invalidar a sincronização. + throw this.synchronizePreviewStale(); + } + } + const alreadyDeactivatedIds = new Set( + await this.getProductsDeactivatedByJob( + productType, + specialistId, + jobId, + tx, + ), + ); + const logicalCatalog: CatalogProductSnapshot[] = []; + for (const product of currentCatalog) { + const effect = effects.get(product.id); + const wasDeactivatedByJob = alreadyDeactivatedIds.has(product.id); + if (!effect && !wasDeactivatedByJob) { + logicalCatalog.push(product); + continue; + } + const original = originals.get(product.id); + if (wasDeactivatedByJob) { + if (original) logicalCatalog.push(original); + } else if (effect && product.rowVersion !== effect.rowVersion) { + // Mudança posterior ao checkpoint não pertence a este job. + logicalCatalog.push(product); + } else if (original) { + logicalCatalog.push(original); + } else if (effect?.action !== 'CREATED') { + // Um UPDATED desconhecido não pode ser atribuído ao job com segurança. + logicalCatalog.push(product); + } + } + if (this.catalogDigest(logicalCatalog) !== snapshot.catalogDigest) { + throw this.synchronizePreviewStale(); + } + } + private async deactivateMissingProducts( productType: ProductType, specialistId: string, seenProductIds: Set, jobId: string, + snapshot: SynchronizePreviewSnapshot | null, + tx: Prisma.TransactionClient, ): Promise { - const activeProductIds = await this.getActiveProductIdsByType( + if (!snapshot) { + throw this.synchronizePreviewStale(); + } + const activeProducts = await this.getActiveProductsByType( productType, specialistId, + tx, ); - - const staleIds = activeProductIds.filter((id) => !seenProductIds.has(id)); - - if (staleIds.length === 0) { + const alreadyDeactivatedIds = await this.getProductsDeactivatedByJob( + productType, + specialistId, + jobId, + tx, + ); + const currentCandidateIds = [ + ...activeProducts + .map((product) => product.id) + .filter((id) => !seenProductIds.has(id)), + ...alreadyDeactivatedIds, + ].sort(); + const expectedCandidateIds = [...snapshot.candidateIds].sort(); + this.assertCandidateIdsMatch(currentCandidateIds, expectedCandidateIds); + if (expectedCandidateIds.length === 0) { return []; } @@ -508,30 +1854,86 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { deactivated_by_sync_job_id: jobId, }; - await this.prisma.$transaction(async (tx) => { - for (const productId of [...staleIds].sort()) { - await acquireProductMonetaryLock(tx, { productType, productId }); - } + if (productType === ProductType.CAR) { + await tx.car.updateMany({ + where: { + id: { in: expectedCandidateIds }, + specialist_id: specialistId, + is_active: true, + }, + data, + }); + } else if (productType === ProductType.BOAT) { + await tx.boat.updateMany({ + where: { + id: { in: expectedCandidateIds }, + specialist_id: specialistId, + is_active: true, + }, + data, + }); + } else { + await tx.aircraft.updateMany({ + where: { + id: { in: expectedCandidateIds }, + specialist_id: specialistId, + is_active: true, + }, + data, + }); + } + return expectedCandidateIds; + } - if (productType === ProductType.CAR) { - await tx.car.updateMany({ - where: { id: { in: staleIds }, specialist_id: specialistId }, - data, - }); - } else if (productType === ProductType.BOAT) { - await tx.boat.updateMany({ - where: { id: { in: staleIds }, specialist_id: specialistId }, - data, - }); - } else { - await tx.aircraft.updateMany({ - where: { id: { in: staleIds }, specialist_id: specialistId }, - data, - }); - } - }); + private async getProductsDeactivatedByJob( + productType: ProductType, + specialistId: string, + jobId: string, + client: PrismaService | Prisma.TransactionClient, + ): Promise { + const query = { + where: { + specialist_id: specialistId, + is_active: false, + deactivated_by_sync_job_id: jobId, + }, + select: { id: true }, + }; + if (productType === ProductType.CAR) { + return (await (client as PrismaService).car.findMany(query)).map( + ({ id }) => id, + ); + } + if (productType === ProductType.BOAT) { + return (await (client as PrismaService).boat.findMany(query)).map( + ({ id }) => id, + ); + } + return (await (client as PrismaService).aircraft.findMany(query)).map( + ({ id }) => id, + ); + } - return staleIds; + private assertCandidateIdsMatch( + currentCandidateIds: string[], + expectedCandidateIds: string[], + ): void { + const current = [...currentCandidateIds].sort(); + const expected = [...expectedCandidateIds].sort(); + if ( + current.length !== expected.length || + current.some((id, index) => id !== expected[index]) + ) { + throw this.synchronizePreviewStale(); + } + } + + private synchronizePreviewStale(): ConflictException { + return new ConflictException({ + code: 'SYNCHRONIZE_PREVIEW_STALE', + message: + 'O catálogo mudou desde a prévia. Nenhum produto foi desativado; gere uma nova prévia.', + }); } private async getActiveProductIdsByType( @@ -565,6 +1967,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { productType: ProductType, row: ImportParsedRow, specialistId: string, + client: PrismaService | Prisma.TransactionClient = this.prisma, ): Promise { row = this.normalizeProductRow(row); this.validateRequiredProductFields(row); @@ -598,7 +2001,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { await this.validatePayload(data, CreateCarDto); - const existing = await this.prisma.car.findFirst({ + const existing = await (client as PrismaService).car.findFirst({ where: { specialist_id: specialistId, identificador, @@ -608,7 +2011,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { if (existing) { const { specialist_id: _specialistId, ...updateData } = data; const reactivated = !existing.is_active; - await updateProductWithMonetaryLock(this.prisma, { + const updated = (await updateProductWithMonetaryLock(client, { productType: ProductType.CAR, productId: existing.id, nextValue: data.valor, @@ -619,13 +2022,22 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { deactivated_at: null, deactivated_by_sync_job_id: null, }, - }); + })) as { updated_at?: Date }; - return { productId: existing.id, action: 'UPDATED', reactivated }; + return { + productId: existing.id, + action: 'UPDATED', + reactivated, + updatedAt: updated.updated_at?.toISOString(), + }; } - const created = await this.prisma.car.create({ data }); - return { productId: created.id, action: 'CREATED' }; + const created = await (client as PrismaService).car.create({ data }); + return { + productId: created.id, + action: 'CREATED', + updatedAt: created.updated_at?.toISOString(), + }; } if (productType === ProductType.BOAT) { @@ -653,7 +2065,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { await this.validatePayload(data, CreateBoatDto); - const existing = await this.prisma.boat.findFirst({ + const existing = await (client as PrismaService).boat.findFirst({ where: { specialist_id: specialistId, identificador, @@ -663,7 +2075,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { if (existing) { const { specialist_id: _specialistId, ...updateData } = data; const reactivated = !existing.is_active; - await updateProductWithMonetaryLock(this.prisma, { + const updated = (await updateProductWithMonetaryLock(client, { productType: ProductType.BOAT, productId: existing.id, nextValue: data.valor, @@ -674,13 +2086,22 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { deactivated_at: null, deactivated_by_sync_job_id: null, }, - }); + })) as { updated_at?: Date }; - return { productId: existing.id, action: 'UPDATED', reactivated }; + return { + productId: existing.id, + action: 'UPDATED', + reactivated, + updatedAt: updated.updated_at?.toISOString(), + }; } - const created = await this.prisma.boat.create({ data }); - return { productId: created.id, action: 'CREATED' }; + const created = await (client as PrismaService).boat.create({ data }); + return { + productId: created.id, + action: 'CREATED', + updatedAt: created.updated_at?.toISOString(), + }; } const data = { @@ -702,7 +2123,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { await this.validatePayload(data, CreateAircraftDto); - const existing = await this.prisma.aircraft.findFirst({ + const existing = await (client as PrismaService).aircraft.findFirst({ where: { specialist_id: specialistId, identificador, @@ -712,7 +2133,7 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { if (existing) { const { specialist_id: _specialistId, ...updateData } = data; const reactivated = !existing.is_active; - await updateProductWithMonetaryLock(this.prisma, { + const updated = (await updateProductWithMonetaryLock(client, { productType: ProductType.AIRCRAFT, productId: existing.id, nextValue: data.valor, @@ -723,13 +2144,22 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { deactivated_at: null, deactivated_by_sync_job_id: null, }, - }); + })) as { updated_at?: Date }; - return { productId: existing.id, action: 'UPDATED', reactivated }; + return { + productId: existing.id, + action: 'UPDATED', + reactivated, + updatedAt: updated.updated_at?.toISOString(), + }; } - const created = await this.prisma.aircraft.create({ data }); - return { productId: created.id, action: 'CREATED' }; + const created = await (client as PrismaService).aircraft.create({ data }); + return { + productId: created.id, + action: 'CREATED', + updatedAt: created.updated_at?.toISOString(), + }; } private normalizeProductRow(row: ImportParsedRow): ImportParsedRow { @@ -741,6 +2171,22 @@ export class ProductImportJobsService implements OnModuleInit, OnModuleDestroy { ); } + private validateUniqueIdentifiers(rows: ImportParsedRow[]): void { + const seen = new Set(); + const duplicates = new Set(); + for (const row of rows) { + const identifier = row.identificador?.trim(); + if (!identifier) continue; + if (seen.has(identifier)) duplicates.add(identifier); + seen.add(identifier); + } + if (duplicates.size > 0) { + throw new BadRequestException( + `O CSV contém identificadores duplicados: ${[...duplicates].join(', ')}.`, + ); + } + } + private validateRequiredProductFields(row: ImportParsedRow): void { const missingFields = REQUIRED_PRODUCT_FIELDS.filter( ({ key }) => !row[key], diff --git a/backend/src/features/product-import-jobs/product-sync-preview.postgres.spec.ts b/backend/src/features/product-import-jobs/product-sync-preview.postgres.spec.ts new file mode 100644 index 00000000..3dbc1295 --- /dev/null +++ b/backend/src/features/product-import-jobs/product-sync-preview.postgres.spec.ts @@ -0,0 +1,1008 @@ +import { randomUUID } from 'node:crypto'; +import { + PrismaClient, + ProductImportJobStatus, + ProductType, + UserRole, +} from '@prisma/client'; +import { ProductImportJobsService } from './product-import-jobs.service'; +import { acquireProductMonetaryLock } from '../products/product-monetary-lock'; + +const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL; +const describeWithPostgres = databaseUrl ? describe : describe.skip; + +describeWithPostgres('product synchronization preview — PostgreSQL', () => { + const prisma = new PrismaClient({ + datasources: { db: { url: databaseUrl! } }, + }); + const specialistId = randomUUID(); + const adminId = randomUUID(); + const suffix = randomUUID().replaceAll('-', ''); + const row = { + marca: 'Ferrari', + modelo: 'Roma', + identificador: `KEEP-${suffix}`, + valor: '1000000', + estado: 'SP', + ano: '2024', + }; + const xlsx = { + parseCsv: jest.fn().mockReturnValue({ rows: [row] }), + validateStructure: jest.fn().mockReturnValue({ valid: true }), + } as any; + + beforeAll(async () => { + process.env.PRODUCT_IMPORT_PREVIEW_SECRET = 'postgres-preview-secret'; + await prisma.user.create({ + data: { + id: specialistId, + name: 'Sync', + surname: 'Specialist', + email: `sync-${suffix}@example.test`, + rg: suffix.slice(0, 11), + role: UserRole.SPECIALIST, + speciality: ProductType.CAR, + password_hash: 'not-used', + }, + }); + }); + + beforeEach(async () => { + xlsx.parseCsv.mockReturnValue({ rows: [row] }); + await prisma.productImportJob.deleteMany({ + where: { specialist_id: specialistId }, + }); + await prisma.car.deleteMany({ where: { specialist_id: specialistId } }); + await prisma.car.createMany({ + data: [ + { + specialist_id: specialistId, + identificador: row.identificador, + marca: row.marca, + modelo: row.modelo, + valor: Number(row.valor), + estado: row.estado, + ano: Number(row.ano), + }, + { + specialist_id: specialistId, + identificador: `STALE-B-${suffix}`, + marca: 'Legacy', + modelo: 'B', + valor: 500000, + estado: 'SP', + ano: 2020, + }, + ], + }); + }); + + afterAll(async () => { + await prisma.productImportJob.deleteMany({ + where: { specialist_id: specialistId }, + }); + await prisma.car.deleteMany({ where: { specialist_id: specialistId } }); + await prisma.user.delete({ where: { id: specialistId } }); + await prisma.$disconnect(); + delete process.env.PRODUCT_IMPORT_PREVIEW_SECRET; + }); + + function createService( + drive = { importImagesForProductFromFolder: jest.fn() } as any, + ) { + const service = new ProductImportJobsService( + prisma as any, + xlsx, + drive, + ); + jest.spyOn(service as any, 'scheduleJob').mockImplementation(() => {}); + return service; + } + + function options(token: string) { + return { + mode: 'SYNCHRONIZE' as const, + confirmSynchronize: true, + synchronizePreviewToken: token, + context: { + actorId: adminId, + actorRole: UserRole.ADMIN, + actor: { id: adminId, role: UserRole.ADMIN, name: 'Admin', surname: '' }, + specialistId, + specialist: {} as any, + delegated: true, + }, + }; + } + + it('rejeita o POST se um novo candidato surgiu depois da prévia', async () => { + const service = createService(); + const file = Buffer.from('same-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + await prisma.car.create({ + data: { + specialist_id: specialistId, + identificador: `NEW-C-BEFORE-${suffix}`, + marca: 'New', + modelo: 'C', + valor: 600000, + estado: 'RJ', + ano: 2025, + }, + }); + + await expect( + service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ), + ).rejects.toMatchObject({ + response: expect.objectContaining({ code: 'SYNCHRONIZE_PREVIEW_STALE' }), + }); + await expect( + prisma.productImportJob.count({ where: { specialist_id: specialistId } }), + ).resolves.toBe(0); + }); + + it('rejeita o POST se um produto do CSV saiu do catálogo sem mudar candidatos', async () => { + const service = createService(); + const file = Buffer.from('same-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + await prisma.car.updateMany({ + where: { + specialist_id: specialistId, + identificador: row.identificador, + }, + data: { is_active: false, deactivated_at: new Date() }, + }); + + await expect( + service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ), + ).rejects.toMatchObject({ + response: expect.objectContaining({ code: 'SYNCHRONIZE_PREVIEW_STALE' }), + }); + await expect( + prisma.productImportJob.count({ where: { specialist_id: specialistId } }), + ).resolves.toBe(0); + }); + + it('não desativa nada se o catálogo mudar entre o POST e a execução', async () => { + const service = createService(); + const file = Buffer.from('same-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + await prisma.car.updateMany({ + where: { + specialist_id: specialistId, + identificador: row.identificador, + }, + data: { modelo: 'Antes do worker', valor: 123456 }, + }); + const productC = await prisma.car.create({ + data: { + specialist_id: specialistId, + identificador: `NEW-C-AFTER-${suffix}`, + marca: 'New', + modelo: 'C', + valor: 600000, + estado: 'RJ', + ano: 2025, + }, + }); + + await (service as any).processJob(accepted.jobId); + + const products = await prisma.car.findMany({ + where: { specialist_id: specialistId }, + select: { + id: true, + identificador: true, + modelo: true, + valor: true, + is_active: true, + }, + }); + expect(products).toHaveLength(3); + expect(products.every((product) => product.is_active)).toBe(true); + expect(products.find((product) => product.id === productC.id)?.is_active).toBe( + true, + ); + const kept = products.find( + (product) => product.identificador === row.identificador, + ); + expect(kept?.modelo).toBe('Antes do worker'); + expect(Number(kept?.valor)).toBe(123456); + await expect( + prisma.productImportJob.findUniqueOrThrow({ + where: { id: accepted.jobId }, + select: { + status: true, + deactivated_items: true, + error_message: true, + }, + }), + ).resolves.toMatchObject({ + status: ProductImportJobStatus.FAILED, + deactivated_items: 0, + error_message: expect.stringContaining('catálogo mudou'), + }); + }); + + it('não processa linhas se produto do CSV sair do catálogo antes do worker', async () => { + const service = createService(); + const file = Buffer.from('same-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + const matching = await prisma.car.findFirstOrThrow({ + where: { + specialist_id: specialistId, + identificador: row.identificador, + }, + }); + await prisma.car.update({ + where: { id: matching.id }, + data: { + is_active: false, + deactivated_at: new Date(), + modelo: 'External change', + valor: 321654, + }, + }); + + await (service as any).processJob(accepted.jobId); + + const unchanged = await prisma.car.findUniqueOrThrow({ + where: { id: matching.id }, + }); + expect(unchanged).toMatchObject({ + is_active: false, + modelo: 'External change', + }); + expect(Number(unchanged.valor)).toBe(321654); + await expect( + prisma.productImportJob.findUniqueOrThrow({ + where: { id: accepted.jobId }, + select: { status: true, success_items: true }, + }), + ).resolves.toEqual({ + status: ProductImportJobStatus.FAILED, + success_items: 0, + }); + }); + + it('desativa somente o candidato consentido quando o snapshot permanece igual', async () => { + const service = createService(); + const file = Buffer.from('same-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + + await (service as any).processJob(accepted.jobId); + + const products = await prisma.car.findMany({ + where: { specialist_id: specialistId }, + select: { identificador: true, is_active: true }, + }); + expect( + products.find((product) => product.identificador === row.identificador), + ).toMatchObject({ is_active: true }); + expect( + products.find((product) => product.identificador.startsWith('STALE-B-')), + ).toMatchObject({ is_active: false }); + await expect( + prisma.productImportJob.findUniqueOrThrow({ + where: { id: accepted.jobId }, + select: { status: true, deactivated_items: true }, + }), + ).resolves.toEqual({ + status: ProductImportJobStatus.COMPLETED, + deactivated_items: 1, + }); + }); + + it('relata alterações parciais se D surgir durante o processamento', async () => { + const service = createService(); + const file = Buffer.from('same-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + const realUpsert = (service as any).upsertProductFromRow.bind(service); + let productDId: string | undefined; + jest + .spyOn(service as any, 'upsertProductFromRow') + .mockImplementation(async (...args: unknown[]) => { + const result = await realUpsert(...args); + const productD = await prisma.car.create({ + data: { + specialist_id: specialistId, + identificador: `NEW-D-DURING-${suffix}`, + marca: 'New', + modelo: 'D', + valor: 700000, + estado: 'MG', + ano: 2026, + }, + }); + productDId = productD.id; + return result; + }); + + await (service as any).processJob(accepted.jobId); + + const products = await prisma.car.findMany({ + where: { specialist_id: specialistId }, + select: { id: true, identificador: true, modelo: true, is_active: true }, + }); + const kept = products.find( + (product) => product.identificador === row.identificador, + ); + expect(kept).toMatchObject({ modelo: row.modelo, is_active: true }); + expect(products.find((product) => product.id === productDId)).toMatchObject({ + is_active: true, + }); + expect( + products.find((product) => product.identificador.startsWith('STALE-B-')), + ).toMatchObject({ is_active: true }); + + const status = await service.getJobStatus( + accepted.jobId, + { id: adminId, role: UserRole.ADMIN } as any, + specialistId, + ); + expect(status).toMatchObject({ + status: ProductImportJobStatus.COMPLETED_WITH_ERRORS, + deactivatedItems: 0, + errorMessage: expect.stringContaining('Importação parcial'), + result: { + message: expect.stringContaining('Importação parcial'), + updatedIds: [kept!.id], + deactivatedCount: 0, + }, + }); + }); + + it('detecta alteração externa de A depois do checkpoint e antes da finalização', async () => { + let keptId = ''; + let leaseWasExtendedForDrive = false; + const drive = { + importImagesForProductFromFolder: jest.fn(async () => { + const [lease] = await prisma.$queryRaw< + Array<{ extended: boolean }> + >` + SELECT "processing_lease_expires_at" > NOW() + INTERVAL '20 minutes' AS "extended" + FROM "ProductImportJob" + WHERE "id" = ${acceptedJobId}::uuid + `; + leaseWasExtendedForDrive = lease?.extended === true; + await prisma.car.update({ + where: { id: keptId }, + data: { modelo: 'External after checkpoint', valor: 654321 }, + }); + return { failed: 0, warnings: [] }; + }), + } as any; + const service = createService(drive); + let acceptedJobId = ''; + const file = Buffer.from('same-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + acceptedJobId = accepted.jobId; + const kept = await prisma.car.findFirstOrThrow({ + where: { specialist_id: specialistId, identificador: row.identificador }, + }); + keptId = kept.id; + await prisma.productImportJobItem.updateMany({ + where: { job_id: accepted.jobId }, + data: { folder_url: 'https://drive.example/folder' }, + }); + + await (service as any).processJob(accepted.jobId); + + expect(leaseWasExtendedForDrive).toBe(true); + + await expect( + prisma.car.findUniqueOrThrow({ where: { id: kept.id } }), + ).resolves.toMatchObject({ + modelo: 'External after checkpoint', + is_active: true, + }); + await expect( + prisma.productImportJob.findUniqueOrThrow({ + where: { id: accepted.jobId }, + select: { status: true, deactivated_items: true, error_message: true }, + }), + ).resolves.toMatchObject({ + status: ProductImportJobStatus.COMPLETED_WITH_ERRORS, + deactivated_items: 0, + error_message: expect.stringContaining('Importação parcial'), + }); + }); + + it('retoma efeito checkpointado atomicamente sem repetir o upsert', async () => { + const service = createService(); + const file = Buffer.from('same-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + const kept = await prisma.car.findFirstOrThrow({ + where: { specialist_id: specialistId, identificador: row.identificador }, + }); + const updated = await prisma.car.update({ + where: { id: kept.id }, + data: { modelo: row.modelo, valor: Number(row.valor) }, + }); + const [version] = await prisma.$queryRaw>` + SELECT xmin::text AS "rowVersion" + FROM "Car" + WHERE "id" = ${kept.id}::uuid + `; + await prisma.productImportJobItem.updateMany({ + where: { job_id: accepted.jobId }, + data: { + status: 'PROCESSING', + product_id: kept.id, + action: 'UPDATED', + payload: { + ...row, + __productImportEffect: { + productId: kept.id, + action: 'UPDATED', + rowVersion: version.rowVersion, + updatedAt: updated.updated_at.toISOString(), + }, + }, + }, + }); + const upsert = jest.spyOn(service as any, 'upsertProductFromRow'); + + await (service as any).processJob(accepted.jobId); + + expect(upsert).not.toHaveBeenCalled(); + await expect( + prisma.productImportJob.findUniqueOrThrow({ + where: { id: accepted.jobId }, + select: { status: true, deactivated_items: true }, + }), + ).resolves.toEqual({ + status: ProductImportJobStatus.COMPLETED, + deactivated_items: 1, + }); + }); + + it('concede o claim distribuído do job a apenas um worker', async () => { + const first = createService(); + const second = createService(); + const file = Buffer.from('same-csv'); + const preview = await first.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await first.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + + const claims = await Promise.all([ + (first as any).claimJob(accepted.jobId), + (second as any).claimJob(accepted.jobId), + ]); + + expect(claims.filter(Boolean)).toHaveLength(1); + expect(claims.filter((claim) => claim === null)).toHaveLength(1); + }); + + it('impede worker antigo de gravar depois que outro assumiu o lease', async () => { + const staleWorker = createService(); + const currentWorker = createService(); + const file = Buffer.from('same-csv'); + const preview = await staleWorker.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await staleWorker.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + const staleLease = await (staleWorker as any).claimJob(accepted.jobId); + expect(staleLease).toEqual(expect.any(String)); + await prisma.$executeRaw` + UPDATE "ProductImportJob" + SET "processing_lease_expires_at" = NOW() - INTERVAL '1 second' + WHERE "id" = ${accepted.jobId}::uuid + `; + const currentLease = await (currentWorker as any).claimJob(accepted.jobId); + expect(currentLease).toEqual(expect.any(String)); + const job = await prisma.productImportJob.findUniqueOrThrow({ + where: { id: accepted.jobId }, + include: { items: true }, + }); + const item = job.items[0]; + + await expect( + (staleWorker as any).checkpointProductUpsert( + job, + item, + { ...row, modelo: 'Stale worker mutation' }, + staleLease, + ), + ).rejects.toThrow(/lease/i); + await (staleWorker as any).markJobFailedUnlessTerminal( + accepted.jobId, + 'stale worker failure', + staleLease, + ); + + await expect( + prisma.car.findFirstOrThrow({ + where: { specialist_id: specialistId, identificador: row.identificador }, + select: { modelo: true }, + }), + ).resolves.toEqual({ modelo: row.modelo }); + const leaseState = await prisma.$queryRaw< + Array<{ status: ProductImportJobStatus; processing_lease_token: string }> + >` + SELECT "status", "processing_lease_token"::text + FROM "ProductImportJob" + WHERE "id" = ${accepted.jobId}::uuid + `; + expect(leaseState).toEqual([ + { + status: ProductImportJobStatus.PROCESSING, + processing_lease_token: currentLease, + }, + ]); + }); + + it('detecta mudança externa mesmo quando updated_at coincide com o checkpoint', async () => { + const service = createService(); + const file = Buffer.from('same-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + const lease = await (service as any).claimJob(accepted.jobId); + const job = await prisma.productImportJob.findUniqueOrThrow({ + where: { id: accepted.jobId }, + include: { items: true }, + }); + const item = job.items[0]; + await (service as any).checkpointProductUpsert( + job, + item, + item.payload, + lease, + ); + const checkpointed = await prisma.productImportJobItem.findUniqueOrThrow({ + where: { id: item.id }, + }); + const checkpointTimestamp = new Date( + (checkpointed.payload as any).__productImportEffect.updatedAt, + ); + await prisma.car.update({ + where: { id: checkpointed.product_id! }, + data: { + modelo: 'External same timestamp', + valor: 987654, + updated_at: checkpointTimestamp, + }, + }); + await (service as any).releaseJobLease(accepted.jobId, lease); + + await (service as any).processJob(accepted.jobId); + + await expect( + prisma.car.findUniqueOrThrow({ where: { id: checkpointed.product_id! } }), + ).resolves.toMatchObject({ + modelo: 'External same timestamp', + is_active: true, + }); + await expect( + prisma.productImportJob.findUniqueOrThrow({ + where: { id: accepted.jobId }, + select: { status: true, deactivated_items: true, error_message: true }, + }), + ).resolves.toMatchObject({ + status: ProductImportJobStatus.COMPLETED_WITH_ERRORS, + deactivated_items: 0, + error_message: expect.stringContaining('Importação parcial'), + }); + await expect( + prisma.productImportJobItem.findUniqueOrThrow({ + where: { id: item.id }, + select: { status: true, warnings: true }, + }), + ).resolves.toMatchObject({ + status: 'COMPLETED_WITH_WARNINGS', + warnings: expect.arrayContaining([ + expect.stringContaining('catálogo mudou'), + ]), + }); + const status = await service.getJobStatus( + accepted.jobId, + { id: adminId, role: UserRole.ADMIN } as any, + specialistId, + ); + expect(status.result.updatedIds).toContain(checkpointed.product_id); + }); + + it('não finaliza se produto criado pelo job for removido após o checkpoint', async () => { + const createdRow = { + ...row, + identificador: `CREATED-THEN-DELETED-${suffix}`, + modelo: 'Created then deleted', + }; + xlsx.parseCsv.mockReturnValue({ rows: [createdRow] }); + let createdId = ''; + const drive = { + importImagesForProductFromFolder: jest.fn(async ({ product_id }) => { + createdId = product_id; + await prisma.car.delete({ where: { id: product_id } }); + return { failed: 0, warnings: [] }; + }), + } as any; + const service = createService(drive); + const file = Buffer.from('created-delete-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + await prisma.productImportJobItem.updateMany({ + where: { job_id: accepted.jobId }, + data: { folder_url: 'https://drive.example/folder' }, + }); + + await (service as any).processJob(accepted.jobId); + + expect(createdId).toEqual(expect.any(String)); + await expect( + prisma.car.count({ where: { id: createdId } }), + ).resolves.toBe(0); + await expect( + prisma.car.count({ + where: { specialist_id: specialistId, is_active: true }, + }), + ).resolves.toBe(2); + await expect( + prisma.productImportJob.findUniqueOrThrow({ + where: { id: accepted.jobId }, + select: { status: true, deactivated_items: true, error_message: true }, + }), + ).resolves.toMatchObject({ + status: ProductImportJobStatus.COMPLETED_WITH_ERRORS, + deactivated_items: 0, + error_message: expect.stringContaining('Importação parcial'), + }); + }); + + it('não cria deadlock com uma mutação manual que já detém o lock monetário', async () => { + const service = createService(); + const file = Buffer.from('same-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + const candidate = await prisma.car.findFirstOrThrow({ + where: { + specialist_id: specialistId, + identificador: { startsWith: 'STALE-B-' }, + }, + }); + let advisoryReady!: () => void; + const advisoryAcquired = new Promise((resolve) => { + advisoryReady = resolve; + }); + let allowManualUpdate!: () => void; + const manualUpdateGate = new Promise((resolve) => { + allowManualUpdate = resolve; + }); + const manualUpdate = prisma.$transaction(async (tx) => { + await acquireProductMonetaryLock(tx, { + productType: ProductType.CAR, + productId: candidate.id, + }); + advisoryReady(); + await manualUpdateGate; + return tx.car.update({ + where: { id: candidate.id }, + data: { modelo: 'Manual after sync lock' }, + }); + }); + await advisoryAcquired; + + const realCatalogLock = ( + service as any + ).lockProductCatalogForSnapshot.bind(service); + let catalogReady!: () => void; + const catalogLocked = new Promise((resolve) => { + catalogReady = resolve; + }); + jest + .spyOn(service as any, 'lockProductCatalogForSnapshot') + .mockImplementation(async (...args: unknown[]) => { + const result = await realCatalogLock(...args); + catalogReady(); + return result; + }); + const processing = (service as any).processJob(accepted.jobId); + await catalogLocked; + allowManualUpdate(); + + await Promise.all([manualUpdate, processing]); + + await expect( + prisma.productImportJob.findUniqueOrThrow({ + where: { id: accepted.jobId }, + select: { status: true }, + }), + ).resolves.toEqual({ status: ProductImportJobStatus.COMPLETED }); + }); + + it('retoma como COMPLETED quando o próprio job já desativou o candidato', async () => { + const service = createService(); + const file = Buffer.from('same-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + const [kept, candidate] = await Promise.all([ + prisma.car.findFirstOrThrow({ + where: { + specialist_id: specialistId, + identificador: row.identificador, + }, + }), + prisma.car.findFirstOrThrow({ + where: { + specialist_id: specialistId, + identificador: { startsWith: 'STALE-B-' }, + }, + }), + ]); + await prisma.$transaction([ + prisma.car.update({ + where: { id: candidate.id }, + data: { + is_active: false, + deactivated_at: new Date(), + deactivated_by_sync_job_id: accepted.jobId, + }, + }), + prisma.productImportJobItem.updateMany({ + where: { job_id: accepted.jobId }, + data: { + status: 'COMPLETED', + product_id: kept.id, + action: 'UPDATED', + processed_at: new Date(), + }, + }), + prisma.productImportJob.update({ + where: { id: accepted.jobId }, + data: { status: ProductImportJobStatus.PROCESSING }, + }), + ]); + + await (service as any).processJob(accepted.jobId); + + await expect( + prisma.productImportJob.findUniqueOrThrow({ + where: { id: accepted.jobId }, + select: { + status: true, + deactivated_items: true, + deactivated_product_ids: true, + error_message: true, + }, + }), + ).resolves.toEqual({ + status: ProductImportJobStatus.COMPLETED, + deactivated_items: 1, + deactivated_product_ids: [candidate.id], + error_message: null, + }); + }); + + it('relata retomada parcial se D surgiu após C ter sido desativado pelo job', async () => { + const service = createService(); + const file = Buffer.from('same-csv'); + const preview = await service.previewCsvImport( + file, + ProductType.CAR, + specialistId, + 'SYNCHRONIZE', + ); + const accepted = await service.createJobFromCsv( + file, + { id: adminId, role: UserRole.ADMIN } as any, + ProductType.CAR, + options(preview.synchronizePreviewToken!), + ); + const [kept, candidate] = await Promise.all([ + prisma.car.findFirstOrThrow({ + where: { + specialist_id: specialistId, + identificador: row.identificador, + }, + }), + prisma.car.findFirstOrThrow({ + where: { + specialist_id: specialistId, + identificador: { startsWith: 'STALE-B-' }, + }, + }), + ]); + await prisma.$transaction([ + prisma.car.update({ + where: { id: candidate.id }, + data: { + is_active: false, + deactivated_at: new Date(), + deactivated_by_sync_job_id: accepted.jobId, + }, + }), + prisma.productImportJobItem.updateMany({ + where: { job_id: accepted.jobId }, + data: { + status: 'COMPLETED', + product_id: kept.id, + action: 'UPDATED', + processed_at: new Date(), + }, + }), + prisma.productImportJob.update({ + where: { id: accepted.jobId }, + data: { status: ProductImportJobStatus.PROCESSING }, + }), + ]); + const productD = await prisma.car.create({ + data: { + specialist_id: specialistId, + identificador: `NEW-D-RESUME-${suffix}`, + marca: 'New', + modelo: 'D', + valor: 700000, + estado: 'MG', + ano: 2026, + }, + }); + + await (service as any).processJob(accepted.jobId); + + await expect( + prisma.car.findUniqueOrThrow({ + where: { id: productD.id }, + select: { is_active: true }, + }), + ).resolves.toEqual({ is_active: true }); + await expect( + prisma.productImportJob.findUniqueOrThrow({ + where: { id: accepted.jobId }, + select: { + status: true, + deactivated_items: true, + deactivated_product_ids: true, + error_message: true, + }, + }), + ).resolves.toMatchObject({ + status: ProductImportJobStatus.COMPLETED_WITH_ERRORS, + deactivated_items: 1, + deactivated_product_ids: [candidate.id], + error_message: expect.stringContaining('Importação parcial'), + }); + }); +}); diff --git a/backend/src/features/products/product-association-concurrency.postgres.spec.ts b/backend/src/features/products/product-association-concurrency.postgres.spec.ts index 817b92d9..7b54b502 100644 --- a/backend/src/features/products/product-association-concurrency.postgres.spec.ts +++ b/backend/src/features/products/product-association-concurrency.postgres.spec.ts @@ -1,5 +1,11 @@ import { randomUUID } from 'node:crypto'; -import { PrismaClient, ProductCurrency, ProductType, UserRole } from '@prisma/client'; +import { + AppointmentSchedulingMethod, + PrismaClient, + ProductCurrency, + ProductType, + UserRole, +} from '@prisma/client'; import { BadRequestException } from '@nestjs/common'; import { ConflictException } from '@nestjs/common'; import { CarsService } from '../cars/cars.service'; @@ -85,6 +91,93 @@ function signalProductLockAttempt(client: PrismaClient, attempted: Deferred) { }); } +async function deleteFixtureProcesses( + client: PrismaClient, + clientId: string, + specialistId: string, +): Promise { + const processes = await client.process.findMany({ + where: { client_id: clientId, specialist_id: specialistId }, + select: { id: true }, + }); + const processIds = processes.map(({ id }) => id); + await client.processStatusHistory.deleteMany({ + where: { processId: { in: processIds } }, + }); + await client.process.deleteMany({ + where: { id: { in: processIds } }, + }); +} + +describe('product association fixture cleanup', () => { + it('removes restricted history before its own processes and preserves other fixtures', async () => { + const clientId = 'fixture-client'; + const specialistId = 'fixture-specialist'; + let processes = [ + { id: 'own-process', client_id: clientId, specialist_id: specialistId }, + { + id: 'other-client-process', + client_id: 'other-client', + specialist_id: specialistId, + }, + { + id: 'other-specialist-process', + client_id: clientId, + specialist_id: 'other-specialist', + }, + ]; + let history = processes.map(({ id }) => ({ processId: id })); + const deletionOrder: string[] = []; + const client = { + process: { + findMany: async ({ where }: any) => + processes + .filter( + (row) => + row.client_id === where.client_id && + row.specialist_id === where.specialist_id, + ) + .map(({ id }) => ({ id })), + deleteMany: async ({ where }: any) => { + const targets = processes + .filter((row) => + where.id + ? where.id.in.includes(row.id) + : row.client_id === where.client_id && + row.specialist_id === where.specialist_id, + ) + .map(({ id }) => id); + if (history.some(({ processId }) => targets.includes(processId))) { + throw new Error('ProcessStatusHistory FK RESTRICT'); + } + processes = processes.filter(({ id }) => !targets.includes(id)); + deletionOrder.push('process'); + }, + }, + processStatusHistory: { + deleteMany: async ({ where }: any) => { + history = history.filter( + ({ processId }) => !where.processId.in.includes(processId), + ); + deletionOrder.push('history'); + }, + }, + } as unknown as PrismaClient; + + await deleteFixtureProcesses(client, clientId, specialistId); + + expect(deletionOrder).toEqual(['history', 'process']); + expect(processes.map(({ id }) => id)).toEqual([ + 'other-client-process', + 'other-specialist-process', + ]); + expect(history.map(({ processId }) => processId)).toEqual([ + 'other-client-process', + 'other-specialist-process', + ]); + }); +}); + const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL; const describeWithPostgres = databaseUrl ? describe : describe.skip; @@ -93,27 +186,9 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = const clientId = randomUUID(); const specialistId = randomUUID(); const carId = randomUUID(); - const updater = new PrismaClient({ - datasources: { - db: { - url: withApplicationName(databaseUrl!, `product_mutation_${suffix}`), - }, - }, - }); - const creator = new PrismaClient({ - datasources: { - db: { - url: withApplicationName(databaseUrl!, `product_consumer_${suffix}`), - }, - }, - }); - const competitor = new PrismaClient({ - datasources: { - db: { - url: withApplicationName(databaseUrl!, `product_competitor_${suffix}`), - }, - }, - }); + let updater: PrismaClient; + let creator: PrismaClient; + let competitor: PrismaClient; beforeEach(async () => { const processes = await updater.process.findMany({ @@ -140,6 +215,27 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = }); beforeAll(async () => { + updater = new PrismaClient({ + datasources: { + db: { + url: withApplicationName(databaseUrl!, `product_mutation_${suffix}`), + }, + }, + }); + creator = new PrismaClient({ + datasources: { + db: { + url: withApplicationName(databaseUrl!, `product_consumer_${suffix}`), + }, + }, + }); + competitor = new PrismaClient({ + datasources: { + db: { + url: withApplicationName(databaseUrl!, `product_competitor_${suffix}`), + }, + }, + }); await updater.user.createMany({ data: [ { @@ -179,17 +275,24 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = }); afterAll(async () => { - await updater.process.deleteMany({ - where: { client_id: clientId, specialist_id: specialistId }, - }); - await updater.appointment.deleteMany({ - where: { client_id: clientId, specialist_id: specialistId }, - }); - await updater.car.deleteMany({ where: { id: carId } }); - await updater.user.deleteMany({ - where: { id: { in: [clientId, specialistId] } }, - }); - await Promise.all([updater.$disconnect(), creator.$disconnect(), competitor.$disconnect()]); + try { + if (updater) { + await deleteFixtureProcesses(updater, clientId, specialistId); + await updater.appointment.deleteMany({ + where: { client_id: clientId, specialist_id: specialistId }, + }); + await updater.car.deleteMany({ where: { id: carId } }); + await updater.user.deleteMany({ + where: { id: { in: [clientId, specialistId] } }, + }); + } + } finally { + await Promise.all([ + updater?.$disconnect(), + creator?.$disconnect(), + competitor?.$disconnect(), + ]); + } }); it('serializes deactivation against creation and rejects the now-inactive product', async () => { @@ -208,14 +311,15 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = const deactivate = cars.remove(carId); await mutationReached.promise; - const create = appointments.create( + const create = appointments.createPending( { client_id: clientId, specialist_id: specialistId, product_type: ProductType.CAR, product_id: carId, appointment_datetime: '2099-01-01T10:00:00.000Z', - } as any, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + }, clientId, UserRole.CUSTOMER, ); @@ -225,6 +329,7 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = await expect(deactivate).resolves.toEqual({ ok: true }); await expect(create).rejects.toBeInstanceOf(BadRequestException); await expect(updater.appointment.count({ where: { product_id: carId } })).resolves.toBe(0); + await expect(updater.process.count({ where: { car_id: carId } })).resolves.toBe(0); }, 15_000); it('serializes late assignment against creation on the target product identity', async () => { @@ -273,14 +378,15 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = sendAppointmentCreatedEmail: jest.fn().mockResolvedValue(undefined), } as any, {} as any, - ).create( + ).createPending( { client_id: clientId, specialist_id: specialistId, product_type: ProductType.CAR, product_id: carId, appointment_datetime: '2099-01-01T10:00:00.000Z', - } as any, + scheduling_method: AppointmentSchedulingMethod.EMAIL, + }, clientId, UserRole.CUSTOMER, ); @@ -293,6 +399,14 @@ describeWithPostgres('product association lock — PostgreSQL concurrency', () = expect(outcomes.find(({ status }) => status === 'rejected')).toMatchObject({ reason: expect.any(ConflictException), }); + if (outcomes[1].status === 'fulfilled') { + expect(outcomes[1].value).toMatchObject({ + status: 'PENDING', + scheduling_method: AppointmentSchedulingMethod.EMAIL, + appointment_datetime: new Date('2099-01-01T10:00:00.000Z'), + process_id: expect.any(String), + }); + } await expect( updater.process.count({ where: { diff --git a/backend/src/features/products/product-association-validator.ts b/backend/src/features/products/product-association-validator.ts index 95490eb4..cce5d741 100644 --- a/backend/src/features/products/product-association-validator.ts +++ b/backend/src/features/products/product-association-validator.ts @@ -35,7 +35,7 @@ export async function validateSpecialistProductAssociation( const specialist = await client.user.findUnique({ where: { id: input.specialistId }, - select: { id: true, role: true, speciality: true }, + select: { id: true, role: true, speciality: true, is_active: true }, }); if (!specialist) { throw new NotFoundException('Especialista não encontrado'); @@ -43,9 +43,11 @@ export async function validateSpecialistProductAssociation( if (specialist.role !== UserRole.SPECIALIST) { throw new BadRequestException('Usuário informado não é especialista'); } + if (specialist.is_active === false) { + throw new ForbiddenException('Especialista inativo'); + } if ( input.productType && - specialist.speciality && specialist.speciality !== input.productType ) { throw new BadRequestException( diff --git a/backend/src/features/products/product-delegated-audit.postgres.spec.ts b/backend/src/features/products/product-delegated-audit.postgres.spec.ts new file mode 100644 index 00000000..46bd43f6 --- /dev/null +++ b/backend/src/features/products/product-delegated-audit.postgres.spec.ts @@ -0,0 +1,166 @@ +import { randomUUID } from 'node:crypto'; +import { PrismaClient, ProductType, UserRole } from '@prisma/client'; +import { CarsController } from '../cars/cars.controller'; +import { CarsService } from '../cars/cars.service'; +import { BoatsController } from '../boats/boats.controller'; +import { BoatsService } from '../boats/boats.service'; +import { AircraftsController } from '../aircrafts/aircrafts.controller'; +import { AircraftsService } from '../aircrafts/aircrafts.service'; + +const databaseUrl = process.env.POSTGRES_CONCURRENCY_TEST_URL; +const describeWithPostgres = databaseUrl ? describe : describe.skip; + +describeWithPostgres('delegated product mutation audit — PostgreSQL', () => { + const prisma = new PrismaClient({ + datasources: { db: { url: databaseUrl! } }, + }); + const specialistId = randomUUID(); + const adminId = randomUUID(); + const suffix = randomUUID().replaceAll('-', ''); + const s3 = { + uploadBase64Image: jest.fn(), + getSignedUrl: jest.fn(async (key) => key), + } as any; + const actorContext = { + resolve: jest.fn(async (user, target) => ({ + actorId: user.id, + actorRole: user.role, + actor: { id: user.id, role: user.role, name: 'Admin', surname: '' }, + specialistId: target, + specialist: {}, + delegated: true, + })), + assertResourceSpecialist: jest.fn((context, owner) => { + if (context.specialistId !== owner) throw new Error('wrong owner'); + }), + } as any; + const audit = { + record: jest.fn(async () => { + throw new Error('audit unavailable'); + }), + } as any; + const jobs = {} as any; + const admin = { id: adminId, role: UserRole.ADMIN } as any; + + beforeAll(async () => { + await prisma.user.create({ + data: { + id: specialistId, + name: 'Audit', + surname: 'Specialist', + email: `audit-${suffix}@example.test`, + rg: suffix.slice(0, 11), + role: UserRole.SPECIALIST, + speciality: ProductType.CAR, + password_hash: 'not-used', + }, + }); + }); + + beforeEach(async () => { + audit.record.mockClear(); + await prisma.car.deleteMany({ where: { specialist_id: specialistId } }); + await prisma.boat.deleteMany({ where: { specialist_id: specialistId } }); + await prisma.aircraft.deleteMany({ + where: { specialist_id: specialistId }, + }); + }); + + afterAll(async () => { + await prisma.car.deleteMany({ where: { specialist_id: specialistId } }); + await prisma.boat.deleteMany({ where: { specialist_id: specialistId } }); + await prisma.aircraft.deleteMany({ + where: { specialist_id: specialistId }, + }); + await prisma.user.delete({ where: { id: specialistId } }); + await prisma.$disconnect(); + }); + + const cases = [ + { + label: 'CAR', + delegate: 'car', + controller: new CarsController( + new CarsService(prisma as any, s3), + jobs, + actorContext, + audit, + prisma as any, + ), + }, + { + label: 'BOAT', + delegate: 'boat', + controller: new BoatsController( + new BoatsService(prisma as any, s3), + jobs, + actorContext, + audit, + prisma as any, + ), + }, + { + label: 'AIRCRAFT', + delegate: 'aircraft', + controller: new AircraftsController( + new AircraftsService(prisma as any, s3), + jobs, + actorContext, + audit, + prisma as any, + ), + }, + ] as const; + + it.each(cases)( + 'reverte POST/PATCH/DELETE de $label quando a auditoria falha', + async ({ label, delegate, controller }) => { + const model = (prisma as any)[delegate]; + const createDto = { + specialist_id: specialistId, + identificador: `${label}-CREATE-${suffix}`, + marca: 'Original', + modelo: 'Original', + valor: 100000, + estado: 'SP', + ano: 2024, + }; + + await expect( + (controller as any).create({ ...createDto }, admin), + ).rejects.toThrow('audit unavailable'); + await expect( + model.count({ where: { identificador: createDto.identificador } }), + ).resolves.toBe(0); + + const existing = await model.create({ + data: { + ...createDto, + identificador: `${label}-EXISTING-${suffix}`, + }, + }); + await expect( + (controller as any).update( + existing.id, + { modelo: 'Changed' }, + admin, + specialistId, + ), + ).rejects.toThrow('audit unavailable'); + await expect( + model.findUnique({ where: { id: existing.id }, select: { modelo: true } }), + ).resolves.toEqual({ modelo: 'Original' }); + + await expect( + (controller as any).remove(existing.id, admin, specialistId), + ).rejects.toThrow('audit unavailable'); + await expect( + model.findUnique({ + where: { id: existing.id }, + select: { is_active: true }, + }), + ).resolves.toEqual({ is_active: true }); + expect(audit.record).toHaveBeenCalledTimes(3); + }, + ); +}); diff --git a/backend/src/features/products/product-image-preparation.spec.ts b/backend/src/features/products/product-image-preparation.spec.ts new file mode 100644 index 00000000..0b05aa56 --- /dev/null +++ b/backend/src/features/products/product-image-preparation.spec.ts @@ -0,0 +1,79 @@ +import { + cleanupPreparedProductImages, + prepareProductImages, +} from './product-image-preparation'; +import { Logger } from '@nestjs/common'; + +describe('product image preparation', () => { + it('remove somente uploads concluídos se um upload posterior falhar', async () => { + const s3 = { + uploadBase64Image: jest + .fn() + .mockResolvedValueOnce('cars/product/new-0.jpg') + .mockRejectedValueOnce(new Error('upload unavailable')), + deleteObjects: jest.fn().mockResolvedValue(undefined), + } as any; + + await expect( + prepareProductImages(s3, 'cars', 'product', [ + { data: 'first', is_primary: true }, + { data: 'second', is_primary: false }, + ]), + ).rejects.toThrow('upload unavailable'); + + expect(s3.deleteObjects).toHaveBeenCalledWith([ + 'cars/product/new-0.jpg', + ]); + }); + + it('não chama S3 para uma compensação vazia', async () => { + const s3 = { deleteObjects: jest.fn() } as any; + + await cleanupPreparedProductImages(s3, []); + + expect(s3.deleteObjects).not.toHaveBeenCalled(); + }); + + it('não mascara a falha original se a limpeza compensatória também falhar', async () => { + const logSpy = jest.spyOn(Logger.prototype, 'error').mockImplementation(); + const s3 = { + uploadBase64Image: jest + .fn() + .mockResolvedValueOnce('cars/product/new-0.jpg') + .mockRejectedValueOnce(new Error('upload unavailable')), + deleteObjects: jest.fn().mockRejectedValue(new Error('cleanup unavailable')), + } as any; + + await expect( + prepareProductImages(s3, 'cars', 'product', [ + { data: 'first', is_primary: true }, + { data: 'second', is_primary: false }, + ]), + ).rejects.toThrow('upload unavailable'); + logSpy.mockRestore(); + }); + + it('gera chaves distintas para preparações concorrentes mesmo no mesmo milissegundo', async () => { + const dateSpy = jest.spyOn(Date, 'now').mockReturnValue(123456789); + const uploadedKeys: string[] = []; + const s3 = { + uploadBase64Image: jest.fn(async (_data: string, key: string) => { + uploadedKeys.push(key); + return key; + }), + deleteObjects: jest.fn(), + } as any; + + await Promise.all([ + prepareProductImages(s3, 'cars', 'same-product', [ + { data: 'first', is_primary: true }, + ]), + prepareProductImages(s3, 'cars', 'same-product', [ + { data: 'second', is_primary: true }, + ]), + ]); + + expect(new Set(uploadedKeys).size).toBe(2); + dateSpy.mockRestore(); + }); +}); diff --git a/backend/src/features/products/product-image-preparation.ts b/backend/src/features/products/product-image-preparation.ts new file mode 100644 index 00000000..d9dd905c --- /dev/null +++ b/backend/src/features/products/product-image-preparation.ts @@ -0,0 +1,56 @@ +import { S3Service } from 'src/aws/s3.service'; +import { Logger } from '@nestjs/common'; +import { randomUUID } from 'node:crypto'; + +const logger = new Logger('ProductImagePreparation'); + +export type ProductImageInput = { + data: string; + is_primary: boolean; +}; + +export type PreparedProductImage = { + image_url: string; + is_primary: boolean; +}; + +export async function prepareProductImages( + s3Service: S3Service, + prefix: string, + productId: string, + images: ProductImageInput[] = [], +): Promise { + const prepared: PreparedProductImage[] = []; + try { + for (let index = 0; index < images.length; index += 1) { + const key = `${prefix}/${productId}/${randomUUID()}-${index}.jpg`; + const imageUrl = await s3Service.uploadBase64Image( + images[index].data, + key, + ); + prepared.push({ + image_url: imageUrl, + is_primary: images[index].is_primary, + }); + } + return prepared; + } catch (error) { + await cleanupPreparedProductImages(s3Service, prepared); + throw error; + } +} + +export async function cleanupPreparedProductImages( + s3Service: S3Service, + prepared: PreparedProductImage[], +): Promise { + if (prepared.length === 0) return; + try { + await s3Service.deleteObjects(prepared.map((image) => image.image_url)); + } catch (error) { + logger.error( + `Falha ao compensar ${prepared.length} upload(s) de produto`, + error instanceof Error ? error.stack : undefined, + ); + } +} diff --git a/backend/src/features/products/product-monetary-lock.spec.ts b/backend/src/features/products/product-monetary-lock.spec.ts index 8b2680c1..2f59c613 100644 --- a/backend/src/features/products/product-monetary-lock.spec.ts +++ b/backend/src/features/products/product-monetary-lock.spec.ts @@ -44,7 +44,7 @@ describe('assertProductMonetaryFieldsUnlocked', () => { 'Valor e moeda não podem ser alterados enquanto o produto estiver em negociação.', }); expect(prisma.process.findFirst).toHaveBeenCalledWith({ - where: { car_id: 'car-1', status: ProcessStatus.NEGOTIATION }, + where: { car_id: 'car-1', status: ProcessStatus.NEGOTIATION, removed_at: null }, select: { id: true }, }); }); @@ -89,6 +89,7 @@ describe('assertProductMonetaryFieldsUnlocked', () => { where: { [foreignKey]: 'car-1', status: ProcessStatus.NEGOTIATION, + removed_at: null, }, select: { id: true }, }); diff --git a/backend/src/features/products/product-monetary-lock.ts b/backend/src/features/products/product-monetary-lock.ts index 6bbc9dc4..2a9917db 100644 --- a/backend/src/features/products/product-monetary-lock.ts +++ b/backend/src/features/products/product-monetary-lock.ts @@ -106,7 +106,11 @@ export async function assertProductMonetaryFieldsUnlocked( const foreignKey = PROCESS_FOREIGN_KEY_BY_TYPE[input.productType]; const activeProcess = await prisma.process.findFirst({ - where: { [foreignKey]: input.productId, status: ProcessStatus.NEGOTIATION }, + where: { + [foreignKey]: input.productId, + status: ProcessStatus.NEGOTIATION, + removed_at: null, + }, select: { id: true }, }); @@ -120,10 +124,10 @@ export async function assertProductMonetaryFieldsUnlocked( } export async function updateProductWithMonetaryLock( - prisma: PrismaService, + prisma: PrismaService | Prisma.TransactionClient, input: ProductMonetaryUpdateInput, ): Promise { - return prisma.$transaction(async (tx) => { + const update = async (tx: Prisma.TransactionClient) => { await acquireProductMonetaryLock(tx, input); const delegateName = PRODUCT_DELEGATE_BY_TYPE[input.productType]; @@ -152,5 +156,10 @@ export async function updateProductWithMonetaryLock( where: { id: input.productId }, data: input.data, }); - }); + }; + + if ('$transaction' in prisma) { + return prisma.$transaction(update); + } + return update(prisma); } diff --git a/backend/src/features/products/product-services-update-errors.spec.ts b/backend/src/features/products/product-services-update-errors.spec.ts new file mode 100644 index 00000000..c7f930ae --- /dev/null +++ b/backend/src/features/products/product-services-update-errors.spec.ts @@ -0,0 +1,59 @@ +import { ConflictException, NotFoundException } from '@nestjs/common'; +import { Prisma, ProductCurrency } from '@prisma/client'; +import { CarsService } from '../cars/cars.service'; +import { BoatsService } from '../boats/boats.service'; +import { AircraftsService } from '../aircrafts/aircrafts.service'; + +type ServiceFactory = (prisma: any) => { + update(id: string, dto: any): Promise; +}; + +const services: Array<[string, string, ServiceFactory]> = [ + ['carro', 'car', (prisma) => new CarsService(prisma, {} as any)], + ['barco', 'boat', (prisma) => new BoatsService(prisma, {} as any)], + ['aeronave', 'aircraft', (prisma) => new AircraftsService(prisma, {} as any)], +]; + +describe.each(services)('%s — preserva erros HTTP no update', (_label, delegateName, factory) => { + const productId = '11111111-1111-4111-8111-111111111111'; + + function prismaWith(currentProduct: unknown, activeProcess: unknown) { + const delegate = { + findUnique: jest.fn().mockResolvedValue(currentProduct), + update: jest.fn(), + }; + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + [delegateName]: delegate, + process: { findFirst: jest.fn().mockResolvedValue(activeProcess) }, + }; + return { + ...tx, + $transaction: jest.fn(async (callback: any) => callback(tx)), + }; + } + + it('mantém NotFoundException em vez de converter para 500', async () => { + const service = factory(prismaWith(null, null)); + + await expect(service.update(productId, { modelo: 'Novo' })).rejects.toBeInstanceOf( + NotFoundException, + ); + }); + + it('mantém ConflictException da trava monetária em vez de converter para 500', async () => { + const prisma = prismaWith( + { + id: productId, + valor: new Prisma.Decimal('100'), + currency: ProductCurrency.BRL, + }, + { id: 'process-1' }, + ); + const service = factory(prisma); + + await expect(service.update(productId, { valor: 200 })).rejects.toBeInstanceOf( + ConflictException, + ); + }); +}); diff --git a/backend/src/features/products/public-catalog-projection.spec.ts b/backend/src/features/products/public-catalog-projection.spec.ts new file mode 100644 index 00000000..5e1d7765 --- /dev/null +++ b/backend/src/features/products/public-catalog-projection.spec.ts @@ -0,0 +1,211 @@ +import { Prisma } from '@prisma/client'; +import { AircraftsService } from '../aircrafts/aircrafts.service'; +import { BoatsService } from '../boats/boats.service'; +import { CarsService } from '../cars/cars.service'; + +const privateSpecialistFields = { + cpf: '11222333000181', + rg: '12345678901', + phone: '+5511999999999', + password_hash: 'private-password-hash', + bank: 'private-bank', + agency: '0001', + checking_account: 'private-account', + calendly_user_uri: 'https://api.calendly.com/users/private', + calendly_organization_uri: 'https://api.calendly.com/organizations/private', + calendly_connection: { + access_token_encrypted: 'private-access-token', + refresh_token_encrypted: 'private-refresh-token', + webhook_uri: 'https://api.calendly.com/webhooks/private', + }, +}; + +const specialist = { + id: '22222222-2222-4222-8222-222222222222', + name: 'Ana', + surname: 'Silva', + email: 'ana.private@example.test', + ...privateSpecialistFields, +}; + +const images = [ + { + id: 1, + product_type: 'CAR', + image_url: 'public-s3-key', + is_primary: true, + created_at: new Date('2026-01-01T00:00:00.000Z'), + car_id: '11111111-1111-4111-8111-111111111111', + }, +]; + +const baseProduct = { + id: '11111111-1111-4111-8111-111111111111', + specialist_id: specialist.id, + is_active: true, + deactivated_at: null, + deactivated_by_sync_job_id: '33333333-3333-4333-8333-333333333333', + marca: 'Marca', + modelo: 'Modelo', + identificador: 'PUBLIC-1', + valor: new Prisma.Decimal('100000.00'), + currency: 'BRL', + estado: 'SP', + ano: 2026, + created_at: new Date('2026-01-01T00:00:00.000Z'), + updated_at: new Date('2026-01-02T00:00:00.000Z'), + images, + specialist, +}; + +function project(record: Record, select: Record) { + return Object.fromEntries( + Object.entries(select).map(([key, selection]) => { + const value = record[key]; + if ( + selection && + typeof selection === 'object' && + 'select' in selection && + value != null + ) { + if (Array.isArray(value)) { + return [key, value.map((item) => project(item, selection.select))]; + } + return [key, project(value, selection.select)]; + } + return [key, value]; + }), + ); +} + +function makePrisma(model: 'car' | 'boat' | 'aircraft', record: object) { + const findMany = jest.fn(async (args: any) => + args.select ? [project(record, args.select)] : [record], + ); + const findUnique = jest.fn(async (args: any) => + args.select ? project(record, args.select) : record, + ); + const delegate = { + findMany, + findUnique, + count: jest.fn().mockResolvedValue(1), + }; + return { + prisma: { + [model]: delegate, + $transaction: jest.fn(async (operations: Promise[]) => + Promise.all(operations), + ), + } as any, + findMany, + findUnique, + }; +} + +const forbiddenKeys = [ + 'cpf', + 'cnpj', + 'rg', + 'phone', + 'telefone', + 'email', + 'password_hash', + 'bank', + 'agency', + 'checking_account', + 'calendly_user_uri', + 'calendly_organization_uri', + 'calendly_connection', + 'access_token_encrypted', + 'refresh_token_encrypted', + 'webhook_uri', + 'deactivated_at', + 'deactivated_by_sync_job_id', +]; + +function expectPublicPayload(payload: unknown) { + const serialized = JSON.stringify(payload); + for (const key of forbiddenKeys) { + expect(serialized).not.toContain(`"${key}"`); + } + expect(serialized).not.toContain('private-'); +} + +describe.each([ + { + label: 'cars', + model: 'car' as const, + record: { ...baseProduct, descricao: 'Descrição', images }, + makeService: (prisma: any, s3: any) => new CarsService(prisma, s3), + list: (service: CarsService) => + service.getAllCars({ page: 1, perPage: 20, appliedFilters: {} }), + detail: (service: CarsService) => service.findOne(baseProduct.id), + }, + { + label: 'boats', + model: 'boat' as const, + record: { + ...baseProduct, + descricao_completa: 'Descrição', + images: images.map((image) => ({ + ...image, + product_type: 'BOAT', + car_id: undefined, + boat_id: baseProduct.id, + })), + }, + makeService: (prisma: any, s3: any) => new BoatsService(prisma, s3), + list: (service: BoatsService) => + service.getAllBoats({ page: 1, perPage: 20, appliedFilters: {} }), + detail: (service: BoatsService) => service.findOne(baseProduct.id), + }, + { + label: 'aircrafts', + model: 'aircraft' as const, + record: { + ...baseProduct, + descricao: 'Descrição', + images: images.map((image) => ({ + ...image, + product_type: 'AIRCRAFT', + car_id: undefined, + aircraft_id: baseProduct.id, + })), + }, + makeService: (prisma: any, s3: any) => new AircraftsService(prisma, s3), + list: (service: AircraftsService) => + service.getAllAircrafts({ page: 1, perPage: 20, appliedFilters: {} }), + detail: (service: AircraftsService) => service.findOne(baseProduct.id), + }, +])('$label public catalog projection', (scenario) => { + const s3 = { + getSignedUrl: jest.fn(async (key: string) => `https://cdn.test/${key}`), + }; + + it('uses a default-deny projection and exposes only the public specialist identity in list responses', async () => { + const { prisma, findMany } = makePrisma(scenario.model, scenario.record); + const service = scenario.makeService(prisma, s3) as any; + + const result = await scenario.list(service); + + expect(findMany.mock.calls[0][0]).toHaveProperty('select'); + expect(findMany.mock.calls[0][0]).not.toHaveProperty('include'); + expect(result.data[0].specialist).toEqual({ + id: specialist.id, + name: specialist.name, + surname: specialist.surname, + }); + expectPublicPayload(result.data[0]); + }); + + it('uses a default-deny projection for the public detail response', async () => { + const { prisma, findUnique } = makePrisma(scenario.model, scenario.record); + const service = scenario.makeService(prisma, s3) as any; + + const result = await scenario.detail(service); + + expect(findUnique.mock.calls[0][0]).toHaveProperty('select'); + expect(findUnique.mock.calls[0][0]).not.toHaveProperty('include'); + expectPublicPayload(result); + }); +}); diff --git a/backend/src/features/proposals/entities/proposal.entity.ts b/backend/src/features/proposals/entities/proposal.entity.ts index b977459f..9860a96c 100644 --- a/backend/src/features/proposals/entities/proposal.entity.ts +++ b/backend/src/features/proposals/entities/proposal.entity.ts @@ -29,6 +29,11 @@ export class ProposalResponseEntity { surname: string; role: UserRole; }; + executed_by?: { + id: string; + role: UserRole; + name: string | null; + }; } /** diff --git a/backend/src/features/proposals/proposals.controller.ts b/backend/src/features/proposals/proposals.controller.ts index af2ed477..55ca0159 100644 --- a/backend/src/features/proposals/proposals.controller.ts +++ b/backend/src/features/proposals/proposals.controller.ts @@ -9,10 +9,14 @@ import { Request, HttpStatus, Logger, + Query, + Optional, } from '@nestjs/common'; import { ProposalsService } from './proposals.service'; import { CreateProposalDto, RespondProposalDto } from './dto'; import { AuthGuard } from 'src/auth/auth.guard'; +import { UserRole } from '@prisma/client'; +import { ActorContextService } from 'src/shared/actor-context/actor-context.service'; /** * ProposalsController @@ -33,7 +37,20 @@ import { AuthGuard } from 'src/auth/auth.guard'; export class ProposalsController { private readonly logger = new Logger(ProposalsController.name); - constructor(private proposalsService: ProposalsService) {} + constructor( + private proposalsService: ProposalsService, + @Optional() private readonly actorContextService?: ActorContextService, + ) {} + + private async resolveContext(user: any, targetSpecialistId?: string) { + if ( + !this.actorContextService || + (user?.role !== UserRole.ADMIN && user?.role !== UserRole.SPECIALIST) + ) { + return undefined; + } + return this.actorContextService.resolve(user, targetSpecialistId); + } /** * POST /api/proposals @@ -55,13 +72,18 @@ export class ProposalsController { * - 404 Not Found: Processo não encontrado */ @Post() - async create(@Body() dto: CreateProposalDto, @Request() req: any) { + async create( + @Body() dto: CreateProposalDto, + @Request() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, + ) { const userId = req.user.id; this.logger.log( `[POST /proposals] Criando proposta para processo ${dto.process_id}`, ); - const proposal = await this.proposalsService.create(dto, userId); + const context = await this.resolveContext(req.user, targetSpecialistId); + const proposal = await this.proposalsService.create(dto, userId, context); return { success: true, @@ -85,13 +107,19 @@ export class ProposalsController { async getByProcess( @Param('processId') processId: string, @Request() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ) { const userId = req.user.id; this.logger.log( `[GET /processes/${processId}/proposals] Listando propostas`, ); - const result = await this.proposalsService.getByProcess(processId, userId); + const context = await this.resolveContext(req.user, targetSpecialistId); + const result = await this.proposalsService.getByProcess( + processId, + userId, + context, + ); return { success: true, @@ -113,11 +141,16 @@ export class ProposalsController { * - 404 Not Found: Proposta não encontrada */ @Get(':id') - async getById(@Param('id') id: string, @Request() req: any) { + async getById( + @Param('id') id: string, + @Request() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, + ) { const userId = req.user.id; this.logger.log(`[GET /proposals/${id}] Buscando proposta`); - const proposal = await this.proposalsService.getById(id, userId); + const context = await this.resolveContext(req.user, targetSpecialistId); + const proposal = await this.proposalsService.getById(id, userId, context); return { success: true, @@ -146,11 +179,18 @@ export class ProposalsController { @Param('id') id: string, @Body() dto: RespondProposalDto, @Request() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ) { const userId = req.user.id; this.logger.log(`[PATCH /proposals/${id}/accept] Aceitando proposta`); - const proposal = await this.proposalsService.accept(id, userId, dto); + const context = await this.resolveContext(req.user, targetSpecialistId); + const proposal = await this.proposalsService.accept( + id, + userId, + dto, + context, + ); return { success: true, @@ -180,11 +220,18 @@ export class ProposalsController { @Param('id') id: string, @Body() dto: RespondProposalDto, @Request() req: any, + @Query('target_specialist_id') targetSpecialistId?: string, ) { const userId = req.user.id; this.logger.log(`[PATCH /proposals/${id}/reject] Rejeitando proposta`); - const proposal = await this.proposalsService.reject(id, userId, dto); + const context = await this.resolveContext(req.user, targetSpecialistId); + const proposal = await this.proposalsService.reject( + id, + userId, + dto, + context, + ); return { success: true, diff --git a/backend/src/features/proposals/proposals.service.spec.ts b/backend/src/features/proposals/proposals.service.spec.ts index 61fbb81a..2443abda 100644 --- a/backend/src/features/proposals/proposals.service.spec.ts +++ b/backend/src/features/proposals/proposals.service.spec.ts @@ -146,13 +146,23 @@ function setup() { sendProposalRejectedEmail: jest.fn().mockResolvedValue(undefined), sendProcessStatusChangedEmail: jest.fn().mockResolvedValue(undefined), } as any; - const service = new ProposalsService(prisma, settings, notifications); + const audit = { + record: jest.fn().mockResolvedValue(undefined), + listProposalCreators: jest.fn().mockResolvedValue([]), + } as any; + const service = new ProposalsService( + prisma, + settings, + notifications, + audit, + ); return { service, prisma, settings, notifications, + audit, transactionProposalCreate, transactionProposalUpdateMany, transactionProcessFindUnique, @@ -202,6 +212,43 @@ describe('ProposalsService — snapshot e mínimo dinâmico', () => { }); }); + it('mostra o executor administrativo sem trocar a autoria comercial', async () => { + const { service, prisma, audit } = setup(); + prisma.process.findUnique.mockResolvedValue( + processFixture({ + proposals: [ + proposalFixture({ + proposed_by_id: 'specialist-1', + proposed_to_id: 'client-1', + proposed_by: { + id: 'specialist-1', + name: 'Especialista', + surname: 'Alfa', + role: UserRole.SPECIALIST, + }, + }), + ], + }), + ); + audit.listProposalCreators.mockResolvedValue([ + { + proposalId: 'proposal-1', + actor: { id: 'admin-1', role: UserRole.ADMIN, name: 'Admin Validação' }, + }, + ]); + + const response = await service.getByProcess('process-1', 'specialist-1'); + + expect(response.proposals[0]).toMatchObject({ + proposed_by: { id: 'specialist-1' }, + executed_by: { id: 'admin-1', role: UserRole.ADMIN }, + }); + expect(audit.listProposalCreators).toHaveBeenCalledWith( + 'process-1', + 'specialist-1', + ); + }); + it('exposes the cent-rounded minimum used by proposal creation', async () => { const { service, prisma, settings } = setup(); settings.getMinimumProposalPercentage.mockResolvedValue(0.8); @@ -363,6 +410,62 @@ describe('ProposalsService — snapshot e mínimo dinâmico', () => { ); }); + it('não cria uma segunda PENDING sem responder a pendente identificada', async () => { + const { service, prisma, transactionProposalCreate } = setup(); + prisma.process.findUnique.mockResolvedValue( + processFixture({ proposals: [proposalFixture()] }), + ); + + await expect( + service.create( + { process_id: 'process-1', proposed_value: 90000 }, + 'specialist-1', + ), + ).rejects.toMatchObject({ + response: expect.objectContaining({ + error: expect.objectContaining({ + code: 'PENDING_PROPOSAL_MUST_BE_ANSWERED', + }), + }), + }); + expect(transactionProposalCreate).not.toHaveBeenCalled(); + }); + + it('mantém SPECIALIST como parte comercial e ADMIN como executor auditado', async () => { + const { service, prisma, transactionProposalCreate, audit } = setup(); + prisma.process.findUnique.mockResolvedValue(processFixture()); + const context = { + actorId: 'admin-1', + actorRole: UserRole.ADMIN, + specialistId: 'specialist-1', + delegated: true, + specialist: {} as any, + }; + + await service.create( + { process_id: 'process-1', proposed_value: 90000 }, + 'admin-1', + context, + ); + + expect(transactionProposalCreate).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + proposed_by_id: 'specialist-1', + proposed_to_id: 'client-1', + }), + }), + ); + expect(audit.record).toHaveBeenCalledWith( + expect.objectContaining({ + context, + action: 'PROPOSAL_CREATE', + resourceType: 'PROPOSAL', + }), + expect.anything(), + ); + }); + it('rejects a counterproposal that references another process', async () => { const { service, prisma, transactionProposalCreate } = setup(); prisma.process.findUnique.mockResolvedValue(processFixture()); @@ -502,6 +605,7 @@ describe('ProposalsService — snapshot e mínimo dinâmico', () => { ).toEqual({ select: { status: true, + removed_at: true, client_id: true, specialist_id: true, product_type: true, diff --git a/backend/src/features/proposals/proposals.service.ts b/backend/src/features/proposals/proposals.service.ts index 6d22e3f0..feb40ad8 100644 --- a/backend/src/features/proposals/proposals.service.ts +++ b/backend/src/features/proposals/proposals.service.ts @@ -5,6 +5,7 @@ import { NotFoundException, ForbiddenException, Logger, + Optional, } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { CreateProposalDto, RespondProposalDto } from './dto'; @@ -17,6 +18,8 @@ import { SettingsService } from 'src/features/settings/settings.service'; import { NotificationService } from 'src/features/notifications/notification.service'; import { requireNegotiationSnapshot } from 'src/features/processes/negotiation-snapshot'; import { calculateMinimumProposalValue } from './proposal-money'; +import { ActorContext } from 'src/shared/actor-context/actor-context.service'; +import { DelegatedActionAuditService } from 'src/shared/actor-context/delegated-action-audit.service'; /** * ProposalsService @@ -45,6 +48,8 @@ export class ProposalsService { private prisma: PrismaService, private settingsService: SettingsService, private notificationService: NotificationService, + @Optional() + private readonly delegatedAudit?: DelegatedActionAuditService, ) {} private async lockProposalProcess(tx: any, processId: string): Promise { @@ -88,6 +93,7 @@ export class ProposalsService { async create( dto: CreateProposalDto, userId: string, + context?: ActorContext, ): Promise { this.logger.log( `[create] Criando proposta para processo ${dto.process_id} por usuário ${userId}`, @@ -139,7 +145,7 @@ export class ProposalsService { }, }); - if (!process) { + if (!process || process.removed_at) { this.logger.warn( `[create] Processo ${dto.process_id} não encontrado`, ); @@ -172,9 +178,16 @@ export class ProposalsService { } // 3. Validar que usuário é participante do processo (cliente, especialista ou consultor do cliente) - const isClient = process.client_id === userId; - const isSpecialist = process.specialist_id === userId; - const isConsultantOfClient = process.client?.consultant_id === userId; + const partyUserId = context?.specialistId ?? userId; + if (context && process.specialist_id !== context.specialistId) { + throw new ForbiddenException( + 'O processo não pertence ao especialista representado.', + ); + } + const isClient = process.client_id === partyUserId; + const isSpecialist = process.specialist_id === partyUserId; + const isConsultantOfClient = + !context && process.client?.consultant_id === userId; const isOnClientSide = isClient || isConsultantOfClient; if (!isClient && !isSpecialist && !isConsultantOfClient) { @@ -194,6 +207,17 @@ export class ProposalsService { // 4. Validar alternância por lado (cliente/consultor vs especialista) — não pode dois envios seguidos do mesmo lado const lastProposal = process.proposals[0]; if (lastProposal && lastProposal.status === ProposalStatus.PENDING) { + if (dto.counter_to_id !== lastProposal.id) { + throw new BadRequestException({ + success: false, + error: { + code: 'PENDING_PROPOSAL_MUST_BE_ANSWERED', + message: + 'Responda explicitamente a proposta pendente antes de criar outra.', + details: { pending_proposal_id: lastProposal.id }, + }, + }); + } const lastProposerSide = lastProposal.proposed_by.id === process.specialist_id ? 'SPECIALIST' @@ -315,7 +339,7 @@ export class ProposalsService { }); } - if (originalProposal.proposed_to_id !== userId) { + if (originalProposal.proposed_to_id !== partyUserId) { throw new ForbiddenException({ success: false, error: { @@ -338,7 +362,7 @@ export class ProposalsService { where: { id: dto.counter_to_id, process_id: dto.process_id, - proposed_to_id: userId, + proposed_to_id: partyUserId, status: ProposalStatus.PENDING, }, data: { status: ProposalStatus.COUNTERED }, @@ -362,7 +386,7 @@ export class ProposalsService { const proposal = await tx.negotiationProposal.create({ data: { process_id: dto.process_id, - proposed_by_id: userId, + proposed_by_id: partyUserId, proposed_to_id: proposedToId, proposed_value: dto.proposed_value, message: dto.message, @@ -379,6 +403,25 @@ export class ProposalsService { }, }); + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: dto.counter_to_id + ? 'PROPOSAL_COUNTER' + : 'PROPOSAL_CREATE', + resourceType: 'PROPOSAL', + resourceId: proposal.id, + metadata: { + processId: dto.process_id, + commercialSide: 'SPECIALIST', + proposedValue: dto.proposed_value, + }, + }, + tx, + ); + } + return { proposal, process, currency, productValue, isOnClientSide }; }); @@ -432,6 +475,7 @@ export class ProposalsService { async getByProcess( processId: string, userId: string, + context?: ActorContext, ): Promise { this.logger.log( `[getByProcess] Buscando propostas do processo ${processId}`, @@ -486,7 +530,7 @@ export class ProposalsService { }, }); - if (!process) { + if (!process || process.removed_at) { throw new NotFoundException({ success: false, error: { @@ -498,10 +542,11 @@ export class ProposalsService { } // 2. Validar que usuário é participante (cliente, especialista ou consultor do cliente) + const partyUserId = context?.specialistId ?? userId; const isParticipant = - process.client_id === userId || - process.specialist_id === userId || - process.client?.consultant_id === userId; + process.client_id === partyUserId || + process.specialist_id === partyUserId || + (!context && process.client?.consultant_id === userId); if (!isParticipant) { throw new ForbiddenException({ @@ -555,9 +600,10 @@ export class ProposalsService { // 5. Verificar se usuário pode criar proposta (lógica por lado) const userSide: 'CLIENT' | 'SPECIALIST' | null = - process.client_id === userId || process.client?.consultant_id === userId + process.client_id === partyUserId || + (!context && process.client?.consultant_id === userId) ? 'CLIENT' - : process.specialist_id === userId + : process.specialist_id === partyUserId ? 'SPECIALIST' : null; @@ -573,8 +619,24 @@ export class ProposalsService { process.status === ProcessStatus.NEGOTIATION && (!lastPendingProposal || lastPendingTargetSide === userSide); + const proposalExecutors = + this.delegatedAudit && process.proposals.length > 0 + ? await this.delegatedAudit.listProposalCreators( + process.id, + process.specialist_id, + ) + : []; + const executorByProposal = new Map( + proposalExecutors.map(({ proposalId, actor }) => [proposalId, actor]), + ); + return { - proposals: process.proposals.map((p) => this.mapToResponseEntity(p)), + proposals: process.proposals.map((p) => ({ + ...this.mapToResponseEntity(p), + ...(executorByProposal.has(p.id) + ? { executed_by: executorByProposal.get(p.id) } + : {}), + })), process: { id: process.id, status: process.status, @@ -620,6 +682,7 @@ export class ProposalsService { proposalId: string, userId: string, dto?: RespondProposalDto, + context?: ActorContext, ): Promise { this.logger.log(`[accept] Aceitando proposta ${proposalId}`); @@ -629,6 +692,7 @@ export class ProposalsService { proposalId, userId, tx, + context, ); const { currency } = requireNegotiationSnapshot(proposal.process); @@ -637,7 +701,7 @@ export class ProposalsService { where: { id: proposalId, status: ProposalStatus.PENDING, - process: { status: ProcessStatus.NEGOTIATION }, + process: { status: ProcessStatus.NEGOTIATION, removed_at: null }, }, data: { status: ProposalStatus.ACCEPTED }, }); @@ -650,6 +714,7 @@ export class ProposalsService { where: { id: proposal.process_id, status: ProcessStatus.NEGOTIATION, + removed_at: null, accepted_proposal_id: null, }, data: { @@ -668,6 +733,18 @@ export class ProposalsService { changed_by: userId, }, }); + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'PROPOSAL_ACCEPT', + resourceType: 'PROPOSAL', + resourceId: proposalId, + metadata: { processId: proposal.process_id }, + }, + tx, + ); + } const updated = await tx.negotiationProposal.findUniqueOrThrow({ where: { id: proposalId }, @@ -737,7 +814,9 @@ export class ProposalsService { ].filter((recipient) => Boolean(recipient.email)); const changedByName = - `${proposal.proposed_to.name} ${proposal.proposed_to.surname || ''}`.trim(); + context?.delegated && context.actor + ? `${context.actor.name} ${context.actor.surname}`.trim() + : `${proposal.proposed_to.name} ${proposal.proposed_to.surname || ''}`.trim(); Promise.allSettled( recipients.map((recipient) => @@ -777,6 +856,7 @@ export class ProposalsService { proposalId: string, userId: string, dto?: RespondProposalDto, + context?: ActorContext, ): Promise { this.logger.log(`[reject] Rejeitando proposta ${proposalId}`); @@ -786,6 +866,7 @@ export class ProposalsService { proposalId, userId, tx, + context, ); const { currency } = requireNegotiationSnapshot(proposal.process); @@ -793,7 +874,7 @@ export class ProposalsService { where: { id: proposalId, status: ProposalStatus.PENDING, - process: { status: ProcessStatus.NEGOTIATION }, + process: { status: ProcessStatus.NEGOTIATION, removed_at: null }, }, data: { status: ProposalStatus.REJECTED, @@ -803,6 +884,21 @@ export class ProposalsService { if (proposalClaim.count !== 1) { throw this.proposalResponseConflict(proposalId); } + if (context && this.delegatedAudit) { + await this.delegatedAudit.record( + { + context, + action: 'PROPOSAL_REJECT', + resourceType: 'PROPOSAL', + resourceId: proposalId, + metadata: { + processId: proposal.process_id, + reason: dto?.message ?? null, + }, + }, + tx, + ); + } const updated = await tx.negotiationProposal.findUniqueOrThrow({ where: { id: proposalId }, @@ -857,6 +953,7 @@ export class ProposalsService { async getById( proposalId: string, userId: string, + context?: ActorContext, ): Promise { const proposal = await this.prisma.negotiationProposal.findUnique({ where: { id: proposalId }, @@ -865,6 +962,7 @@ export class ProposalsService { select: { client_id: true, specialist_id: true, + removed_at: true, client: { select: { consultant_id: true } }, }, }, @@ -877,7 +975,7 @@ export class ProposalsService { }, }); - if (!proposal) { + if (!proposal || proposal.process.removed_at) { throw new NotFoundException({ success: false, error: { @@ -889,10 +987,11 @@ export class ProposalsService { } // Validar participação (cliente, especialista ou consultor do cliente) + const partyUserId = context?.specialistId ?? userId; const isParticipant = - proposal.process.client_id === userId || - proposal.process.specialist_id === userId || - proposal.process.client?.consultant_id === userId; + proposal.process.client_id === partyUserId || + proposal.process.specialist_id === partyUserId || + (!context && proposal.process.client?.consultant_id === userId); if (!isParticipant) { throw new ForbiddenException({ @@ -915,6 +1014,7 @@ export class ProposalsService { proposalId: string, userId: string, client: PrismaService | Prisma.TransactionClient = this.prisma, + context?: ActorContext, ): Promise { const proposal = await client.negotiationProposal.findUnique({ where: { id: proposalId }, @@ -922,6 +1022,7 @@ export class ProposalsService { process: { select: { status: true, + removed_at: true, client_id: true, specialist_id: true, product_type: true, @@ -942,7 +1043,7 @@ export class ProposalsService { }, }); - if (!proposal) { + if (!proposal || proposal.process.removed_at) { throw new NotFoundException({ success: false, error: { @@ -954,8 +1055,15 @@ export class ProposalsService { } // Validar destinatário — usuário direto ou consultor do cliente quando a proposta é para o cliente - const isDirectTarget = proposal.proposed_to_id === userId; + if (context && proposal.process.specialist_id !== context.specialistId) { + throw new ForbiddenException( + 'A proposta não pertence ao especialista representado.', + ); + } + const partyUserId = context?.specialistId ?? userId; + const isDirectTarget = proposal.proposed_to_id === partyUserId; const isConsultantOfTargetClient = + !context && proposal.process.client?.consultant_id === userId && proposal.proposed_to_id === proposal.process.client_id; diff --git a/backend/src/features/specialists/specialists.controller.spec.ts b/backend/src/features/specialists/specialists.controller.spec.ts new file mode 100644 index 00000000..8fe4abef --- /dev/null +++ b/backend/src/features/specialists/specialists.controller.spec.ts @@ -0,0 +1,54 @@ +import { PATH_METADATA } from '@nestjs/common/constants'; +import { IS_PUBLIC_KEY } from 'src/shared/decorators/public.decorator'; +import { SpecialistsController } from './specialists.controller'; + +describe('SpecialistsController public profile', () => { + it('protege a listagem administrativa com ADMIN', () => { + expect( + Reflect.getMetadata('roles', SpecialistsController.prototype.findAll), + ).toEqual(['ADMIN']); + expect( + Reflect.getMetadata( + IS_PUBLIC_KEY, + SpecialistsController.prototype.findAll, + ), + ).not.toBe(true); + }); + + it('protege o cadastro completo com ADMIN', () => { + expect( + Reflect.getMetadata('roles', SpecialistsController.prototype.findOne), + ).toEqual(['ADMIN']); + expect( + Reflect.getMetadata( + IS_PUBLIC_KEY, + SpecialistsController.prototype.findOne, + ), + ).not.toBe(true); + }); + + it('publica a rota dedicada antes da rota genérica', () => { + const prototype = SpecialistsController.prototype; + expect( + Reflect.getMetadata(PATH_METADATA, prototype.findPublicProfile), + ).toBe(':id/public-profile'); + expect( + Reflect.getMetadata(IS_PUBLIC_KEY, prototype.findPublicProfile), + ).toBe(true); + const methods = Object.getOwnPropertyNames(prototype); + expect(methods.indexOf('findPublicProfile')).toBeLessThan( + methods.indexOf('findOne'), + ); + }); + + it('encaminha o ID para a projeção segura', async () => { + const profile = { + id: 'specialist-1', + calendly_scheduling_available: false, + }; + const service = { findPublicProfile: jest.fn().mockResolvedValue(profile) }; + const controller = new SpecialistsController(service as any); + expect(await controller.findPublicProfile('specialist-1')).toBe(profile); + expect(service.findPublicProfile).toHaveBeenCalledWith('specialist-1'); + }); +}); diff --git a/backend/src/features/specialists/specialists.controller.ts b/backend/src/features/specialists/specialists.controller.ts index 449a4e7a..c8711e04 100644 --- a/backend/src/features/specialists/specialists.controller.ts +++ b/backend/src/features/specialists/specialists.controller.ts @@ -15,6 +15,7 @@ import { UpdateSpecialistDto } from './dto/update-specialist.dto'; import { InviteSpecialistDto } from './dto/invite-specialist.dto'; import { Roles } from 'src/shared/decorators/roles.decorator'; import { UserRole } from '@prisma/client'; +import { Public } from 'src/shared/decorators/public.decorator'; /** * Define a rota base para este controlador. @@ -30,6 +31,7 @@ export class SpecialistsController { // ROTAS CRUD PARA ESPECIALISTAS // Rota para buscar todos os especialistas. + @Roles(UserRole.ADMIN) @Get() findAll() { return this.specialistsService.findAll(); @@ -61,7 +63,14 @@ export class SpecialistsController { }; } + @Public() + @Get(':id/public-profile') + findPublicProfile(@Param('id') id: string) { + return this.specialistsService.findPublicProfile(id); + } + // Rota para buscar um único especialista pelo seu ID. + @Roles(UserRole.ADMIN) @Get(':id') findOne(@Param('id') id: string) { return this.specialistsService.findOne(id); diff --git a/backend/src/features/specialists/specialists.service.spec.ts b/backend/src/features/specialists/specialists.service.spec.ts index f620ed04..5cba96a2 100644 --- a/backend/src/features/specialists/specialists.service.spec.ts +++ b/backend/src/features/specialists/specialists.service.spec.ts @@ -3,6 +3,9 @@ import { SpecialistsService } from './specialists.service'; jest.mock('bcrypt', () => ({ hash: jest.fn().mockResolvedValue('hashed-password'), })); +jest.mock('src/auth/constants', () => ({ + jwtConstants: { referral: 'test-referral-secret' }, +})); describe('SpecialistsService.inviteSpecialist', () => { it('assina a comissão definida pelo administrador', async () => { @@ -39,12 +42,17 @@ describe('SpecialistsService.inviteSpecialist', () => { }); describe('SpecialistsService.findAll', () => { - it('preserva null e zero como estados distintos', async () => { + it('preserva null, zero e Decimal de comissão na listagem administrativa', async () => { const prisma = { user: { findMany: jest.fn().mockResolvedValue([ - { id: 'legacy', commission_rate: null }, - { id: 'zero', commission_rate: 0 }, + { id: 'legacy', commission_rate: null, company: null }, + { id: 'zero', commission_rate: 0, company: null }, + { + id: 'decimal', + commission_rate: { toString: () => '12.5' }, + company: { id: 'company-1' }, + }, ]), }, } as any; @@ -57,7 +65,12 @@ describe('SpecialistsService.findAll', () => { const result = await service.findAll(); - expect(result.map((item) => item.commission_rate)).toEqual([null, 0]); + expect(result.map((item) => item.commission_rate)).toEqual([null, 0, 12.5]); + expect(result[2].company).toEqual({ id: 'company-1' }); + expect(prisma.user.findMany).toHaveBeenCalledWith({ + where: { role: 'SPECIALIST' }, + include: { company: true }, + }); }); }); @@ -78,6 +91,112 @@ describe('SpecialistsService.findAllGroupedByCategory', () => { const select = prisma.user.findMany.mock.calls[0][0].select; expect(select).not.toHaveProperty('commission_rate'); }); + + it('usa a mesma allowlist e serializa capacidade nas categorias', async () => { + const prisma = { + user: { findMany: jest.fn().mockResolvedValue([publicSpecialist]) }, + } as any; + const service = new SpecialistsService( + prisma, + {} as any, + {} as any, + {} as any, + ); + expect(await service.findAllGroupedByCategory()).toEqual({ + CAR: [publicProfile], + BOAT: [], + AIRCRAFT: [], + }); + expect(prisma.user.findMany).toHaveBeenCalledWith({ + where: { role: 'SPECIALIST' }, + select: publicSelect, + }); + }); +}); + +const publicSelect = { + id: true, + name: true, + surname: true, + speciality: true, + calendly_url: true, + calendly_connection: { select: { is_active: true } }, +}; +const publicProfile = { + id: 'specialist-1', + name: 'Ana', + surname: 'Silva', + speciality: 'CAR', + calendly_url: 'https://calendly.com/ana/reuniao', + calendly_scheduling_available: true, +}; +const publicSpecialist = { + ...publicProfile, + calendly_connection: { is_active: true }, + cpf: 'private-cpf', + rg: 'private-rg', + password_hash: 'private-password', + commission_rate: 25, + bank: 'private-bank', + calendly_user_uri: 'private-uri', +}; + +describe('SpecialistsService.findPublicProfile', () => { + function makeService(record: unknown) { + const prisma = { + user: { findUnique: jest.fn().mockResolvedValue(record) }, + } as any; + return { + prisma, + service: new SpecialistsService(prisma, {} as any, {} as any, {} as any), + }; + } + + it('seleciona e retorna somente a allowlist pública', async () => { + const { service, prisma } = makeService(publicSpecialist); + expect(await service.findPublicProfile('specialist-1')).toEqual( + publicProfile, + ); + expect(prisma.user.findUnique).toHaveBeenCalledWith({ + where: { id: 'specialist-1', role: 'SPECIALIST' }, + select: publicSelect, + }); + expect(await service.findPublicProfile('specialist-1')).not.toHaveProperty( + 'email', + ); + }); + + it.each([null, { is_active: false }])( + 'desabilita capacidade sem conexão ativa %s', + async (calendly_connection) => { + const { service } = makeService({ + ...publicSpecialist, + calendly_connection, + }); + expect(await service.findPublicProfile('specialist-1')).toEqual({ + ...publicProfile, + calendly_scheduling_available: false, + }); + }, + ); + + it('desabilita capacidade com URL inválida', async () => { + const { service } = makeService({ + ...publicSpecialist, + calendly_url: 'https://evilcalendly.com/a', + }); + expect( + (await service.findPublicProfile('specialist-1')) + .calendly_scheduling_available, + ).toBe(false); + }); + + it('retorna 404 quando nenhum especialista corresponde ao ID', async () => { + const { service } = makeService(null); + await expect(service.findPublicProfile('missing')).rejects.toThrow( + 'Especialista não encontrado', + ); + }); }); describe('SpecialistsService.create', () => { @@ -95,9 +214,11 @@ describe('SpecialistsService.create', () => { const prisma = { user: { findUnique: jest.fn().mockResolvedValue(null), - create: jest.fn().mockImplementation(({ data }) => - Promise.resolve({ id: 'specialist-1', ...data }), - ), + create: jest + .fn() + .mockImplementation(({ data }) => + Promise.resolve({ id: 'specialist-1', ...data }), + ), }, } as any; const notifications = { @@ -115,15 +236,18 @@ describe('SpecialistsService.create', () => { }; } - it.each([0, 100])('persiste comissão obrigatória %s', async (commission_rate) => { - const { prisma, service } = makeService(); + it.each([0, 100])( + 'persiste comissão obrigatória %s', + async (commission_rate) => { + const { prisma, service } = makeService(); - await service.create({ ...base, commission_rate } as any); + await service.create({ ...base, commission_rate } as any); - expect(prisma.user.create).toHaveBeenCalledWith({ - data: expect.objectContaining({ commission_rate }), - }); - }); + expect(prisma.user.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ commission_rate }), + }); + }, + ); it.each([undefined, null, 12.345, 1e-7])( 'rejeita comissão inválida %s antes de persistir', diff --git a/backend/src/features/specialists/specialists.service.ts b/backend/src/features/specialists/specialists.service.ts index 7f64d5c0..7618561a 100644 --- a/backend/src/features/specialists/specialists.service.ts +++ b/backend/src/features/specialists/specialists.service.ts @@ -16,6 +16,41 @@ import { jwtConstants } from 'src/auth/constants'; import { NotificationService } from '../notifications/notification.service'; import { SpecialistInvitePayload } from '../../auth/types/specialist-invite-payload'; import { isValidCommissionRate } from '../../shared/validators/commission-rate.validator'; +import { isCalendlySchedulingAvailable } from '../../shared/utils/calendly-scheduling-capability'; + +const publicSpecialistSelect = { + id: true, + name: true, + surname: true, + speciality: true, + calendly_url: true, + calendly_connection: { select: { is_active: true } }, +} satisfies Prisma.UserSelect; + +type PublicSpecialistRecord = Prisma.UserGetPayload<{ + select: typeof publicSpecialistSelect; +}>; + +export type PublicSpecialistProfile = Pick< + PublicSpecialistRecord, + 'id' | 'name' | 'surname' | 'speciality' | 'calendly_url' +> & { calendly_scheduling_available: boolean }; + +function toPublicProfile( + specialist: PublicSpecialistRecord, +): PublicSpecialistProfile { + return { + id: specialist.id, + name: specialist.name, + surname: specialist.surname, + speciality: specialist.speciality, + calendly_url: specialist.calendly_url, + calendly_scheduling_available: isCalendlySchedulingAvailable({ + calendlyUrl: specialist.calendly_url, + connectionActive: specialist.calendly_connection?.is_active ?? false, + }), + }; +} @Injectable() export class SpecialistsService { @@ -80,6 +115,17 @@ export class SpecialistsService { return specialists.map((specialist) => this.toResponse(specialist)); } + async findPublicProfile(id: string): Promise { + const specialist = await this.prisma.user.findUnique({ + where: { id, role: 'SPECIALIST' }, + select: publicSpecialistSelect, + }); + if (!specialist) { + throw new NotFoundException('Especialista não encontrado'); + } + return toPublicProfile(specialist); + } + // Cria um novo especialista na base de dados. async create(data: CreateSpecialistDto) { if (!isValidCommissionRate(data.commission_rate)) { @@ -278,24 +324,16 @@ export class SpecialistsService { async findAllGroupedByCategory() { const specialists = await this.prisma.user.findMany({ where: { role: 'SPECIALIST' }, - select: { - id: true, - name: true, - surname: true, - email: true, - cpf: true, - rg: true, - speciality: true, - company_id: true, - calendly_url: true, - }, + select: publicSpecialistSelect, }); + const profiles = specialists.map(toPublicProfile); + // Agrupa os especialistas por categoria const grouped = { - CAR: specialists.filter((s) => s.speciality === 'CAR'), - BOAT: specialists.filter((s) => s.speciality === 'BOAT'), - AIRCRAFT: specialists.filter((s) => s.speciality === 'AIRCRAFT'), + CAR: profiles.filter((s) => s.speciality === 'CAR'), + BOAT: profiles.filter((s) => s.speciality === 'BOAT'), + AIRCRAFT: profiles.filter((s) => s.speciality === 'AIRCRAFT'), }; return grouped; diff --git a/backend/src/features/users/dto/update-user.dto.ts b/backend/src/features/users/dto/update-user.dto.ts index a6c6a3ae..edabb9ca 100644 --- a/backend/src/features/users/dto/update-user.dto.ts +++ b/backend/src/features/users/dto/update-user.dto.ts @@ -62,5 +62,5 @@ export class UpdateUserDto { @MaxLength(255, { message: 'URL do Calendly deve ter no máximo 255 caracteres', }) - calendly_url?: string; + calendly_url?: string | null; } diff --git a/backend/src/features/users/users.controller.spec.ts b/backend/src/features/users/users.controller.spec.ts new file mode 100644 index 00000000..0ded0bab --- /dev/null +++ b/backend/src/features/users/users.controller.spec.ts @@ -0,0 +1,108 @@ +import { ForbiddenException } from '@nestjs/common'; +import { GUARDS_METADATA } from '@nestjs/common/constants'; +import { UserRole } from '@prisma/client'; +import { AuthGuard } from 'src/auth/auth.guard'; +import { IS_PUBLIC_KEY } from 'src/shared/decorators/public.decorator'; +import { UsersController } from './users.controller'; + +const targetId = '11111111-1111-4111-8111-111111111111'; +const outsiderId = '22222222-2222-4222-8222-222222222222'; + +function setup() { + const service = { + getById: jest + .fn() + .mockResolvedValue({ id: targetId, phone: '11987654321' }), + update: jest.fn().mockResolvedValue({ id: targetId, name: 'Novo' }), + }; + return { service, controller: new UsersController(service as any) }; +} + +describe('UsersController private profile authorization', () => { + it('rejects editing another user before service access', async () => { + const { controller, service } = setup(); + await expect( + (controller.update as any)( + targetId, + { name: 'Novo' }, + { + user: { id: outsiderId, role: UserRole.CUSTOMER }, + }, + ), + ).rejects.toThrow(ForbiddenException); + expect(service.update).not.toHaveBeenCalled(); + }); + it('requires authentication on both profile routes', () => { + for (const method of [ + UsersController.prototype.getById, + UsersController.prototype.update, + ]) { + expect(Reflect.getMetadata(IS_PUBLIC_KEY, method)).not.toBe(true); + expect(Reflect.getMetadata(GUARDS_METADATA, method)).toContain(AuthGuard); + } + }); + + it.each([ + UserRole.CUSTOMER, + UserRole.SPECIALIST, + UserRole.CONSULTANT, + UserRole.OFFICE, + ])( + 'rejects reading and editing another user as %s before service access', + async (role) => { + const { controller, service } = setup(); + const request = { user: { id: outsiderId, role } }; + await expect( + (controller.getById as any)(targetId, request), + ).rejects.toThrow(ForbiddenException); + await expect( + (controller.update as any)(targetId, { name: 'Novo' }, request), + ).rejects.toThrow(ForbiddenException); + expect(service.getById).not.toHaveBeenCalled(); + expect(service.update).not.toHaveBeenCalled(); + }, + ); + + it.each([undefined, {}, { user: null }, { user: {} }])( + 'fails closed when the authenticated actor is missing: %p', + async (request) => { + const { controller, service } = setup(); + await expect( + (controller.getById as any)(targetId, request), + ).rejects.toThrow(ForbiddenException); + await expect( + (controller.update as any)(targetId, { name: 'Novo' }, request), + ).rejects.toThrow(ForbiddenException); + expect(service.getById).not.toHaveBeenCalled(); + expect(service.update).not.toHaveBeenCalled(); + }, + ); + + it.each([ + { id: targetId, role: UserRole.CUSTOMER }, + { id: targetId, role: UserRole.SPECIALIST }, + { id: outsiderId, role: UserRole.ADMIN }, + ])( + 'preserves private read/update response envelopes for %p', + async (user) => { + const { controller, service } = setup(); + const dto = { name: 'Novo' }; + await expect( + (controller.getById as any)(targetId, { user }), + ).resolves.toEqual({ + success: true, + message: 'Usuário obtido com sucesso', + data: { id: targetId, phone: '11987654321' }, + }); + await expect( + (controller.update as any)(targetId, dto, { user }), + ).resolves.toEqual({ + success: true, + message: 'Usuário atualizado com sucesso', + data: { id: targetId, name: 'Novo' }, + }); + expect(service.getById).toHaveBeenCalledWith(targetId); + expect(service.update).toHaveBeenCalledWith(targetId, dto); + }, + ); +}); diff --git a/backend/src/features/users/users.controller.ts b/backend/src/features/users/users.controller.ts index 1771ff50..d35c559c 100644 --- a/backend/src/features/users/users.controller.ts +++ b/backend/src/features/users/users.controller.ts @@ -7,17 +7,26 @@ import { Body, ParseUUIDPipe, UseGuards, + Req, + ForbiddenException, } from '@nestjs/common'; import { UsersService } from './users.service'; import { GetUsersDto } from './dto/get-users.dto'; import { UpdateUserDto } from './dto/update-user.dto'; import { AuthGuard } from 'src/auth/auth.guard'; -import { Public } from 'src/shared/decorators/public.decorator'; +import { UserRole } from '@prisma/client'; +import { UserEntity } from 'src/auth/entities/user.entity'; @Controller('users') export class UsersController { constructor(private readonly usersService: UsersService) {} + private assertSelfOrAdmin(targetId: string, actor?: UserEntity): void { + if (!actor?.id || (actor.id !== targetId && actor.role !== UserRole.ADMIN)) { + throw new ForbiddenException('Acesso não autorizado'); + } + } + /** * DESATIVADA — GET /api/users (listagem) * @@ -32,7 +41,7 @@ export class UsersController { * * Comentada em vez de apagada: se a listagem voltar, ela precisa nascer * escopada por papel — o ADMIN tem visão global legítima, os demais não. - * Note que GET /api/users/:id (abaixo) continua ativa e é @Public(). + * GET /api/users/:id (abaixo) exige autenticação e acesso self ou ADMIN. */ // /** // * GET /api/users @@ -57,13 +66,17 @@ export class UsersController { /** * GET /api/users/:id - * Get a single user by ID (public - used for specialist info on product pages) + * Get a private user profile (self or ADMIN) * @param userId - The ID of the user (UUID) * @returns User data with full details */ @Get(':id') - @Public() - async getById(@Param('id', new ParseUUIDPipe()) userId: string) { + @UseGuards(AuthGuard) + async getById( + @Param('id', new ParseUUIDPipe()) userId: string, + @Req() req: { user?: UserEntity }, + ) { + this.assertSelfOrAdmin(userId, req?.user); const user = await this.usersService.getById(userId); return { @@ -93,7 +106,9 @@ export class UsersController { async update( @Param('id', new ParseUUIDPipe()) userId: string, @Body() updateUserDto: UpdateUserDto, + @Req() req: { user?: UserEntity }, ) { + this.assertSelfOrAdmin(userId, req?.user); const updatedUser = await this.usersService.update(userId, updateUserDto); return { diff --git a/backend/src/features/users/users.service.spec.ts b/backend/src/features/users/users.service.spec.ts index 095a58be..dc049565 100644 --- a/backend/src/features/users/users.service.spec.ts +++ b/backend/src/features/users/users.service.spec.ts @@ -1,5 +1,9 @@ import { UsersService } from './users.service'; import { UpdateUserDto } from './dto/update-user.dto'; +import { ForbiddenException } from '@nestjs/common'; +import { UserRole } from '@prisma/client'; +import { plainToInstance } from 'class-transformer'; +import { validate } from 'class-validator'; const userId = '11111111-1111-4111-8111-111111111111'; @@ -82,3 +86,68 @@ describe('UsersService — telefone no perfil', () => { expect(semCampo.update.mock.calls[0][0].data).not.toHaveProperty('phone'); }); }); + +describe('UsersService — Calendly no perfil', () => { + it.each([ + UserRole.CUSTOMER, + UserRole.CONSULTANT, + UserRole.OFFICE, + UserRole.ADMIN, + ])( + 'rejects non-null Calendly URLs for target role %s before writing', + async (role) => { + const { service, findUnique, update } = mkService(); + findUnique.mockResolvedValue({ id: userId, role }); + await expect( + service.update(userId, { calendly_url: 'https://calendly.com/ana' }), + ).rejects.toThrow(ForbiddenException); + expect(update).not.toHaveBeenCalled(); + expect(findUnique).toHaveBeenCalledTimes(1); + }, + ); + + it('saves a specialist URL and preserves the private response projection', async () => { + const { service, findUnique, update } = mkService(); + findUnique.mockResolvedValue({ id: userId, role: UserRole.SPECIALIST }); + await service.update(userId, { + calendly_url: ' https://calendly.com/ana ', + }); + expect(update).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + calendly_url: 'https://calendly.com/ana', + }), + select: expect.objectContaining({ phone: true, calendly_url: true }), + }), + ); + }); + + it.each([null, '', ' '])( + 'clears a specialist URL with %p', + async (calendly_url) => { + const { service, findUnique, update } = mkService(); + findUnique.mockResolvedValue({ id: userId, role: UserRole.SPECIALIST }); + await service.update(userId, { calendly_url }); + expect(update.mock.calls[0][0].data.calendly_url).toBeNull(); + }, + ); + + it('allows explicit null removal for a non-specialist but leaves absent URLs untouched', async () => { + const removal = mkService(); + await removal.service.update(userId, { calendly_url: null }); + expect(removal.update.mock.calls[0][0].data.calendly_url).toBeNull(); + const unchanged = mkService(); + await unchanged.service.update(userId, { name: 'Novo' }); + expect(unchanged.update.mock.calls[0][0].data).not.toHaveProperty( + 'calendly_url', + ); + }); + + it.each([null, 'https://calendly.com/ana'])( + 'DTO accepts Calendly value %p', + async (calendly_url) => { + const dto = plainToInstance(UpdateUserDto, { calendly_url }); + expect(await validate(dto)).toEqual([]); + }, + ); +}); diff --git a/backend/src/features/users/users.service.ts b/backend/src/features/users/users.service.ts index 57f427d4..88669c47 100644 --- a/backend/src/features/users/users.service.ts +++ b/backend/src/features/users/users.service.ts @@ -2,11 +2,13 @@ import { Injectable, NotFoundException, ConflictException, + ForbiddenException, } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { GetUsersDto } from './dto/get-users.dto'; import { UpdateUserDto } from './dto/update-user.dto'; import { UserResponse } from './entity/user.response'; +import { UserRole } from '@prisma/client'; @Injectable() export class UsersService { @@ -173,6 +175,15 @@ export class UsersService { throw new NotFoundException(`Usuário com id ${userId} não encontrado`); } + if ( + updateUserDto.calendly_url != null && + existingUser.role !== UserRole.SPECIALIST + ) { + throw new ForbiddenException( + 'Somente especialistas podem definir uma URL do Calendly', + ); + } + // Verificar CPF duplicado (se estiver sendo atualizado) if (updateUserDto.cpf && updateUserDto.cpf !== existingUser.cpf) { const cpfExists = await this.prisma.user.findUnique({ diff --git a/backend/src/providers/docusign/docusign.client.ts b/backend/src/providers/docusign/docusign.client.ts index 775687ea..4edf3a12 100644 --- a/backend/src/providers/docusign/docusign.client.ts +++ b/backend/src/providers/docusign/docusign.client.ts @@ -486,6 +486,22 @@ export class DocuSignClient { ); } + async getTemplateRecipients(templateId: string): Promise { + const token = await this.getAccessToken(); + return this.get( + `/v2.1/accounts/${this.accountId}/templates/${templateId}/recipients`, + token, + ); + } + + async getEnvelopeRecipients(envelopeId: string): Promise { + const token = await this.getAccessToken(); + return this.get( + `/v2.1/accounts/${this.accountId}/envelopes/${envelopeId}/recipients`, + token, + ); + } + /** * Atualiza os campos DocGen de um envelope * diff --git a/backend/src/providers/docusign/docusign.service.spec.ts b/backend/src/providers/docusign/docusign.service.spec.ts index cd1f1fd9..fa1f762f 100644 --- a/backend/src/providers/docusign/docusign.service.spec.ts +++ b/backend/src/providers/docusign/docusign.service.spec.ts @@ -1,5 +1,152 @@ import { DocuSignService } from './docusign.service'; +describe('DocuSignService — prévia com vendedor pendente', () => { + it('cria somente um rascunho e desabilita o envio direto no Sender View', async () => { + const client = { + getEnvelopeRecipients: jest.fn().mockResolvedValue({ + signers: [{ roleName: 'Buyer' }, { roleName: 'Seller' }], + }), + getEnvelopeDocGenFormFields: jest.fn().mockResolvedValue({ docGenFormFields: [] }), + updateEnvelopeDocGenFormFields: jest.fn().mockResolvedValue({}), + createSenderView: jest.fn().mockResolvedValue({ url: 'https://demo.docusign.net/view' }), + } as any; + const service = new DocuSignService(client); + const createDraft = jest.spyOn(service as any, 'createOrRecoverTemplateEnvelope') + .mockResolvedValue({ envelopeId: 'draft-1', status: 'created' }); + + const preview = await service.createEnvelopePreview({ + transactionId: 'operation-1', + templateId: 'template-1', + buyerName: 'Comprador', + buyerEmail: 'buyer@example.test', + sellerName: '', + sellerEmail: '', + formFields: {}, + processId: 'process-1', + requestFingerprint: 'fingerprint-1', + returnUrl: 'https://app.example.test/callback', + }); + + const roles = createDraft.mock.calls[0][0].templateRoles; + expect(roles).toEqual(expect.arrayContaining([ + expect.objectContaining({ roleName: 'Buyer' }), + ])); + expect(roles.some((role: { roleName: string }) => role.roleName === 'Seller')).toBe(false); + expect(roles.some((role: { roleName: string }) => role.roleName === 'Testimonial1')).toBe(false); + expect(preview.sellerSignatureRequired).toBe(true); + expect(client.createSenderView).toHaveBeenCalledWith( + 'draft-1', + 'https://app.example.test/callback', + expect.objectContaining({ sendButtonAction: 'redirect' }), + ); + }); + + it('aceita o modelo futuro sem Seller mesmo quando o formulário tem vendedor', async () => { + const client = { + getTemplateRecipients: jest.fn().mockResolvedValue({ signers: [{ roleName: 'Buyer' }] }), + getEnvelopeRecipients: jest.fn().mockResolvedValue({ signers: [{ roleName: 'Buyer' }] }), + getEnvelopeDocGenFormFields: jest.fn().mockResolvedValue({ docGenFormFields: [] }), + updateEnvelopeDocGenFormFields: jest.fn().mockResolvedValue({}), + createSenderView: jest.fn().mockResolvedValue({ url: 'https://demo.docusign.net/view' }), + } as any; + const service = new DocuSignService(client); + const createDraft = jest.spyOn(service as any, 'createOrRecoverTemplateEnvelope') + .mockResolvedValue({ envelopeId: 'draft-2', status: 'created' }); + + const preview = await service.createEnvelopePreview({ + transactionId: 'operation-2', + templateId: 'template-2', + buyerName: 'Comprador', + buyerEmail: 'buyer@example.test', + sellerName: 'Vendedor', + sellerEmail: 'seller@example.test', + formFields: {}, + processId: 'process-2', + requestFingerprint: 'fingerprint-2', + returnUrl: 'https://app.example.test/callback', + }); + + expect(createDraft.mock.calls[0][0].templateRoles.some( + (role: { roleName: string }) => role.roleName === 'Seller', + )).toBe(false); + expect(preview.sellerSignatureRequired).toBe(false); + }); + + it('atribui Seller, Specialist e Testimonial1 ao especialista quando o vendedor está vazio', async () => { + const client = { + getEnvelopeRecipients: jest.fn().mockResolvedValue({ + signers: [{ roleName: 'Buyer' }, { roleName: 'Seller' }, { roleName: 'Specialist' }, { roleName: 'Testimonial1' }], + }), + getEnvelopeDocGenFormFields: jest.fn().mockResolvedValue({ docGenFormFields: [] }), + updateEnvelopeDocGenFormFields: jest.fn().mockResolvedValue({}), + createSenderView: jest.fn().mockResolvedValue({ url: 'https://demo.docusign.net/view' }), + } as any; + const service = new DocuSignService(client); + const createDraft = jest.spyOn(service as any, 'createOrRecoverTemplateEnvelope') + .mockResolvedValue({ envelopeId: 'draft-3', status: 'created' }); + + await service.createEnvelopePreview({ + transactionId: 'operation-3', + templateId: 'template-3', + templateHasSellerRole: true, + buyerName: 'Comprador', + buyerEmail: 'buyer@example.test', + sellerName: 'Especialista', + sellerEmail: 'specialist@example.test', + specialistName: 'Especialista', + specialistEmail: 'specialist@example.test', + formFields: {}, + processId: 'process-3', + requestFingerprint: 'fingerprint-3', + returnUrl: 'https://app.example.test/callback', + }); + + const roles = createDraft.mock.calls[0][0].templateRoles; + expect(roles.filter((role: { email: string }) => role.email === 'specialist@example.test')) + .toEqual(expect.arrayContaining([ + expect.objectContaining({ roleName: 'Seller', name: 'Especialista' }), + expect.objectContaining({ roleName: 'Specialist', name: 'Especialista' }), + expect.objectContaining({ roleName: 'Testimonial1', name: 'Especialista' }), + ])); + }); + + it('usa o especialista como Testimonial1 quando o modelo não tem Seller', async () => { + const client = { + getEnvelopeRecipients: jest.fn().mockResolvedValue({ + signers: [{ roleName: 'Buyer' }, { roleName: 'Testimonial1' }], + }), + getEnvelopeDocGenFormFields: jest.fn().mockResolvedValue({ docGenFormFields: [] }), + updateEnvelopeDocGenFormFields: jest.fn().mockResolvedValue({}), + createSenderView: jest.fn().mockResolvedValue({ url: 'https://demo.docusign.net/view' }), + } as any; + const service = new DocuSignService(client); + const createDraft = jest.spyOn(service as any, 'createOrRecoverTemplateEnvelope') + .mockResolvedValue({ envelopeId: 'draft-4', status: 'created' }); + + await service.createEnvelopePreview({ + transactionId: 'operation-4', + templateId: 'template-4', + templateHasSellerRole: false, + buyerName: 'Comprador', + buyerEmail: 'buyer@example.test', + sellerName: '', + sellerEmail: '', + specialistName: 'Especialista', + specialistEmail: 'specialist@example.test', + formFields: {}, + processId: 'process-4', + requestFingerprint: 'fingerprint-4', + returnUrl: 'https://app.example.test/callback', + }); + + const roles = createDraft.mock.calls[0][0].templateRoles; + expect(roles).toContainEqual(expect.objectContaining({ + roleName: 'Testimonial1', name: 'Especialista', email: 'specialist@example.test', + })); + expect(roles.some((role: { roleName: string }) => role.roleName === 'Seller')).toBe(false); + }); +}); + describe('DocuSignService — listTemplates', () => { it('mapeia envelopeTemplates do client para {templateId, name}', async () => { const client = { diff --git a/backend/src/providers/docusign/docusign.service.ts b/backend/src/providers/docusign/docusign.service.ts index 33a0fc4e..36c180d9 100644 --- a/backend/src/providers/docusign/docusign.service.ts +++ b/backend/src/providers/docusign/docusign.service.ts @@ -426,12 +426,14 @@ export class DocuSignService { async getEnvelopeProcessId(envelopeId: string): Promise { const envelope = await this.client.getEnvelopeWithCustomFields(envelopeId); - const fields = envelope?.customFields?.textCustomFields; - if (!Array.isArray(fields)) return null; - const processField = fields.find( - (field: any) => field?.name === 'processId', - ); - return typeof processField?.value === 'string' ? processField.value : null; + return this.getCustomFieldValue(envelope, 'processId'); + } + + async getEnvelopeRequestFingerprint( + envelopeId: string, + ): Promise { + const envelope = await this.client.getEnvelopeWithCustomFields(envelopeId); + return this.getCustomFieldValue(envelope, 'requestFingerprint'); } /** @@ -767,10 +769,12 @@ export class DocuSignService { testimonial2Name?: string; testimonial2Email?: string; onEnvelopeCreated?: (envelopeId: string) => void; + templateHasSellerRole?: boolean; }): Promise<{ envelopeId: string; previewUrl: string; expiresAt: string; + sellerSignatureRequired: boolean; }> { const { templateId, @@ -790,6 +794,7 @@ export class DocuSignService { testimonial2Name, testimonial2Email, onEnvelopeCreated, + templateHasSellerRole: knownTemplateHasSellerRole, } = params; let createdEnvelopeId: string | null = null; @@ -806,12 +811,6 @@ export class DocuSignService { ); } - if (!sellerEmail || sellerEmail.trim().length === 0) { - throw new EnvelopeCreationFailedException( - 'Email do vendedor é obrigatório', - ); - } - this.logger.log(`=== INICIANDO FLUXO DE PREVIEW (3 ETAPAS) ===`); this.logger.debug(`Template ID: ${templateId}`); this.logger.debug(`Process ID: ${processId}`); @@ -819,43 +818,50 @@ export class DocuSignService { // ===== ETAPA 1: CRIAR ENVELOPE COMO DRAFT ===== this.logger.log('PREVIEW ETAPA 1: Criando envelope como DRAFT...'); + // Um template futuro pode dispensar o papel Seller. Nesse caso, não + // anexar um destinatário que já não existe no template. + const templateHasSellerRole = knownTemplateHasSellerRole ?? ( + sellerName && sellerEmail + ? await this.templateHasSellerRole(templateId) + : false + ); + + const templateRoles: CreateTemplateEnvelopeDto['templateRoles'] = [ + { roleName: 'Buyer', name: buyerName, email: buyerEmail }, + ]; + if (templateHasSellerRole && sellerName && sellerEmail) { + templateRoles.push({ roleName: 'Seller', name: sellerName, email: sellerEmail }); + } + if (specialistEmail && specialistName) { + templateRoles.push({ + roleName: 'Specialist', name: specialistName, email: specialistEmail, + }); + } + // Sem testemunha informada, o especialista assume Testemunha 1. + // Com vendedor real, preservamos o fallback anterior ao vendedor. + const witness1Email = testimonial1Email || sellerEmail || specialistEmail; + if (witness1Email) { + templateRoles.push({ + roleName: 'Testimonial1', + name: testimonial1Name || + (!testimonial1Email && (!sellerEmail || sellerEmail === specialistEmail) + ? specialistName || 'Testemunha 1' + : 'Testemunha 1'), + email: witness1Email, + }); + } + templateRoles.push({ + roleName: 'Testimonial2', + name: testimonial2Name || 'Testemunha 2', + email: testimonial2Email || buyerEmail, + }); + const createEnvelopeDto: CreateTemplateEnvelopeDto = { transactionId, templateId, status: 'created', // DRAFT - não envia emailSubject: 'Contrato de Compra e Venda - Assinatura Digital', - templateRoles: [ - { - roleName: 'Buyer', - name: buyerName, - email: buyerEmail, - }, - { - roleName: 'Seller', - name: sellerName, - email: sellerEmail, - }, - ...(specialistEmail && specialistName - ? [ - { - roleName: 'Specialist', - name: specialistName, - email: specialistEmail, - }, - ] - : []), - // Testemunhas são obrigatórias no template — se não fornecidas, usar placeholder - { - roleName: 'Testimonial1', - name: testimonial1Name || 'Testemunha 1', - email: testimonial1Email || sellerEmail, - }, - { - roleName: 'Testimonial2', - name: testimonial2Name || 'Testemunha 2', - email: testimonial2Email || buyerEmail, - }, - ], + templateRoles, customFields: { textCustomFields: [ { @@ -889,6 +895,12 @@ export class DocuSignService { this.logger.log(`✓ Envelope DRAFT criado. ID: ${envelopeId}`); + // O envelope é a fonte de verdade: ele preserva os papéis do template + // mesmo quando templateRoles não preenche um destinatário. + const sellerSignatureRequired = this.hasSellerRole( + await this.client.getEnvelopeRecipients(envelopeId), + ); + // ===== ETAPA 2: BUSCAR E ATUALIZAR CAMPOS DOCGEN ===== this.logger.log('PREVIEW ETAPA 2: Preenchendo campos DocGen...'); @@ -922,7 +934,7 @@ export class DocuSignService { showEditRecipients: 'false', showEditDocuments: 'true', showDiscardAction: 'false', - sendButtonAction: 'send', + sendButtonAction: 'redirect', }, ); @@ -936,6 +948,7 @@ export class DocuSignService { envelopeId, previewUrl: senderViewResponse.url, expiresAt, + sellerSignatureRequired, }; } catch (error) { if ( @@ -1153,6 +1166,25 @@ export class DocuSignService { }); } + private hasSellerRole(recipients: { signers?: Array<{ roleName?: string }> }): boolean { + if (!Array.isArray(recipients?.signers)) { + throw new EnvelopeCreationFailedException( + 'Não foi possível verificar os signatários do contrato.', + ); + } + return recipients.signers.some( + (recipient) => recipient.roleName?.trim().toLowerCase() === 'seller', + ); + } + + async hasSellerRecipient(envelopeId: string): Promise { + return this.hasSellerRole(await this.client.getEnvelopeRecipients(envelopeId)); + } + + async templateHasSellerRole(templateId: string): Promise { + return this.hasSellerRole(await this.client.getTemplateRecipients(templateId)); + } + /** * Lista os templates de envelope disponíveis na conta DocuSign * diff --git a/backend/src/providers/docusign/webhook/webhook.service.spec.ts b/backend/src/providers/docusign/webhook/webhook.service.spec.ts index c8cc887d..9760c468 100644 --- a/backend/src/providers/docusign/webhook/webhook.service.spec.ts +++ b/backend/src/providers/docusign/webhook/webhook.service.spec.ts @@ -48,6 +48,7 @@ describe('DocuSignWebhookService monotonic convergence', () => { let providerStatus = ProviderStatus.SENT; const historyCreate = jest.fn().mockResolvedValue({}); const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), contract: { updateMany: jest.fn().mockImplementation(async ({ where, data }) => { if (providerStatus !== where.provider_status) return { count: 0 }; @@ -68,7 +69,7 @@ describe('DocuSignWebhookService monotonic convergence', () => { status: ProcessStatus.DOCUMENTATION, active_contract_id: 'contract-1', }), - update: jest.fn().mockResolvedValue({}), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), }, processStatusHistory: { create: historyCreate }, }; @@ -116,6 +117,7 @@ describe('DocuSignWebhookService monotonic convergence', () => { }); const historyCreate = jest.fn().mockResolvedValue({}); const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), contract: { updateMany: jest.fn().mockImplementation(async ({ where, data }) => { if (data.provider_status === ProviderStatus.COMPLETED) { @@ -144,9 +146,9 @@ describe('DocuSignWebhookService monotonic convergence', () => { status: processStatus, active_contract_id: 'contract-1', })), - update: jest.fn().mockImplementation(async ({ data }) => { + updateMany: jest.fn().mockImplementation(async ({ data }) => { if (data.status) processStatus = data.status; - return {}; + return { count: 1 }; }), }, processStatusHistory: { create: historyCreate }, @@ -200,6 +202,7 @@ describe('DocuSignWebhookService monotonic convergence', () => { signed_at: null, }; const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), contract: { updateMany: jest.fn().mockResolvedValue({ count: 0 }), }, @@ -224,4 +227,54 @@ describe('DocuSignWebhookService monotonic convergence', () => { }); expect(prisma.$transaction).toHaveBeenCalledTimes(3); }); + + it('preserva contrato, mas não altera processo removido em webhook atrasado', async () => { + const contractUpdate = jest.fn().mockResolvedValue({ count: 1 }); + const processUpdate = jest.fn(); + const historyCreate = jest.fn(); + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ locked: null }]), + contract: { + updateMany: contractUpdate, + findUniqueOrThrow: jest.fn().mockResolvedValue({ id: 'contract-1' }), + }, + process: { + findUnique: jest.fn().mockResolvedValue({ + id: 'process-1', + status: ProcessStatus.COMPLETED, + active_contract_id: 'contract-1', + removed_at: new Date(), + }), + updateMany: processUpdate, + }, + processStatusHistory: { create: historyCreate }, + }; + const prisma = { + contract: { + findFirst: jest.fn().mockResolvedValue({ + id: 'contract-1', + process_id: 'process-1', + provider_status: ProviderStatus.DELIVERED, + status: 'PENDING', + provider_meta: {}, + signed_at: null, + }), + findUnique: jest.fn().mockResolvedValue({ + process: { removed_at: new Date() }, + }), + }, + $transaction: jest + .fn() + .mockImplementation(async (callback) => callback(tx)), + } as any; + + await new DocuSignWebhookService( + prisma, + {} as any, + ).handleEnvelopeStatusChanged(completedPayload); + + expect(contractUpdate).toHaveBeenCalledTimes(1); + expect(processUpdate).not.toHaveBeenCalled(); + expect(historyCreate).not.toHaveBeenCalled(); + }); }); diff --git a/backend/src/providers/docusign/webhook/webhook.service.ts b/backend/src/providers/docusign/webhook/webhook.service.ts index 97e0e0db..2d184558 100644 --- a/backend/src/providers/docusign/webhook/webhook.service.ts +++ b/backend/src/providers/docusign/webhook/webhook.service.ts @@ -315,6 +315,11 @@ export class DocuSignWebhookService { // ===== ETAPA 7: ATUALIZAR CONTRATO E SINCRONIZAR PROCESSO ===== const updated = await this.prismaService.$transaction(async (tx) => { + // Serializa com exclusão lógica e operações de contrato no mesmo processo. + const lockKey = `contract-process:${contract.process_id}`; + await tx.$queryRaw` + SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))::text AS locked + `; // 7.1 Claim CAS: somente uma entrega concorrente produz efeitos. const claim = await tx.contract.updateMany({ where: { @@ -340,7 +345,7 @@ export class DocuSignWebhookService { // 7.2 Buscar processo relacionado const process = await tx.process.findUnique({ where: { id: contract.process_id }, - select: { id: true, status: true, active_contract_id: true }, + select: { id: true, status: true, active_contract_id: true, removed_at: true }, }); if (!process) { @@ -350,9 +355,27 @@ export class DocuSignWebhookService { return updatedContract; } + // O evento ainda atualiza o contrato para auditoria, mas não pode + // reabrir ou concluir um processo retirado das jornadas comuns. + if (process.removed_at) { + return updatedContract; + } + + // O contrato mantém seu próprio estado, mas somente o contrato ativo + // pode dirigir a máquina de estados do processo. Eventos atrasados de + // envelopes substituídos não podem reativar nem concluir a venda. + if (process.active_contract_id !== contract.id) { + this.logger.log( + `[SYNC] Webhook do contrato não ativo ${contract.id}; processo ${process.id} preservado`, + ); + return updatedContract; + } + // 7.3 Sincronizar status do processo com base no status do contrato const processStatusUpdate: any = {}; let updateProcessActiveContract = false; + let historyStatus: ProcessStatus | null = null; + let historyReason: ProcessCompletionReason | null = null; if ( providerStatus === 'SENT' && @@ -372,14 +395,8 @@ export class DocuSignWebhookService { this.logger.log( `[SYNC] Processo ${process.id}: → COMPLETED (contrato assinado)`, ); - // Registrar razão de conclusão - await tx.processStatusHistory.create({ - data: { - processId: process.id, - status: ProcessStatus.COMPLETED, - reason: ProcessCompletionReason.CONTRACT_SIGNED, - }, - }); + historyStatus = ProcessStatus.COMPLETED; + historyReason = ProcessCompletionReason.CONTRACT_SIGNED; } else if ( ['DECLINED', 'VOIDED', 'TIMEDOUT'].includes(providerStatus) ) { @@ -397,13 +414,8 @@ export class DocuSignWebhookService { } else if (providerStatus === 'TIMEDOUT') { completionReason = ProcessCompletionReason.CONTRACT_TIMEDOUT; } - await tx.processStatusHistory.create({ - data: { - processId: process.id, - status: ProcessStatus.REJECTED, - reason: completionReason, - }, - }); + historyStatus = ProcessStatus.REJECTED; + historyReason = completionReason; } else if (process.active_contract_id === contract.id) { // Se este é o contrato ativo, manter status como está updateProcessActiveContract = true; @@ -421,11 +433,24 @@ export class DocuSignWebhookService { processStatusUpdate.active_contract_id = contract.id; } - await tx.process.update({ - where: { id: process.id }, + const processClaim = await tx.process.updateMany({ + where: { id: process.id, removed_at: null }, data: processStatusUpdate, }); + if (processClaim.count !== 1) { + return updatedContract; + } + if (historyStatus && historyReason) { + await tx.processStatusHistory.create({ + data: { + processId: process.id, + status: historyStatus, + reason: historyReason, + }, + }); + } + this.logger.log(`[SYNC] Processo atualizado:`, { processId: process.id, statusBefore: process.status, @@ -496,11 +521,13 @@ export class DocuSignWebhookService { id: true, buyer_name: true, seller_name: true, + provider_meta: true, vehicle_model: true, vehicle_year: true, vehicle_price: true, process: { select: { + removed_at: true, client: { select: { email: true, name: true, surname: true } }, specialist: { select: { email: true, name: true, surname: true }, @@ -510,21 +537,27 @@ export class DocuSignWebhookService { }, }); - if (contractWithDetails) { + if (contractWithDetails && !contractWithDetails.process?.removed_at) { const buyerEmail = contractWithDetails.process?.client?.email; const buyerName = contractWithDetails.buyer_name || `${contractWithDetails.process?.client?.name || ''} ${contractWithDetails.process?.client?.surname || ''}`.trim(); - const sellerEmail = contractWithDetails.process?.specialist?.email; - const sellerName = - contractWithDetails.seller_name || - `${contractWithDetails.process?.specialist?.name || ''} ${contractWithDetails.process?.specialist?.surname || ''}`.trim(); + const metadata = contractWithDetails.provider_meta; + const specialistEmail = contractWithDetails.process?.specialist?.email; + const sellerEmail = metadata && typeof metadata === 'object' && + !Array.isArray(metadata) && 'sellerEmail' in metadata + ? typeof metadata.sellerEmail === 'string' + ? metadata.sellerEmail + : undefined + : specialistEmail; // Contratos antigos não registravam sellerEmail. + const sellerName = contractWithDetails.seller_name || undefined; + const specialistName = `${contractWithDetails.process?.specialist?.name || ''} ${contractWithDetails.process?.specialist?.surname || ''}`.trim(); const vehicleDetails = `${contractWithDetails.vehicle_model || ''} ${contractWithDetails.vehicle_year || ''}`.trim(); setImmediate(() => { // Notificar baseado no status - if (providerStatus === 'SENT' && buyerEmail && sellerEmail) { + if (providerStatus === 'SENT' && buyerEmail) { this.notificationService .sendContractSentEmail({ buyerEmail, @@ -545,7 +578,7 @@ export class DocuSignWebhookService { } else if ( providerStatus === 'COMPLETED' && buyerEmail && - sellerEmail + buyerEmail ) { this.notificationService .sendContractSignedEmail({ @@ -565,11 +598,11 @@ export class DocuSignWebhookService { errorType: err instanceof Error ? err.name : typeof err, }); }); - } else if (providerStatus === 'DECLINED' && sellerEmail) { + } else if (providerStatus === 'DECLINED' && specialistEmail) { this.notificationService .sendContractDeclinedEmail({ - specialistEmail: sellerEmail, - specialistName: sellerName, + specialistEmail, + specialistName, clientEmail: buyerEmail || '', clientName: buyerName, contractId: contract.id, @@ -583,11 +616,11 @@ export class DocuSignWebhookService { errorType: err instanceof Error ? err.name : typeof err, }); }); - } else if (providerStatus === 'VOIDED' && sellerEmail) { + } else if (providerStatus === 'VOIDED' && specialistEmail) { this.notificationService .sendContractVoidedEmail({ - specialistEmail: sellerEmail, - specialistName: sellerName, + specialistEmail, + specialistName, clientEmail: buyerEmail || '', clientName: buyerName, contractId: contract.id, @@ -601,11 +634,11 @@ export class DocuSignWebhookService { errorType: err instanceof Error ? err.name : typeof err, }); }); - } else if (providerStatus === 'TIMEDOUT' && sellerEmail) { + } else if (providerStatus === 'TIMEDOUT' && specialistEmail) { this.notificationService .sendContractTimeoutEmail({ - specialistEmail: sellerEmail, - specialistName: sellerName, + specialistEmail, + specialistName, clientEmail: buyerEmail || '', clientName: buyerName, contractId: contract.id, diff --git a/backend/src/shared/actor-context/actor-context.module.ts b/backend/src/shared/actor-context/actor-context.module.ts new file mode 100644 index 00000000..c675d53e --- /dev/null +++ b/backend/src/shared/actor-context/actor-context.module.ts @@ -0,0 +1,10 @@ +import { Global, Module } from '@nestjs/common'; +import { ActorContextService } from './actor-context.service'; +import { DelegatedActionAuditService } from './delegated-action-audit.service'; + +@Global() +@Module({ + providers: [ActorContextService, DelegatedActionAuditService], + exports: [ActorContextService, DelegatedActionAuditService], +}) +export class ActorContextModule {} diff --git a/backend/src/shared/actor-context/actor-context.service.spec.ts b/backend/src/shared/actor-context/actor-context.service.spec.ts new file mode 100644 index 00000000..230b792b --- /dev/null +++ b/backend/src/shared/actor-context/actor-context.service.spec.ts @@ -0,0 +1,100 @@ +import { BadRequestException, ForbiddenException } from '@nestjs/common'; +import { ProductType, UserRole } from '@prisma/client'; +import { ActorContextService } from './actor-context.service'; + +describe('ActorContextService', () => { + const activeSpecialist = { + id: 'specialist-1', + role: UserRole.SPECIALIST, + is_active: true, + speciality: ProductType.CAR, + name: 'Specialist', + surname: 'One', + }; + const prisma = { + user: { findUnique: jest.fn() }, + } as any; + const service = new ActorContextService(prisma); + + beforeEach(() => jest.clearAllMocks()); + + it('requires an explicit represented specialist for ADMIN', async () => { + await expect( + service.resolve( + { id: 'admin-1', role: UserRole.ADMIN } as any, + undefined, + ), + ).rejects.toBeInstanceOf(BadRequestException); + expect(prisma.user.findUnique).not.toHaveBeenCalled(); + }); + + it.each([ + [{ ...activeSpecialist, role: UserRole.CUSTOMER }, 'papel'], + [{ ...activeSpecialist, is_active: false }, 'inativo'], + [{ ...activeSpecialist, speciality: ProductType.BOAT }, 'especialidade'], + ])('denies an invalid represented specialist (%s)', async (record) => { + prisma.user.findUnique.mockResolvedValue(record); + + await expect( + service.resolve( + { id: 'admin-1', role: UserRole.ADMIN } as any, + activeSpecialist.id, + ProductType.CAR, + ), + ).rejects.toBeInstanceOf(ForbiddenException); + }); + + it('keeps the ADMIN as actor and the SPECIALIST as represented party', async () => { + prisma.user.findUnique.mockResolvedValue(activeSpecialist); + + await expect( + service.resolve( + { id: 'admin-1', role: UserRole.ADMIN } as any, + activeSpecialist.id, + ProductType.CAR, + ), + ).resolves.toEqual({ + actorId: 'admin-1', + actorRole: UserRole.ADMIN, + actor: { + id: 'admin-1', + role: UserRole.ADMIN, + name: '', + surname: '', + }, + specialistId: activeSpecialist.id, + specialist: activeSpecialist, + delegated: true, + }); + }); + + it('preserves a specialist normal session and rejects injected targets', async () => { + const specialistActor = { + ...activeSpecialist, + role: UserRole.SPECIALIST, + } as any; + + await expect( + service.resolve(specialistActor, undefined, ProductType.CAR), + ).resolves.toMatchObject({ + actorId: activeSpecialist.id, + specialistId: activeSpecialist.id, + delegated: false, + }); + await expect( + service.resolve(specialistActor, 'specialist-2', ProductType.CAR), + ).rejects.toBeInstanceOf(ForbiddenException); + }); + + it('denies resource IDs owned by another specialist', async () => { + prisma.user.findUnique.mockResolvedValue(activeSpecialist); + const context = await service.resolve( + { id: 'admin-1', role: UserRole.ADMIN } as any, + activeSpecialist.id, + ); + + expect(() => + service.assertResourceSpecialist(context, 'specialist-2'), + ).toThrow(ForbiddenException); + }); +}); diff --git a/backend/src/shared/actor-context/actor-context.service.ts b/backend/src/shared/actor-context/actor-context.service.ts new file mode 100644 index 00000000..6f55b2d2 --- /dev/null +++ b/backend/src/shared/actor-context/actor-context.service.ts @@ -0,0 +1,138 @@ +import { + BadRequestException, + ForbiddenException, + Injectable, +} from '@nestjs/common'; +import { ProductType, UserRole } from '@prisma/client'; +import { UserEntity } from 'src/auth/entities/user.entity'; +import { PrismaService } from 'src/prisma/prisma.service'; + +export type ActorContext = { + actorId: string; + actorRole: UserRole; + actor: { id: string; role: UserRole; name: string; surname: string }; + specialistId: string; + specialist: { + id: string; + role: UserRole; + is_active: boolean; + speciality: ProductType | null; + name: string; + surname: string; + }; + delegated: boolean; +}; + +@Injectable() +export class ActorContextService { + constructor(private readonly prisma: PrismaService) {} + + async resolve( + actor: Pick, + targetSpecialistId?: string, + requiredSpeciality?: ProductType, + ): Promise { + if (actor.role === UserRole.SPECIALIST) { + if (targetSpecialistId && targetSpecialistId !== actor.id) { + throw new ForbiddenException( + 'Especialistas não podem operar em nome de outro especialista.', + ); + } + if (actor.is_active === false) { + throw new ForbiddenException('Especialista inativo.'); + } + if (requiredSpeciality && actor.speciality !== requiredSpeciality) { + throw new ForbiddenException( + 'A especialidade do especialista não corresponde ao recurso.', + ); + } + return { + actorId: actor.id, + actorRole: actor.role, + actor: { + id: actor.id, + role: actor.role, + name: actor.name ?? '', + surname: actor.surname ?? '', + }, + specialistId: actor.id, + specialist: { + id: actor.id, + role: actor.role, + is_active: true, + speciality: actor.speciality ?? null, + name: actor.name ?? '', + surname: actor.surname ?? '', + }, + delegated: false, + }; + } + + if (actor.role !== UserRole.ADMIN) { + throw new ForbiddenException( + 'Este papel não pode representar um especialista.', + ); + } + if (!targetSpecialistId) { + throw new BadRequestException( + 'target_specialist_id é obrigatório para ações administrativas.', + ); + } + + const specialist = await this.prisma.user.findUnique({ + where: { id: targetSpecialistId }, + select: { + id: true, + role: true, + is_active: true, + speciality: true, + name: true, + surname: true, + }, + }); + if (!specialist || specialist.role !== UserRole.SPECIALIST) { + throw new ForbiddenException( + 'O usuário representado deve ser um especialista existente.', + ); + } + if (!specialist.is_active) { + throw new ForbiddenException('O especialista representado está inativo.'); + } + if ( + requiredSpeciality && + specialist.speciality !== requiredSpeciality + ) { + throw new ForbiddenException( + 'A especialidade do especialista representado não corresponde ao recurso.', + ); + } + + return { + actorId: actor.id, + actorRole: actor.role, + actor: { + id: actor.id, + role: actor.role, + name: actor.name ?? '', + surname: actor.surname ?? '', + }, + specialistId: specialist.id, + specialist, + delegated: true, + }; + } + + assertResourceSpecialist( + context: ActorContext, + resourceSpecialistId: string | null | undefined, + ): void { + if ( + !resourceSpecialistId || + resourceSpecialistId !== context.specialistId + ) { + throw new ForbiddenException( + 'O recurso não pertence ao especialista representado.', + ); + } + } +} diff --git a/backend/src/shared/actor-context/delegated-action-audit.service.ts b/backend/src/shared/actor-context/delegated-action-audit.service.ts new file mode 100644 index 00000000..f80a7e03 --- /dev/null +++ b/backend/src/shared/actor-context/delegated-action-audit.service.ts @@ -0,0 +1,140 @@ +import { Injectable } from '@nestjs/common'; +import { Prisma, UserRole } from '@prisma/client'; +import { randomUUID } from 'node:crypto'; +import { PrismaService } from 'src/prisma/prisma.service'; +import { ActorContext } from './actor-context.service'; + +export type DelegatedActionAuditInput = { + context: ActorContext; + action: string; + resourceType: string; + resourceId: string; + metadata?: Record; +}; + +export type DelegatedProposalExecutor = { + proposalId: string; + actor: { id: string; role: UserRole; name: string | null }; +}; + +@Injectable() +export class DelegatedActionAuditService { + constructor(private readonly prisma: PrismaService) {} + + async record( + input: DelegatedActionAuditInput, + client: PrismaService | Prisma.TransactionClient = this.prisma, + ): Promise { + const metadata = JSON.stringify(input.metadata ?? {}); + await client.$executeRaw` + INSERT INTO "DelegatedActionAudit" ( + "id", "actor_id", "actor_role", "represented_specialist_id", + "action", "resource_type", "resource_id", "metadata", "created_at" + ) VALUES ( + ${randomUUID()}::uuid, + ${input.context.actorId}::uuid, + ${input.context.actorRole}::"UserRole", + ${input.context.specialistId}::uuid, + ${input.action}, + ${input.resourceType}, + ${input.resourceId}, + ${metadata}::jsonb, + NOW() + ) + `; + } + + async listProposalCreators( + processId: string, + specialistId: string, + ): Promise { + const rows = await this.prisma.$queryRaw< + Array<{ + resource_id: string; + actor_id: string; + actor_role: UserRole; + actor_name: string | null; + }> + >` + SELECT audit."resource_id", audit."actor_id", audit."actor_role", + CONCAT_WS(' ', actor."name", actor."surname") AS "actor_name" + FROM "DelegatedActionAudit" audit + LEFT JOIN "User" actor ON actor."id" = audit."actor_id" + WHERE audit."represented_specialist_id" = ${specialistId}::uuid + AND audit."resource_type" = 'PROPOSAL' + AND audit."action" IN ('PROPOSAL_CREATE', 'PROPOSAL_COUNTER') + AND audit."metadata"->>'processId' = ${processId} + ORDER BY audit."created_at" DESC + `; + return rows.map((row) => ({ + proposalId: row.resource_id, + actor: { + id: row.actor_id, + role: row.actor_role, + name: row.actor_name, + }, + })); + } + + async listForProcess( + context: ActorContext, + processId: string, + limit = 50, + ): Promise< + Array<{ + id: string; + action: string; + resourceType: string; + resourceId: string; + metadata: Record | null; + createdAt: Date; + actor: { id: string; role: UserRole; name: string | null }; + representedSpecialistId: string; + }> + > { + const boundedLimit = Math.max(1, Math.min(limit, 100)); + const rows = await this.prisma.$queryRaw< + Array<{ + id: string; + actor_id: string; + actor_role: UserRole; + actor_name: string | null; + represented_specialist_id: string; + action: string; + resource_type: string; + resource_id: string; + metadata: Record | null; + created_at: Date; + }> + >` + SELECT audit."id", audit."actor_id", audit."actor_role", + CONCAT_WS(' ', actor."name", actor."surname") AS "actor_name", + audit."represented_specialist_id", audit."action", + audit."resource_type", audit."resource_id", audit."metadata", + audit."created_at" + FROM "DelegatedActionAudit" audit + LEFT JOIN "User" actor ON actor."id" = audit."actor_id" + WHERE audit."represented_specialist_id" = ${context.specialistId}::uuid + AND ( + (audit."resource_type" = 'PROCESS' AND audit."resource_id" = ${processId}) + OR audit."metadata"->>'processId' = ${processId} + ) + ORDER BY audit."created_at" DESC + LIMIT ${boundedLimit} + `; + return rows.map((row) => ({ + id: row.id, + action: row.action, + resourceType: row.resource_type, + resourceId: row.resource_id, + metadata: row.metadata, + createdAt: row.created_at, + actor: { + id: row.actor_id, + role: row.actor_role, + name: row.actor_name, + }, + representedSpecialistId: row.represented_specialist_id, + })); + } +} diff --git a/backend/src/shared/helpers/specialist-auth.helper.ts b/backend/src/shared/helpers/specialist-auth.helper.ts index 51d163c5..a78866f6 100644 --- a/backend/src/shared/helpers/specialist-auth.helper.ts +++ b/backend/src/shared/helpers/specialist-auth.helper.ts @@ -1,4 +1,4 @@ -import { ForbiddenException } from '@nestjs/common'; +import { BadRequestException, ForbiddenException } from '@nestjs/common'; import { UserRole } from '@prisma/client'; import { UserEntity } from 'src/auth/entities/user.entity'; import { SpecialityType } from 'src/auth/dto/auth'; @@ -90,3 +90,13 @@ export function assertSpecialistOwnsProduct( 'Apenas ADMIN e SPECIALIST podem modificar produtos.', ); } + +export function assertNoProductOwnerMutation( + dto: Record, +): void { + if (Object.prototype.hasOwnProperty.call(dto, 'specialist_id')) { + throw new BadRequestException( + 'O responsável pelo produto é imutável nesta rota. Use um comando de transferência dedicado.', + ); + } +} diff --git a/backend/src/shared/selects/public-catalog.select.ts b/backend/src/shared/selects/public-catalog.select.ts new file mode 100644 index 00000000..d2411353 --- /dev/null +++ b/backend/src/shared/selects/public-catalog.select.ts @@ -0,0 +1,85 @@ +import { Prisma } from '@prisma/client'; + +export const publicCatalogSpecialistSelect = { + id: true, + name: true, + surname: true, +} satisfies Prisma.UserSelect; + +export const publicCatalogImageSelect = { + id: true, + image_url: true, + is_primary: true, +} satisfies Prisma.Car_imageSelect & + Prisma.Boat_imageSelect & + Prisma.Aircraft_imageSelect; + +export const publicCarSelect = { + id: true, + specialist_id: true, + is_active: true, + marca: true, + modelo: true, + identificador: true, + valor: true, + currency: true, + estado: true, + ano: true, + descricao: true, + cor: true, + km: true, + cambio: true, + combustivel: true, + tipo_categoria: true, + created_at: true, + updated_at: true, + images: { select: publicCatalogImageSelect }, + specialist: { select: publicCatalogSpecialistSelect }, +} satisfies Prisma.CarSelect; + +export const publicBoatSelect = { + id: true, + specialist_id: true, + is_active: true, + marca: true, + modelo: true, + identificador: true, + valor: true, + currency: true, + ano: true, + fabricante: true, + tamanho: true, + estilo: true, + combustivel: true, + motor: true, + ano_motor: true, + descricao_completa: true, + acessorios: true, + estado: true, + tipo_embarcacao: true, + created_at: true, + updated_at: true, + images: { select: publicCatalogImageSelect }, + specialist: { select: publicCatalogSpecialistSelect }, +} satisfies Prisma.BoatSelect; + +export const publicAircraftSelect = { + id: true, + specialist_id: true, + is_active: true, + categoria: true, + ano: true, + marca: true, + modelo: true, + identificador: true, + assentos: true, + estado: true, + descricao: true, + valor: true, + currency: true, + tipo_aeronave: true, + created_at: true, + updated_at: true, + images: { select: publicCatalogImageSelect }, + specialist: { select: publicCatalogSpecialistSelect }, +} satisfies Prisma.AircraftSelect; diff --git a/backend/src/shared/utils/calendly-scheduling-capability.spec.ts b/backend/src/shared/utils/calendly-scheduling-capability.spec.ts new file mode 100644 index 00000000..9291f26a --- /dev/null +++ b/backend/src/shared/utils/calendly-scheduling-capability.spec.ts @@ -0,0 +1,36 @@ +import { isCalendlySchedulingAvailable } from './calendly-scheduling-capability'; + +describe('isCalendlySchedulingAvailable', () => { + it.each([ + 'https://calendly.com/especialista/reuniao', + 'https://www.calendly.com/a', + 'https://CALENDLY.COM/a', + ])('aceita uma conexão ativa com URL Calendly HTTPS: %s', (calendlyUrl) => { + expect( + isCalendlySchedulingAvailable({ calendlyUrl, connectionActive: true }), + ).toBe(true); + }); + + it.each([ + null, + '', + 'http://calendly.com/a', + 'https://evilcalendly.com/a', + 'https://calendly.com.evil.test/a', + 'https://calendly.com@evil.test/a', + 'not-a-url', + ])('rejeita URL inválida ou ausente: %s', (calendlyUrl) => { + expect( + isCalendlySchedulingAvailable({ calendlyUrl, connectionActive: true }), + ).toBe(false); + }); + + it('não permite agendamento com conexão inativa', () => { + expect( + isCalendlySchedulingAvailable({ + calendlyUrl: 'https://calendly.com/a', + connectionActive: false, + }), + ).toBe(false); + }); +}); diff --git a/backend/src/shared/utils/calendly-scheduling-capability.ts b/backend/src/shared/utils/calendly-scheduling-capability.ts new file mode 100644 index 00000000..e9448e8c --- /dev/null +++ b/backend/src/shared/utils/calendly-scheduling-capability.ts @@ -0,0 +1,17 @@ +export function isCalendlySchedulingAvailable(input: { + calendlyUrl: string | null; + connectionActive: boolean; +}): boolean { + if (!input.connectionActive || !input.calendlyUrl) return false; + + try { + const url = new URL(input.calendlyUrl); + const host = url.hostname.toLowerCase(); + return ( + url.protocol === 'https:' && + (host === 'calendly.com' || host.endsWith('.calendly.com')) + ); + } catch { + return false; + } +} diff --git a/backend/test/admin-specialist-journey.e2e-spec.ts b/backend/test/admin-specialist-journey.e2e-spec.ts new file mode 100644 index 00000000..1be3102f --- /dev/null +++ b/backend/test/admin-specialist-journey.e2e-spec.ts @@ -0,0 +1,588 @@ +import type { INestApplication } from '@nestjs/common'; +import type { PrismaClient } from '@prisma/client'; +import * as bcrypt from 'bcrypt'; +import cookieParser from 'cookie-parser'; +import request from 'supertest'; +import { randomUUID } from 'node:crypto'; + +const databaseUrl = process.env.ADMIN_SPECIALIST_E2E_DATABASE_URL; +const describePostgres = databaseUrl ? describe : describe.skip; + +const ids = { + admin: 'a11d0000-0000-4000-8000-000000000001', + specialistA: 'a11d0000-0000-4000-8000-000000000002', + specialistB: 'a11d0000-0000-4000-8000-000000000003', + customer: 'a11d0000-0000-4000-8000-000000000004', +}; +const password = 'admin-specialist-e2e-password'; +const credentials = { + admin: { email: 'admin-journey@example.test', password }, + specialistA: { email: 'specialist-a-journey@example.test', password }, + specialistB: { email: 'specialist-b-journey@example.test', password }, + customer: { email: 'customer-journey@example.test', password }, +}; + +describePostgres('ADMIN acting for SPECIALIST journey (HTTP + PostgreSQL)', () => { + let app: INestApplication; + let prisma: PrismaClient; + let adminToken: string; + let specialistAToken: string; + let customerToken: string; + let productId: string; + let processId: string; + const envelopes = new Map< + string, + { processId: string; requestFingerprint: string; status: string } + >(); + const previousEnv = new Map(); + + function target(id = ids.specialistA) { + return { target_specialist_id: id }; + } + + async function cleanup() { + if (!prisma) return; + const userIds = Object.values(ids); + const processes = await prisma.process.findMany({ + where: { + OR: [ + { client_id: ids.customer }, + { specialist_id: { in: [ids.specialistA, ids.specialistB] } }, + ], + }, + select: { id: true }, + }); + const processIds = processes.map(({ id }) => id); + await prisma.process.updateMany({ + where: { id: { in: processIds } }, + data: { active_contract_id: null, accepted_proposal_id: null }, + }); + await prisma.contract.deleteMany({ where: { process_id: { in: processIds } } }); + await prisma.negotiationProposal.deleteMany({ + where: { process_id: { in: processIds } }, + }); + await prisma.meetingSession.deleteMany({ + where: { process_id: { in: processIds } }, + }); + await prisma.processStatusHistory.deleteMany({ + where: { processId: { in: processIds } }, + }); + await prisma.processRejection.deleteMany({ + where: { process_id: { in: processIds } }, + }); + await prisma.process.deleteMany({ where: { id: { in: processIds } } }); + await prisma.appointment.deleteMany({ + where: { + OR: [ + { client_id: ids.customer }, + { specialist_id: { in: [ids.specialistA, ids.specialistB] } }, + ], + }, + }); + await prisma.car.deleteMany({ + where: { specialist_id: { in: [ids.specialistA, ids.specialistB] } }, + }); + await prisma.refreshToken.deleteMany({ where: { user_id: { in: userIds } } }); + await prisma.$executeRaw` + DELETE FROM "DelegatedActionAudit" + WHERE "actor_id" IN (${ids.admin}::uuid, ${ids.specialistA}::uuid, + ${ids.specialistB}::uuid, ${ids.customer}::uuid) + OR "represented_specialist_id" IN + (${ids.specialistA}::uuid, ${ids.specialistB}::uuid) + `; + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + } + + beforeAll(async () => { + const parsed = new URL(databaseUrl!); + if ( + !['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname) || + parsed.pathname.slice(1) !== 'admin_specialist_test' + ) { + throw new Error( + 'ADMIN_SPECIALIST_E2E_DATABASE_URL must point to loopback/admin_specialist_test', + ); + } + for (const [key, value] of Object.entries({ + DATABASE_URL: databaseUrl, + DIRECT_URL: databaseUrl, + NOTIFICATIONS_ENABLED: 'false', + MEETING_PROVIDER: 'JITSI', + JWT_SECRET_ACCESS: 'local-admin-journey-access-secret', + JWT_SECRET_REFRESH: 'local-admin-journey-refresh-secret', + JWT_SECRET_REFERRAL: 'local-admin-journey-referral-secret', + JWT_SECRET_ADVISOR: 'local-admin-journey-advisor-secret', + })) { + previousEnv.set(key, process.env[key]); + process.env[key] = value; + } + + const { PrismaClient } = + require('@prisma/client') as typeof import('@prisma/client'); + prisma = new PrismaClient({ datasources: { db: { url: databaseUrl! } } }); + await prisma.$connect(); + await cleanup(); + const hash = await bcrypt.hash(password, 4); + await prisma.user.createMany({ + data: [ + { + id: ids.admin, + name: 'Admin', + surname: 'Journey', + email: credentials.admin.email, + password_hash: hash, + rg: '99110000001', + role: 'ADMIN', + is_active: true, + }, + { + id: ids.specialistA, + name: 'Specialist', + surname: 'Alpha', + email: credentials.specialistA.email, + password_hash: hash, + rg: '99110000002', + role: 'SPECIALIST', + speciality: 'CAR', + commission_rate: 70, + is_active: true, + }, + { + id: ids.specialistB, + name: 'Specialist', + surname: 'Beta', + email: credentials.specialistB.email, + password_hash: hash, + rg: '99110000003', + role: 'SPECIALIST', + speciality: 'CAR', + commission_rate: 60, + is_active: true, + }, + { + id: ids.customer, + name: 'Customer', + surname: 'Journey', + email: credentials.customer.email, + password_hash: hash, + rg: '99110000004', + role: 'CUSTOMER', + is_active: true, + }, + ], + }); + + const { AppModule } = + require('../src/app.module') as typeof import('../src/app.module'); + const { Test } = + require('@nestjs/testing') as typeof import('@nestjs/testing'); + const { ClassSerializerInterceptor, ValidationPipe } = + require('@nestjs/common') as typeof import('@nestjs/common'); + const { Reflector } = + require('@nestjs/core') as typeof import('@nestjs/core'); + const { PrismaService } = + require('../src/prisma/prisma.service') as typeof import('../src/prisma/prisma.service'); + const { S3Service } = + require('../src/aws/s3.service') as typeof import('../src/aws/s3.service'); + const { SesService } = + require('../src/aws/ses.service') as typeof import('../src/aws/ses.service'); + const { NotificationService } = + require('../src/features/notifications/notification.service') as typeof import('../src/features/notifications/notification.service'); + const { ProductImportJobsService } = + require('../src/features/product-import-jobs/product-import-jobs.service') as typeof import('../src/features/product-import-jobs/product-import-jobs.service'); + const { ConsultantInviteJobsService } = + require('../src/features/office/consultant-invite-jobs.service') as typeof import('../src/features/office/consultant-invite-jobs.service'); + const { ClientInviteJobsService } = + require('../src/features/consultant/client-invite-jobs.service') as typeof import('../src/features/consultant/client-invite-jobs.service'); + const { MeetingReminderService } = + require('../src/features/meetings/meeting-reminder.service') as typeof import('../src/features/meetings/meeting-reminder.service'); + const { DocuSignService } = + require('../src/providers/docusign/docusign.service') as typeof import('../src/providers/docusign/docusign.service'); + const { DocuSignClient } = + require('../src/providers/docusign/docusign.client') as typeof import('../src/providers/docusign/docusign.client'); + const { PlatformCompanyService } = + require('../src/features/platform-company/platform-company.service') as typeof import('../src/features/platform-company/platform-company.service'); + const { RateLimitGuard } = + require('../src/shared/guards/rate-limit.guard') as typeof import('../src/shared/guards/rate-limit.guard'); + const { localizedValidationExceptionFactory } = + require('../src/shared/validation/localized-validation-exception') as typeof import('../src/shared/validation/localized-validation-exception'); + + const notifications = new Proxy( + {}, + { + get: (_target, property) => + property === 'then' ? undefined : async () => undefined, + }, + ); + const docusign = { + createEnvelopePreview: async (params: any) => { + const envelopeId = randomUUID(); + envelopes.set(envelopeId, { + processId: params.processId, + requestFingerprint: params.requestFingerprint, + status: 'created', + }); + params.onEnvelopeCreated?.(envelopeId); + return { + envelopeId, + previewUrl: `https://docusign.example.test/${envelopeId}`, + expiresAt: '2099-01-01T00:00:00.000Z', + }; + }, + getEnvelopeProcessId: async (id: string) => envelopes.get(id)?.processId, + getEnvelopeRequestFingerprint: async (id: string) => + envelopes.get(id)?.requestFingerprint, + getEnvelopeStatus: async (id: string) => ({ + envelopeId: id, + status: envelopes.get(id)?.status ?? 'created', + }), + sendDraftEnvelope: async (id: string) => { + const envelope = envelopes.get(id)!; + envelope.status = 'sent'; + return { envelopeId: id, status: 'sent' }; + }, + voidDraftEnvelope: async (id: string) => { + const envelope = envelopes.get(id); + if (envelope) envelope.status = 'voided'; + }, + }; + const module = await Test.createTestingModule({ imports: [AppModule] }) + .overrideProvider(PrismaService) + .useValue(prisma) + .overrideProvider(S3Service) + .useValue({ getSignedUrl: async (key: string) => key }) + .overrideProvider(SesService) + .useValue({}) + .overrideProvider(NotificationService) + .useValue(notifications) + .overrideProvider(ProductImportJobsService) + .useValue({}) + .overrideProvider(ConsultantInviteJobsService) + .useValue({}) + .overrideProvider(ClientInviteJobsService) + .useValue({}) + .overrideProvider(MeetingReminderService) + .useValue({}) + .overrideProvider(DocuSignService) + .useValue(docusign) + .overrideProvider(DocuSignClient) + .useValue({}) + .overrideProvider(PlatformCompanyService) + .useValue({ findOne: async () => ({ default_commission_rate: 10 }) }) + .overrideGuard(RateLimitGuard) + .useValue({ canActivate: () => true }) + .compile(); + + app = module.createNestApplication(); + app.use(cookieParser()); + app.setGlobalPrefix('api'); + app.useGlobalPipes( + new ValidationPipe({ + whitelist: true, + forbidNonWhitelisted: true, + transform: true, + exceptionFactory: localizedValidationExceptionFactory, + }), + ); + app.useGlobalInterceptors( + new ClassSerializerInterceptor(app.get(Reflector)), + ); + app.useLogger(false); + await app.init(); + + const login = async (credential: { email: string; password: string }) => { + const response = await request(app.getHttpServer()) + .post('/api/auth/login') + .send(credential) + .expect(201); + return response.body.data.access_token as string; + }; + [adminToken, specialistAToken, customerToken] = await Promise.all([ + login(credentials.admin), + login(credentials.specialistA), + login(credentials.customer), + ]); + }, 60_000); + + afterAll(async () => { + try { + await app?.close(); + await cleanup(); + } finally { + await prisma?.$disconnect(); + for (const [key, value] of previousEnv) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + } + }, 30_000); + + it('keeps A as executor, S as owner and blocks a mismatched represented specialist', async () => { + const created = await request(app.getHttpServer()) + .post('/api/cars') + .auth(adminToken, { type: 'bearer' }) + .send({ + specialist_id: ids.specialistA, + marca: 'Admin Journey E2E', + modelo: 'Owner Alpha', + identificador: 'admin-journey-owner-alpha', + valor: 100000, + currency: 'BRL', + estado: 'SP', + ano: 2026, + }) + .expect(201); + productId = created.body.id; + expect(created.body.specialist_id).toBe(ids.specialistA); + const inactiveProduct = await prisma.car.create({ + data: { + specialist_id: ids.specialistA, + marca: 'Admin Journey E2E', + modelo: 'Inactive visible to admin', + identificador: 'admin-journey-inactive-alpha', + valor: 80000, + currency: 'BRL', + estado: 'SP', + ano: 2025, + is_active: false, + }, + }); + const adminCatalog = await request(app.getHttpServer()) + .get('/api/cars/admin/all') + .query({ ...target(), page: 1, perPage: 20 }) + .auth(adminToken, { type: 'bearer' }) + .expect(200); + expect(adminCatalog.body.data).toEqual( + expect.arrayContaining([ + expect.objectContaining({ id: productId, is_active: true }), + expect.objectContaining({ id: inactiveProduct.id, is_active: false }), + ]), + ); + const otherCatalog = await request(app.getHttpServer()) + .get('/api/cars/admin/all') + .query({ ...target(ids.specialistB), page: 1, perPage: 20 }) + .auth(adminToken, { type: 'bearer' }) + .expect(200); + expect(otherCatalog.body.data).toEqual([]); + + await request(app.getHttpServer()) + .patch(`/api/cars/${productId}`) + .query(target(ids.specialistB)) + .auth(adminToken, { type: 'bearer' }) + .send({ modelo: 'Must not change' }) + .expect(403); + const customerMutation = await request(app.getHttpServer()) + .patch(`/api/cars/${productId}`) + .query(target()) + .auth(customerToken, { type: 'bearer' }) + .send({ modelo: 'Customer must not change' }); + expect([401, 403]).toContain(customerMutation.status); + expect((await prisma.car.findUniqueOrThrow({ where: { id: productId } })).modelo) + .toBe('Owner Alpha'); + + const audits = await prisma.$queryRaw< + Array<{ actor_id: string; represented_specialist_id: string }> + >`SELECT "actor_id", "represented_specialist_id" + FROM "DelegatedActionAudit" WHERE "resource_id" = ${productId}`; + expect(audits).toEqual([ + { + actor_id: ids.admin, + represented_specialist_id: ids.specialistA, + }, + ]); + }); + + it('runs process, appointment, concurrent meeting/proposal and simulated DocuSign end to end', async () => { + const processResponse = await request(app.getHttpServer()) + .post('/api/processes') + .auth(adminToken, { type: 'bearer' }) + .send({ + client_id: ids.customer, + specialist_id: ids.specialistA, + product_type: 'CAR', + product_id: productId, + notes: 'HTTP E2E admin journey', + }) + .expect(201); + processId = processResponse.body.data.id; + const storedProcess = await prisma.process.findUniqueOrThrow({ + where: { id: processId }, + include: { appointment: true }, + }); + expect(storedProcess.specialist_id).toBe(ids.specialistA); + expect(storedProcess.appointment).toMatchObject({ + status: 'PENDING', + scheduling_method: 'EMAIL', + }); + + await request(app.getHttpServer()) + .get(`/api/processes/${processId}`) + .query(target(ids.specialistB)) + .auth(adminToken, { type: 'bearer' }) + .expect(403); + await request(app.getHttpServer()) + .post(`/api/processes/${processId}/confirm-appointment`) + .query(target()) + .auth(adminToken, { type: 'bearer' }) + .send({ appointment_datetime: '2099-10-23T17:30:00.000Z' }) + .expect(201); + expect( + (await prisma.appointment.findUniqueOrThrow({ + where: { id: storedProcess.appointment_id! }, + })).confirmed_by_id, + ).toBe(ids.admin); + + await request(app.getHttpServer()) + .post(`/api/meetings/process/${processId}/start`) + .query(target()) + .auth(adminToken, { type: 'bearer' }) + .send({}) + .expect(201); + expect( + (await prisma.meetingSession.findUniqueOrThrow({ + where: { process_id: processId }, + })).started_by_id, + ).toBe(ids.admin); + const endResults = await Promise.all( + [1, 2].map(() => + request(app.getHttpServer()) + .post(`/api/meetings/process/${processId}/end`) + .query(target()) + .auth(adminToken, { type: 'bearer' }), + ), + ); + expect(endResults.map(({ status }) => status)).toEqual([201, 201]); + expect( + endResults.map(({ body }) => body.data.alreadyEnded).sort(), + ).toEqual([false, true]); + + const conversation = await request(app.getHttpServer()) + .post(`/api/meetings/process/${processId}/conversation-done`) + .query(target()) + .auth(adminToken, { type: 'bearer' }) + .expect(201); + expect(conversation.body.data.processTransition.status).toBe('NEGOTIATION'); + + const proposalResults = await Promise.all( + [90000, 91000].map((value) => + request(app.getHttpServer()) + .post('/api/proposals') + .query(target()) + .auth(adminToken, { type: 'bearer' }) + .send({ process_id: processId, proposed_value: value }), + ), + ); + expect(proposalResults.map(({ status }) => status).sort()).toEqual([ + 201, 400, + ]); + await expect( + prisma.negotiationProposal.count({ + where: { process_id: processId, status: 'PENDING' }, + }), + ).resolves.toBe(1); + const proposal = proposalResults.find(({ status }) => status === 201)!.body + .data; + expect(proposal.proposed_by.id).toBe(ids.specialistA); + await request(app.getHttpServer()) + .patch(`/api/proposals/${proposal.id}/accept`) + .auth(customerToken, { type: 'bearer' }) + .send({ message: 'Aceita no E2E' }) + .expect(200); + + const accepted = await prisma.negotiationProposal.findUniqueOrThrow({ + where: { id: proposal.id }, + }); + const contractDto = { + operation_id: randomUUID(), + return_url: 'http://localhost/admin/journey/contracts/preview-callback', + process_id: processId, + template_id: 'admin-journey-template', + seller_name: 'Seller Distinct', + seller_email: 'seller-distinct@example.test', + buyer_name: 'Customer Journey', + buyer_email: credentials.customer.email, + specialist_name: 'Specialist Alpha', + specialist_email: credentials.specialistA.email, + vehicle_model: 'Owner Alpha', + vehicle_year: '2026', + vehicle_price: Number(accepted.proposed_value), + payment_seller_value: Number(accepted.proposed_value) * 0.9, + total_commission_rate: 10, + city: 'Sao Paulo', + description: 'Approved E2E legal content', + }; + await request(app.getHttpServer()) + .post('/api/contracts/generate') + .query(target()) + .auth(adminToken, { type: 'bearer' }) + .send(contractDto) + .expect(401); + await expect( + prisma.contract.count({ where: { process_id: processId } }), + ).resolves.toBe(0); + + const preview = await request(app.getHttpServer()) + .post('/api/contracts/preview') + .query(target()) + .auth(adminToken, { type: 'bearer' }) + .send(contractDto) + .expect(201); + const envelopeId = preview.body.data.envelope_id; + await request(app.getHttpServer()) + .post(`/api/contracts/send/${envelopeId}`) + .query(target()) + .auth(adminToken, { type: 'bearer' }) + .send(contractDto) + .expect(201); + + const contract = await prisma.contract.findFirstOrThrow({ + where: { process_id: processId }, + }); + expect(contract).toMatchObject({ + uploaded_by_id: ids.admin, + provider_id: envelopeId, + status: 'PENDING', + }); + expect(envelopes.get(envelopeId)?.status).toBe('sent'); + const auditRows = await prisma.$queryRaw>` + SELECT "action" FROM "DelegatedActionAudit" + WHERE "actor_id" = ${ids.admin}::uuid + AND "represented_specialist_id" = ${ids.specialistA}::uuid + AND "resource_id" IN (${processId}, ${contract.id}, ${envelopeId}) + ORDER BY "created_at" ASC + `; + expect(auditRows.map(({ action }) => action)).toEqual( + expect.arrayContaining([ + 'PROCESS_CREATE', + 'CONTRACT_PREVIEW', + 'CONTRACT_SEND', + ]), + ); + const timeline = await request(app.getHttpServer()) + .get(`/api/processes/${processId}/admin-timeline`) + .query(target()) + .auth(adminToken, { type: 'bearer' }) + .expect(200); + expect(timeline.body.data).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + action: 'CONTRACT_SEND', + actor: expect.objectContaining({ id: ids.admin, role: 'ADMIN' }), + representedSpecialistId: ids.specialistA, + }), + ]), + ); + await request(app.getHttpServer()) + .get(`/api/processes/${processId}/admin-timeline`) + .query(target(ids.specialistB)) + .auth(adminToken, { type: 'bearer' }) + .expect(403); + + const specialistOwnList = await request(app.getHttpServer()) + .get(`/api/processes/specialist/${ids.specialistA}`) + .auth(specialistAToken, { type: 'bearer' }) + .expect(200); + expect(specialistOwnList.body.data.some(({ id }: any) => id === processId)) + .toBe(true); + }, 30_000); +}); diff --git a/backend/test/app.e2e-spec.ts b/backend/test/app.e2e-spec.ts index 36852c54..6c35b2d8 100644 --- a/backend/test/app.e2e-spec.ts +++ b/backend/test/app.e2e-spec.ts @@ -3,23 +3,41 @@ import { INestApplication } from '@nestjs/common'; import request from 'supertest'; import { App } from 'supertest/types'; import { AppModule } from './../src/app.module'; +import { RateLimitGuard } from '../src/shared/guards/rate-limit.guard'; -describe('AppController (e2e)', () => { +describe('HealthController (e2e)', () => { let app: INestApplication; - beforeEach(async () => { + beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], - }).compile(); + }) + .overrideGuard(RateLimitGuard) + .useValue({ canActivate: () => true }) + .compile(); app = moduleFixture.createNestApplication(); + app.setGlobalPrefix('api'); await app.init(); }); - it('/ (GET)', () => { - return request(app.getHttpServer()) - .get('/') - .expect(200) - .expect('Hello World!'); + afterAll(async () => { + await app?.close(); + }); + + it('/api/health (GET)', async () => { + const response = await request(app.getHttpServer()) + .get('/api/health') + .expect(200); + + expect(response.body).toEqual( + expect.objectContaining({ + status: 'ok', + timestamp: expect.any(String), + service: 'bmf-lux-brokerage-backend', + environment: expect.any(String), + }), + ); + expect(Number.isNaN(Date.parse(response.body.timestamp))).toBe(false); }); }); diff --git a/backend/test/email-scheduling.e2e-spec.ts b/backend/test/email-scheduling.e2e-spec.ts new file mode 100644 index 00000000..17e59f2b --- /dev/null +++ b/backend/test/email-scheduling.e2e-spec.ts @@ -0,0 +1,882 @@ +import type { INestApplication } from '@nestjs/common'; +import type { PrismaClient } from '@prisma/client'; +import cookieParser from 'cookie-parser'; +import request from 'supertest'; +import { + cleanupEmailSchedulingFixtures, + emailSchedulingFixtures, + readEmailSchedulingE2EConfig, + seedEmailSchedulingFixtures, +} from '../prisma/seed-email-scheduling-e2e'; +import { + getSanitizeCallCount, + resetSanitizeCallCount, +} from './mocks/isomorphic-dompurify'; + +const fixture = emailSchedulingFixtures('http'); +const proposedIso = '2099-10-20T17:30:00.000Z'; +const changedIso = '2099-10-21T19:00:00.000Z'; +const secondIso = '2099-10-23T17:30:00.000Z'; +const checkKeys = [ + 'exists', + 'appointment_id', + 'process_id', + 'appointment_status', + 'scheduling_method', + 'appointment_datetime', + 'specialist_contact_email', +]; + +// A dedicated URL opts in to the real PostgreSQL gate. Ordinary e2e discovery +// never falls back to a developer's DATABASE_URL or the application's .env. +const describeHttp = process.env.EMAIL_SCHEDULING_E2E_DATABASE_URL + ? describe + : describe.skip; + +describe('email scheduling fixture safety', () => { + const validEnv = { + EMAIL_SCHEDULING_E2E_DATABASE_URL: + 'postgresql://test:test@127.0.0.1:5432/email_scheduling_e2e', + EMAIL_SCHEDULING_E2E_CUSTOMER_EMAIL: 'customer@example.test', + EMAIL_SCHEDULING_E2E_CUSTOMER_PASSWORD: 'customer-test-password', + EMAIL_SCHEDULING_E2E_SPECIALIST_EMAIL: 'specialist@example.test', + EMAIL_SCHEDULING_E2E_SPECIALIST_PASSWORD: 'specialist-test-password', + EMAIL_SCHEDULING_E2E_OUTSIDER_EMAIL: 'outsider@example.test', + EMAIL_SCHEDULING_E2E_OUTSIDER_PASSWORD: 'outsider-test-password', + }; + + it('uses separate deterministic base IDs for browser seed and HTTP fixtures', () => { + const browser = emailSchedulingFixtures('browser'); + const baseIds = (items: typeof fixture) => [ + ...items.users.map(({ id }) => id), + ...items.cars.map(({ id }) => id), + ]; + expect(new Set([...baseIds(browser), ...baseIds(fixture)]).size).toBe(10); + expect(emailSchedulingFixtures('http')).toEqual(fixture); + }); + + it.each([ + undefined, + 'not-a-url', + 'postgresql://test:test@production.example.test:5432/database', + 'mysql://test:test@localhost:3306/database', + 'postgresql://test:test@localhost:5432/bmfluxdb', + ])('rejects a missing, malformed or nonlocal database URL', (databaseUrl) => { + expect(() => + readEmailSchedulingE2EConfig({ + ...validEnv, + EMAIL_SCHEDULING_E2E_DATABASE_URL: databaseUrl, + }), + ).toThrow(/EMAIL_SCHEDULING_E2E_DATABASE_URL/); + }); + + it('requires environment credentials and only reserved .test recipients', () => { + expect(() => + readEmailSchedulingE2EConfig({ + ...validEnv, + EMAIL_SCHEDULING_E2E_CUSTOMER_PASSWORD: undefined, + }), + ).toThrow(/EMAIL_SCHEDULING_E2E_CUSTOMER_PASSWORD/); + expect(() => + readEmailSchedulingE2EConfig({ + ...validEnv, + EMAIL_SCHEDULING_E2E_CUSTOMER_EMAIL: 'customer@example.com', + }), + ).toThrow(/EMAIL_SCHEDULING_E2E_CUSTOMER_EMAIL/); + expect(() => + readEmailSchedulingE2EConfig({ + ...validEnv, + EMAIL_SCHEDULING_E2E_OUTSIDER_EMAIL: + validEnv.EMAIL_SCHEDULING_E2E_CUSTOMER_EMAIL, + }), + ).toThrow(/distinct/i); + }); + + it('normalizes addresses and derives a separate HTTP login namespace', () => { + const config = readEmailSchedulingE2EConfig( + { + ...validEnv, + EMAIL_SCHEDULING_E2E_CUSTOMER_EMAIL: ' CUSTOMER@EXAMPLE.TEST ', + }, + 'http', + ); + expect(config.credentials.customer.email).toBe( + 'customer+http@example.test', + ); + expect(config.namespace).toBe('http'); + }); + + it.each(['browser', 'http'] as const)( + 'rejects collisions across both email namespaces before seeding %s', + (namespace) => { + expect(() => + readEmailSchedulingE2EConfig( + { + ...validEnv, + EMAIL_SCHEDULING_E2E_SPECIALIST_EMAIL: + ' CUSTOMER+HTTP@EXAMPLE.TEST ', + }, + namespace, + ), + ).toThrow(/distinct/i); + }, + ); + + it('keeps all six normalized browser and HTTP addresses distinct', () => { + const emails = (['browser', 'http'] as const).flatMap((namespace) => + Object.values( + readEmailSchedulingE2EConfig(validEnv, namespace).credentials, + ).map(({ email }) => email), + ); + expect(new Set(emails).size).toBe(6); + }); + + it('fails closed if the out-of-scope SVG sanitizer boundary is called', () => { + const boundary = + require('isomorphic-dompurify') as typeof import('./mocks/isomorphic-dompurify'); + boundary.resetSanitizeCallCount(); + try { + expect(() => boundary.default.sanitize('')).toThrow( + /SVG sanitization is outside the email scheduling E2E gate/, + ); + expect(boundary.getSanitizeCallCount()).toBe(1); + } finally { + boundary.resetSanitizeCallCount(); + } + }); +}); + +describeHttp('no-Calendly email scheduling (HTTP + PostgreSQL)', () => { + let app: INestApplication | undefined; + let prisma: PrismaClient | undefined; + let config: ReturnType; + let fixtureReady = false; + let customerToken: string; + let specialistToken: string; + let outsiderToken: string; + const oldDatabaseUrl = process.env.DATABASE_URL; + const oldNotificationsEnabled = process.env.NOTIFICATIONS_ENABLED; + + beforeAll(async () => { + config = readEmailSchedulingE2EConfig(process.env, 'http'); + for (const name of [ + 'JWT_SECRET_ACCESS', + 'JWT_SECRET_REFRESH', + 'JWT_SECRET_REFERRAL', + 'JWT_SECRET_ADVISOR', + ]) { + if (!process.env[name]?.trim()) throw new Error(`Missing ${name}`); + } + process.env.DATABASE_URL = config.databaseUrl; + process.env.NOTIFICATIONS_ENABLED = 'false'; + resetSanitizeCallCount(); + // Resolve the complete application graph before connecting or seeding. + // External delivery and unrelated background jobs are outside this gate. + const { AppModule } = + require('../src/app.module') as typeof import('../src/app.module'); + expect(getSanitizeCallCount()).toBe(0); + const { PrismaClient } = + require('@prisma/client') as typeof import('@prisma/client'); + prisma = new PrismaClient({ + datasources: { db: { url: config.databaseUrl } }, + }); + await prisma.$connect(); + await seedEmailSchedulingFixtures(prisma, config, fixture); + fixtureReady = true; + await seedEmailSchedulingFixtures(prisma, config, fixture); + expect( + await prisma.user.count({ + where: { id: { in: fixture.users.map(({ id }) => id) } }, + }), + ).toBe(3); + expect( + await prisma.car.count({ + where: { id: { in: fixture.cars.map(({ id }) => id) } }, + }), + ).toBe(2); + + const { Test } = + require('@nestjs/testing') as typeof import('@nestjs/testing'); + const { ClassSerializerInterceptor, ValidationPipe } = + require('@nestjs/common') as typeof import('@nestjs/common'); + const { Reflector } = + require('@nestjs/core') as typeof import('@nestjs/core'); + const { PrismaService } = + require('../src/prisma/prisma.service') as typeof import('../src/prisma/prisma.service'); + const { S3Service } = + require('../src/aws/s3.service') as typeof import('../src/aws/s3.service'); + const { SesService } = + require('../src/aws/ses.service') as typeof import('../src/aws/ses.service'); + const { DocuSignClient } = + require('../src/providers/docusign/docusign.client') as typeof import('../src/providers/docusign/docusign.client'); + const { NotificationService } = + require('../src/features/notifications/notification.service') as typeof import('../src/features/notifications/notification.service'); + const { RateLimitGuard } = + require('../src/shared/guards/rate-limit.guard') as typeof import('../src/shared/guards/rate-limit.guard'); + const { ProductImportJobsService } = + require('../src/features/product-import-jobs/product-import-jobs.service') as typeof import('../src/features/product-import-jobs/product-import-jobs.service'); + const { ConsultantInviteJobsService } = + require('../src/features/office/consultant-invite-jobs.service') as typeof import('../src/features/office/consultant-invite-jobs.service'); + const { ClientInviteJobsService } = + require('../src/features/consultant/client-invite-jobs.service') as typeof import('../src/features/consultant/client-invite-jobs.service'); + const { MeetingReminderService } = + require('../src/features/meetings/meeting-reminder.service') as typeof import('../src/features/meetings/meeting-reminder.service'); + const { localizedValidationExceptionFactory } = + require('../src/shared/validation/localized-validation-exception') as typeof import('../src/shared/validation/localized-validation-exception'); + const module = await Test.createTestingModule({ + imports: [AppModule], + }) + .overrideProvider(PrismaService) + .useValue(prisma) + .overrideProvider(S3Service) + .useValue({}) + .overrideProvider(SesService) + .useValue({}) + .overrideProvider(DocuSignClient) + .useValue({}) + .overrideProvider(NotificationService) + .useValue({ sendAppointmentConfirmedEmail: async () => undefined }) + .overrideProvider(ProductImportJobsService) + .useValue({}) + .overrideProvider(ConsultantInviteJobsService) + .useValue({}) + .overrideProvider(ClientInviteJobsService) + .useValue({}) + .overrideProvider(MeetingReminderService) + .useValue({}) + // RateLimitGuard owns an interval with no destruction hook. Its login + // throttling is outside this gate; authentication itself is never stubbed. + .overrideGuard(RateLimitGuard) + .useValue({ canActivate: () => true }) + .compile(); + app = module.createNestApplication(); + app.use(cookieParser()); + app.setGlobalPrefix('api'); + app.useGlobalPipes( + new ValidationPipe({ + whitelist: true, + forbidNonWhitelisted: true, + transform: true, + exceptionFactory: localizedValidationExceptionFactory, + }), + ); + app.useGlobalInterceptors( + new ClassSerializerInterceptor(app.get(Reflector)), + ); + app.useLogger(false); + await app.init(); + expect(getSanitizeCallCount()).toBe(0); + + [customerToken, specialistToken, outsiderToken] = await Promise.all([ + login('customer'), + login('specialist'), + login('outsider'), + ]); + }, 30_000); + + afterAll(async () => { + try { + await app?.close(); + if (prisma && fixtureReady) { + await cleanupEmailSchedulingFixtures(prisma, fixture); + expect( + await prisma.appointment.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(0); + expect( + await prisma.process.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(0); + } + } finally { + await prisma?.$disconnect(); + if (oldDatabaseUrl === undefined) delete process.env.DATABASE_URL; + else process.env.DATABASE_URL = oldDatabaseUrl; + if (oldNotificationsEnabled === undefined) + delete process.env.NOTIFICATIONS_ENABLED; + else process.env.NOTIFICATIONS_ENABLED = oldNotificationsEnabled; + } + expect(getSanitizeCallCount()).toBe(0); + }); + + async function login(actor: 'customer' | 'specialist' | 'outsider') { + const response = await request(app!.getHttpServer()) + .post('/api/auth/login') + .send(config.credentials[actor]) + .expect(201); + expect(response.body.success).toBe(true); + expect(typeof response.body.data.access_token).toBe('string'); + expect(response.body.data.access_token.length > 0).toBe(true); + expect(response.body.data.user.id).toBe( + fixture.users.find((user) => user.actor === actor)!.id, + ); + expect( + Object.prototype.hasOwnProperty.call( + response.body.data.user, + 'password_hash', + ), + ).toBe(false); + const cookies = response.headers['set-cookie'] as unknown as + | string[] + | undefined; + expect( + Array.isArray(cookies) && + cookies.some((cookie) => cookie.startsWith('refreshToken=')), + ).toBe(true); + return response.body.data.access_token as string; + } + + function checkQuery(productId: string) { + return { + specialist_id: fixture.users[1].id, + product_type: 'CAR', + product_id: productId, + }; + } + + function pendingBody(productId: string, datetime = proposedIso) { + return { + client_id: fixture.users[0].id, + ...checkQuery(productId), + scheduling_method: 'EMAIL', + appointment_datetime: datetime, + }; + } + + function assertNoPrivateFields(value: unknown) { + const forbidden = new Set([ + 'cpf', + 'rg', + 'password_hash', + 'civil_state', + 'bank', + 'agency', + 'checking_account', + 'calendly_connection', + 'calendly_user_uri', + 'calendly_organization_uri', + 'access_token', + 'refresh_token', + ]); + const visit = (item: unknown) => { + if (!item || typeof item !== 'object') return; + for (const [key, child] of Object.entries(item)) { + expect(forbidden.has(key)).toBe(false); + visit(child); + } + }; + visit(value); + } + + function assertNoContacts(value: unknown) { + assertNoPrivateFields(value); + const serialized = JSON.stringify(value); + for (const actor of ['customer', 'specialist', 'outsider'] as const) { + expect(serialized.includes(config.credentials[actor].email)).toBe(false); + } + for (const user of fixture.users) { + expect(serialized.includes(user.phone)).toBe(false); + } + } + + function assertOwnerScopedSpecialistEmail(value: unknown) { + assertNoPrivateFields(value); + const serialized = JSON.stringify(value); + expect(serialized.includes(config.credentials.specialist.email)).toBe(true); + expect(serialized.includes(config.credentials.outsider.email)).toBe(false); + for (const user of fixture.users) { + expect(serialized.includes(user.phone)).toBe(false); + } + } + + async function assertStoredState( + productId: string, + processId: string, + appointmentId: string, + status: 'PENDING' | 'SCHEDULED', + datetime: string, + ) { + const appointments = await prisma!.appointment.findMany({ + where: { + client_id: fixture.users[0].id, + specialist_id: fixture.users[1].id, + product_id: productId, + }, + }); + const processes = await prisma!.process.findMany({ + where: { + client_id: fixture.users[0].id, + specialist_id: fixture.users[1].id, + car_id: productId, + }, + include: { ProcessStatusHistory: { orderBy: { id: 'asc' } } }, + }); + expect(appointments).toHaveLength(1); + expect(processes).toHaveLength(1); + expect(appointments[0]).toMatchObject({ + id: appointmentId, + status, + scheduling_method: 'EMAIL', + appointment_datetime: new Date(datetime), + specialist_rescheduled_at: null, + specialist_rescheduled_from: null, + confirmed_by_id: status === 'SCHEDULED' ? fixture.users[1].id : null, + }); + expect(appointments[0].confirmed_at === null).toBe(status === 'PENDING'); + expect(processes[0]).toMatchObject({ + id: processId, + appointment_id: appointmentId, + status: 'SCHEDULING', + }); + expect(processes[0].ProcessStatusHistory).toHaveLength(1); + expect(processes[0].ProcessStatusHistory[0].status).toBe('SCHEDULING'); + return { appointment: appointments[0], process: processes[0] }; + } + + it('serves only the public business profile and blocks private profile IDOR', async () => { + const profile = await request(app!.getHttpServer()) + .get(`/api/specialists/${fixture.users[1].id}/public-profile`) + .expect(200); + expect(Object.keys(profile.body).sort()).toEqual( + [ + 'id', + 'name', + 'surname', + 'speciality', + 'calendly_url', + 'calendly_scheduling_available', + ].sort(), + ); + expect(profile.body).toMatchObject({ + id: fixture.users[1].id, + calendly_url: null, + calendly_scheduling_available: false, + }); + expect(profile.body).not.toHaveProperty('email'); + assertNoPrivateFields(profile.body); + expect(profile.body).not.toHaveProperty('phone'); + await request(app!.getHttpServer()) + .get(`/api/users/${fixture.users[0].id}`) + .expect(401); + const unchangedProfile = { + id: true, + name: true, + surname: true, + phone: true, + calendly_url: true, + updated_at: true, + } as const; + const before = await prisma!.user.findUniqueOrThrow({ + where: { id: fixture.users[0].id }, + select: unchangedProfile, + }); + for (const token of [specialistToken, outsiderToken]) { + const deniedGet = await request(app!.getHttpServer()) + .get(`/api/users/${fixture.users[0].id}`) + .auth(token, { type: 'bearer' }) + .expect(403); + assertNoContacts(deniedGet.body); + const deniedPatch = await request(app!.getHttpServer()) + .patch(`/api/users/${fixture.users[0].id}`) + .auth(token, { type: 'bearer' }) + .send({ name: 'IDOR should never be written' }) + .expect(403); + assertNoContacts(deniedPatch.body); + } + expect( + await prisma!.user.findUniqueOrThrow({ + where: { id: before.id }, + select: unchangedProfile, + }), + ).toEqual(before); + await request(app!.getHttpServer()) + .get(`/api/users/${fixture.users[0].id}`) + .auth(customerToken, { type: 'bearer' }) + .expect(200); + }); + + it('derives own-check identity from JWT and rejects query identity/other roles', async () => { + const own = await request(app!.getHttpServer()) + .get('/api/appointments/check') + .auth(customerToken, { type: 'bearer' }) + .query(checkQuery(fixture.cars[0].id)) + .expect(200); + expect(own.body.data).toEqual({ exists: false }); + assertNoContacts(own.body); + await request(app!.getHttpServer()) + .get('/api/appointments/check') + .query(checkQuery(fixture.cars[0].id)) + .expect(401); + await request(app!.getHttpServer()) + .get('/api/appointments/check') + .auth(customerToken, { type: 'bearer' }) + .query({ + ...checkQuery(fixture.cars[0].id), + client_id: fixture.users[2].id, + }) + .expect(400); + for (const token of [specialistToken, outsiderToken]) { + const denied = await request(app!.getHttpServer()) + .get('/api/appointments/check') + .auth(token, { type: 'bearer' }) + .query(checkQuery(fixture.cars[0].id)) + .expect(403); + assertNoContacts(denied.body); + } + }); + + it('does not expose specialist contact through an unavailable CALENDLY path', async () => { + const { appointment_datetime: _date, ...withoutDate } = pendingBody( + fixture.cars[0].id, + ); + const calendly = await request(app!.getHttpServer()) + .post('/api/appointments/pending') + .auth(customerToken, { type: 'bearer' }) + .send({ ...withoutDate, scheduling_method: 'CALENDLY' }) + .expect(409); + + expect(calendly.body.error.code).toBe('CALENDLY_UNAVAILABLE'); + expect(JSON.stringify(calendly.body)).not.toContain( + 'specialist_contact_email', + ); + assertNoContacts(calendly.body); + }); + + it('rejects invalid creation, identity substitution and PLATFORM bypass without writes', async () => { + const body = pendingBody(fixture.cars[0].id); + const { appointment_datetime: _date, ...withoutDate } = body; + for (const invalid of [ + withoutDate, + { ...body, appointment_datetime: '2000-01-01T00:00:00.000Z' }, + { ...body, appointment_datetime: '2099-10-20T17:30' }, + ]) { + await request(app!.getHttpServer()) + .post('/api/appointments/pending') + .auth(customerToken, { type: 'bearer' }) + .send(invalid) + .expect(400); + } + for (const [token, requestBody] of [ + [customerToken, { ...body, client_id: fixture.users[2].id }], + [outsiderToken, body], + ] as const) { + const denied = await request(app!.getHttpServer()) + .post('/api/appointments/pending') + .auth(token, { type: 'bearer' }) + .send(requestBody) + .expect(403); + assertNoContacts(denied.body); + } + const { scheduling_method: _method, ...directBody } = body; + await request(app!.getHttpServer()) + .post('/api/appointments') + .auth(customerToken, { type: 'bearer' }) + .send(directBody) + .expect(403); + expect( + await prisma!.appointment.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(0); + expect( + await prisma!.process.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(0); + }); + + it('creates two dated proposals, projects assigned contacts, and confirms changed/unchanged times', async () => { + const created = [] as { + appointmentId: string; + processId: string; + productId: string; + }[]; + for (const car of fixture.cars) { + const response = await request(app!.getHttpServer()) + .post('/api/appointments/pending') + .auth(customerToken, { type: 'bearer' }) + .send(pendingBody(car.id)) + .expect(201); + expect(response.body.data).toMatchObject({ + id: expect.any(String), + process_id: expect.any(String), + status: 'PENDING', + scheduling_method: 'EMAIL', + appointment_datetime: proposedIso, + client: { id: fixture.users[0].id }, + specialist: { id: fixture.users[1].id }, + product: { id: car.id }, + specialist_contact_email: config.credentials.specialist.email, + }); + assertOwnerScopedSpecialistEmail(response.body); + created.push({ + appointmentId: response.body.data.id, + processId: response.body.data.process_id, + productId: car.id, + }); + await assertStoredState( + car.id, + response.body.data.process_id, + response.body.data.id, + 'PENDING', + proposedIso, + ); + const own = await request(app!.getHttpServer()) + .get('/api/appointments/check') + .auth(customerToken, { type: 'bearer' }) + .query(checkQuery(car.id)) + .expect(200); + expect(Object.keys(own.body.data).sort()).toEqual([...checkKeys].sort()); + expect(own.body.data).toEqual({ + exists: true, + appointment_id: response.body.data.id, + process_id: response.body.data.process_id, + appointment_status: 'PENDING', + scheduling_method: 'EMAIL', + appointment_datetime: proposedIso, + specialist_contact_email: config.credentials.specialist.email, + }); + assertOwnerScopedSpecialistEmail(own.body); + const duplicate = await request(app!.getHttpServer()) + .post('/api/appointments/pending') + .auth(customerToken, { type: 'bearer' }) + .send(pendingBody(car.id)) + .expect(409); + expect(duplicate.body.error.code).toBe('ACTIVE_PROCESS_EXISTS'); + const { exists: _exists, ...snapshot } = own.body.data; + expect(duplicate.body.error.details).toEqual({ + existing_request: snapshot, + }); + assertOwnerScopedSpecialistEmail(duplicate.body); + await assertStoredState( + car.id, + response.body.data.process_id, + response.body.data.id, + 'PENDING', + proposedIso, + ); + } + + for (const { processId } of created) { + const detail = await request(app!.getHttpServer()) + .get(`/api/processes/${processId}`) + .auth(specialistToken, { type: 'bearer' }) + .expect(200); + expect(detail.body.data.client).toEqual({ + id: fixture.users[0].id, + name: fixture.users[0].name, + email: config.credentials.customer.email, + phone: fixture.users[0].phone, + }); + assertNoPrivateFields(detail.body); + const customer = await request(app!.getHttpServer()) + .get(`/api/processes/${processId}`) + .auth(customerToken, { type: 'bearer' }) + .expect(200); + expect(customer.body.data.client).not.toHaveProperty('email'); + expect(customer.body.data.client.phone).toBeNull(); + expect(customer.body.data.specialist.phone).toBeNull(); + assertNoContacts(customer.body); + const outsider = await request(app!.getHttpServer()) + .get(`/api/processes/${processId}`) + .auth(outsiderToken, { type: 'bearer' }) + .expect(403); + assertNoContacts(outsider.body); + for (const token of [customerToken, outsiderToken]) { + await request(app!.getHttpServer()) + .post(`/api/processes/${processId}/confirm-appointment`) + .auth(token, { type: 'bearer' }) + .send({ appointment_datetime: changedIso }) + .expect(403); + } + } + const privateAppointment = await request(app!.getHttpServer()) + .get(`/api/appointments/${created[0].appointmentId}`) + .auth(outsiderToken, { type: 'bearer' }) + .expect(403); + assertNoContacts(privateAppointment.body); + const assignedList = await request(app!.getHttpServer()) + .get(`/api/processes/specialist/${fixture.users[1].id}`) + .auth(specialistToken, { type: 'bearer' }) + .expect(200); + expect(assignedList.body.data).toHaveLength(2); + for (const process of assignedList.body.data) { + expect(process.client.email).toBe(config.credentials.customer.email); + expect(process.client.phone).toBe(fixture.users[0].phone); + } + const forbiddenList = await request(app!.getHttpServer()) + .get(`/api/processes/specialist/${fixture.users[1].id}`) + .auth(outsiderToken, { type: 'bearer' }) + .expect(403); + assertNoContacts(forbiddenList.body); + const emptyList = await request(app!.getHttpServer()) + .get(`/api/processes/specialist/${fixture.users[2].id}`) + .auth(outsiderToken, { type: 'bearer' }) + .expect(200); + expect(emptyList.body.data).toEqual([]); + assertNoContacts(emptyList.body); + + const confirm = (processId: string, datetime: string) => + request(app!.getHttpServer()) + .post(`/api/processes/${processId}/confirm-appointment`) + .auth(specialistToken, { type: 'bearer' }) + .send({ appointment_datetime: datetime }); + const first = await confirm(created[0].processId, changedIso).expect(201); + expect(first.body.data).toEqual({ + processId: created[0].processId, + status: 'SCHEDULING', + appointment_status: 'SCHEDULED', + appointment_datetime: changedIso, + }); + assertNoContacts(first.body); + const firstStored = await assertStoredState( + created[0].productId, + created[0].processId, + created[0].appointmentId, + 'SCHEDULED', + changedIso, + ); + expect(firstStored.process.notes).toContain(`proposta: ${proposedIso}`); + expect(firstStored.process.notes).toContain( + `horário confirmado: ${changedIso}`, + ); + + // A confirmed commitment conflicts; a still-pending EMAIL proposal did not. + const conflict = await confirm(created[1].processId, changedIso).expect( + 409, + ); + assertNoContacts(conflict.body); + expect(Object.keys(conflict.body.error.details)).toEqual([ + 'suggested_times', + ]); + for (const item of created) { + expect(JSON.stringify(conflict.body).includes(item.appointmentId)).toBe( + false, + ); + expect(JSON.stringify(conflict.body).includes(item.processId)).toBe( + false, + ); + } + await assertStoredState( + created[1].productId, + created[1].processId, + created[1].appointmentId, + 'PENDING', + proposedIso, + ); + + // The second product confirms its original suggestion without changing it. + const second = await confirm(created[1].processId, proposedIso).expect(201); + expect(second.body.data.appointment_datetime).toBe(proposedIso); + await assertStoredState( + created[1].productId, + created[1].processId, + created[1].appointmentId, + 'SCHEDULED', + proposedIso, + ); + const beforeRepeat = await assertStoredState( + created[0].productId, + created[0].processId, + created[0].appointmentId, + 'SCHEDULED', + changedIso, + ); + await confirm(created[0].processId, changedIso).expect(201); + const afterRepeat = await assertStoredState( + created[0].productId, + created[0].processId, + created[0].appointmentId, + 'SCHEDULED', + changedIso, + ); + // Equality covers appointment confirmation/audit timestamps, process notes + // and the full ordered history; assertStoredState also checks cardinality. + expect(afterRepeat).toEqual(beforeRepeat); + await confirm(created[0].processId, secondIso).expect(400); + + for (const item of created) { + const confirmed = await request(app!.getHttpServer()) + .get(`/api/processes/${item.processId}`) + .auth(specialistToken, { type: 'bearer' }) + .expect(200); + expect(confirmed.body.data.status).toBe('SCHEDULING'); + expect(confirmed.body.data.appointment_status).toBe('SCHEDULED'); + expect(confirmed.body.data.client.email).toBe( + config.credentials.customer.email, + ); + expect(confirmed.body.data.client.phone).toBe(fixture.users[0].phone); + const own = await request(app!.getHttpServer()) + .get('/api/appointments/check') + .auth(customerToken, { type: 'bearer' }) + .query(checkQuery(item.productId)) + .expect(200); + expect(Object.keys(own.body.data).sort()).toEqual([...checkKeys].sort()); + expect(own.body.data.appointment_status).toBe('SCHEDULED'); + expect(own.body.data.specialist_contact_email).toBe( + config.credentials.specialist.email, + ); + assertOwnerScopedSpecialistEmail(own.body); + } + expect( + await prisma!.appointment.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(2); + expect( + await prisma!.process.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(2); + }, 30_000); + + it('aborts cleanup before deleting anything when a fixture has a foreign participant', async () => { + const sentinel = { + id: '8c26e2a3-fd13-447a-9b6c-000000000901', + client_id: fixture.users[0].id, + specialist_id: fixture.users[2].id, + product_id: fixture.cars[0].id, + product_type: 'CAR' as const, + scheduling_method: 'EMAIL' as const, + }; + const before = { + appointments: await prisma!.appointment.count({ + where: { client_id: fixture.users[0].id }, + }), + processes: await prisma!.process.count({ + where: { client_id: fixture.users[0].id }, + }), + }; + // Fixed test-owned ID; create fails on collision and never deletes a row + // that existed before this test. The invalid participant is intentional. + await prisma!.appointment.create({ + data: { + ...sentinel, + status: 'PENDING', + appointment_datetime: new Date(secondIso), + }, + }); + try { + await expect( + cleanupEmailSchedulingFixtures(prisma!, fixture), + ).rejects.toThrow(/Refusing cleanup/); + expect( + await prisma!.appointment.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(before.appointments + 1); + expect( + await prisma!.process.count({ + where: { client_id: fixture.users[0].id }, + }), + ).toBe(before.processes); + expect(await prisma!.appointment.count({ where: sentinel })).toBe(1); + } finally { + // Only the exact row created above may be removed; no cascade or broad + // fixture reset is used to recover from the deliberate integrity failure. + await prisma!.appointment.deleteMany({ where: sentinel }); + } + }); +}); diff --git a/backend/test/jest-e2e.json b/backend/test/jest-e2e.json index e9d912f3..bcfc11b4 100644 --- a/backend/test/jest-e2e.json +++ b/backend/test/jest-e2e.json @@ -3,6 +3,10 @@ "rootDir": ".", "testEnvironment": "node", "testRegex": ".e2e-spec.ts$", + "moduleNameMapper": { + "^src/(.*)$": "/../src/$1", + "^isomorphic-dompurify$": "/mocks/isomorphic-dompurify.ts" + }, "transform": { "^.+\\.(t|j)s$": "ts-jest" } diff --git a/backend/test/mocks/isomorphic-dompurify.ts b/backend/test/mocks/isomorphic-dompurify.ts new file mode 100644 index 00000000..53983039 --- /dev/null +++ b/backend/test/mocks/isomorphic-dompurify.ts @@ -0,0 +1,20 @@ +// Scheduling never sanitizes SVG. Keep LogoSanitizerService and its Nest +// wiring real, but fail if this unrelated dependency is used by the E2E gate. +let sanitizeCallCount = 0; + +export function getSanitizeCallCount() { + return sanitizeCallCount; +} + +export function resetSanitizeCallCount() { + sanitizeCallCount = 0; +} + +export default { + sanitize(_input: string): never { + sanitizeCallCount += 1; + throw new Error( + 'SVG sanitization is outside the email scheduling E2E gate', + ); + }, +}; diff --git a/docs/docs/agendamento-sem-calendly.md b/docs/docs/agendamento-sem-calendly.md index 1536650a..cb925ca1 100644 --- a/docs/docs/agendamento-sem-calendly.md +++ b/docs/docs/agendamento-sem-calendly.md @@ -3,344 +3,104 @@ sidebar_position: 6 title: Agendamento sem Calendly --- -# Agendamento sem Calendly — especificação de design +# Agendamento sem Calendly por e-mail -**Data:** 14 de setembro de 2026 -**Status:** aprovado para planejamento -**Escopo:** cadastro de produtos e início de negociação quando o especialista não possui Calendly conectado +Sem Calendly ativo, o cliente usa **Solicitar reunião**, propõe uma data e hora futura e registra um pedido pendente. O especialista atribuído pode confirmar a sugestão ou **Alterar e confirmar**. A confirmação reserva o horário; o processo continua em `SCHEDULING` para permitir a reunião. -## 1. Objetivo +Conectar Calendly é opcional e não bloqueia cadastro, edição ou publicação de produtos. A capacidade `calendly_scheduling_available` vem do backend: exige uma URL HTTPS do domínio Calendly e uma conexão OAuth ativa. Uma URL residual, sozinha, não ativa esse caminho. -Permitir que especialistas operem normalmente sem uma conta Calendly e oferecer ao cliente duas formas simples de iniciar uma negociação: +## Fluxo do cliente -1. entrar em contato livremente por e-mail e combinar o horário fora da plataforma; ou -2. escolher uma data e hora diretamente na plataforma. +1. Entre como cliente, abra o produto e escolha **Solicitar reunião**. +2. Informe a data e hora futura no modal. A interface mostra o fuso local; a API recebe e armazena um instante UTC em ISO 8601. +3. Após a criação, a página mostra o sucesso e tenta abrir o aplicativo padrão de e-mail com destinatário, assunto e corpo sugeridos. O pedido já está salvo como `PENDING/EMAIL`, com o horário proposto, junto ao processo `SCHEDULING`. +4. Use os fallbacks **Abrir aplicativo de e-mail**, **Abrir no Gmail**, **Copiar e-mail** ou **Acompanhar processo**. Eles continuam disponíveis após recarregar ou revisitar o produto enquanto o próprio pedido está pendente. -O Calendly continua disponível como conveniência, mas deixa de ser requisito para cadastrar produtos ou receber solicitações. +A abertura automática ocorre no máximo uma vez por pedido recém-criado. Reload, revisita e recuperação de duplicidade restauram o painel sem repetir essa tentativa. Falha do navegador, ausência de aplicativo padrão ou indisponibilidade do clipboard não desfazem o pedido; o endereço permanece visível e selecionável. -## 2. Estado atual e problemas encontrados +O assunto e o corpo são editáveis no compositor externo. A plataforma não captura nem persiste essas edições e não comprova que um e-mail foi enviado. Um `mailto:` ou link Gmail válido demonstra apenas que a composição foi preparada. Uma falha na criação não abre o compositor. -O sistema já possui boa parte da infraestrutura necessária: +## Fluxo do especialista -- `Appointment` registra data, participantes e estado do agendamento; -- `Process` representa o processo comercial e nasce em `SCHEDULING`; -- o backend já valida conflitos de horário e consegue criar `Appointment` e `Process` atomicamente; -- a página de produto já possui um fallback que cria uma solicitação pendente e abre um `mailto:`; -- a área de processos já possui a sala de reunião interna e ações para iniciar e entrar em uma reunião; -- existe um modal global dispensável que incentiva o especialista a conectar o Calendly. +No processo pendente por e-mail, o especialista atribuído vê a proposta, o e-mail do cliente e seu telefone, quando preenchido. Um número brasileiro normalizável também produz um atalho WhatsApp. Telefone ausente não produz ação; telefone inválido permanece como texto, sem link incorreto. -Entretanto, o comportamento atual não atende integralmente ao objetivo: +- **Confirmar horário** envia o instante proposto ao endpoint canônico do processo. +- **Alterar e confirmar** abre o seletor com a proposta existente e envia o horário escolhido. Sem edição efetiva, o instante ISO original é preservado. -- `ProductFormPage` substitui o formulário por um bloqueio quando o especialista não tem Calendly; -- o modal global afirma que a negociação fica bloqueada sem Calendly; -- o cliente sem Calendly só recebe a opção de e-mail; -- não existe interface ativa para o cliente escolher uma data e hora na plataforma; -- no fluxo de e-mail, a confirmação do especialista não exige o horário combinado; -- não existe controle explícito da única alteração de horário permitida ao especialista; -- o endpoint direto de agendamento precisa garantir que o usuário autenticado seja o próprio cliente informado. +Ambas as ações resultam em `Appointment=SCHEDULED` e `Process=SCHEDULING`. A primeira definição ou alteração antes da confirmação não consome a remarcação posterior: `specialist_rescheduled_at` e `specialist_rescheduled_from` continuam nulos. As notas preservam a proposta e o horário confirmado. O cliente passa a ver o horário efetivo, e os controles da reunião continuam disponíveis no processo. -## 3. Decisões de produto +Pedidos `PENDING/EMAIL` são propostas e não ocupam a agenda. A confirmação valida o conflito novamente sob trava de agenda. Se houver `409`, o especialista pode escolher outro horário no modal, que conserva a mensagem do erro. Dupla submissão do mesmo horário confirmado não cria registros ou histórico adicionais. -- Conectar o Calendly é opcional. -- A ausência ou indisponibilidade do Calendly nunca bloqueia criação, edição ou publicação de produtos. -- Um especialista com Calendly mantém o fluxo atual de agendamento. -- Um cliente que escolhe um produto de especialista sem Calendly pode optar por e-mail ou agendamento interno. -- Um horário escolhido pelo cliente na plataforma é confirmado imediatamente. -- No fluxo por e-mail, somente o especialista registra o horário acordado. -- Registrar o primeiro horário após a conversa por e-mail não conta como alteração. -- Depois que um horário está confirmado, o especialista pode alterá-lo uma única vez. -- A alteração feita pelo especialista é definitiva e não depende de aprovação do cliente. -- O MVP não restringe tecnicamente o início da sala a uma janela exata ao redor do horário; o horário é exibido e o especialista inicia a sala quando chega o momento. +A remarcação de um compromisso já confirmado continua sendo uma ação separada, permitida uma vez ao especialista responsável. Ela preenche os dois campos de auditoria. A reunião e o avanço comercial seguem o fluxo existente. -## 4. Abordagem escolhida +## Contratos e privacidade -A implementação evoluirá o fluxo atual, reutilizando `Appointment`, `Process`, as validações de agenda e a sala interna. +| Operação | Contrato | +|---|---| +| `POST /api/appointments/pending` | Cliente autenticado cria para si, com `scheduling_method=EMAIL`, produto/especialista e `appointment_datetime` futura. Retorna o appointment e o `process_id` criados atomicamente. | +| `GET /api/appointments/check` | Somente `CUSTOMER`; aceita `specialist_id`, `product_type` e `product_id`. A identidade vem do JWT; enviar `client_id` na query é inválido. | +| `POST /api/processes/:id/confirm-appointment` | Somente o especialista atribuído; aceita o horário sugerido ou outro futuro, confirma sob lock e mantém `SCHEDULING`. | +| `GET /api/specialists/:id/public-profile` | ID, nome comercial, especialidade, e-mail comercial, URL Calendly e booleano de capacidade. Não inclui documentos, telefone pessoal ou dados OAuth. | +| `GET/PATCH /api/users/:id` | Perfil privado: somente o próprio usuário ou `ADMIN`. Apenas especialista pode definir uma URL Calendly; `null` remove a URL. | -Não será criado um calendário completo de disponibilidade. Essa alternativa exigiria regras de jornada, recorrência, bloqueios e fuso horário que não são necessárias para o primeiro lançamento. +A consulta do próprio pedido retorna somente `{ exists: false }` ou `{ exists: true, appointment_id, process_id, appointment_status, scheduling_method, appointment_datetime }`, sem nomes ou contatos. Um pedido ativo duplicado responde `409/ACTIVE_PROCESS_EXISTS` com `error.details.existing_request` nesse mesmo formato mínimo, sem o discriminante `exists`. Outros conflitos não expõem IDs ou contatos do compromisso concorrente. -Também não haverá uma etapa de aprovação da sugestão do cliente: no agendamento interno, a seleção já cria um horário confirmado. +Os contatos do cliente aparecem na lista e no detalhe somente para o especialista atribuído ao pedido `PENDING/EMAIL` em `SCHEDULING` e continuam disponíveis para ele após a confirmação. Outros especialistas não podem listar ou abrir esse processo. As projeções de cliente não recebem os contatos privados nesse estado. O e-mail comercial do especialista é intencionalmente público para permitir a composição da mensagem. -## 5. Modelo de dados +O backend recusa a criação direta `SCHEDULED/PLATFORM` por `POST /api/appointments` nesse cenário. O caminho com Calendly ativo continua usando `CALENDLY` e não aceita horário enviado pelo cliente: o instante é resolvido na API autenticada do Calendly e, enquanto ela não retornar um horário válido, o pedido permanece `PENDING` sem reservar agenda para que o webhook assinado possa completá-lo. Se `CALENDLY_WEBHOOK_CALLBACK_URL` for configurada, `CALENDLY_WEBHOOK_SIGNING_KEY` é obrigatória; callbacks sem assinatura válida e fresca são rejeitados. A consultoria sem produto conserva o pedido `PENDING/EMAIL` sem data e exige sua definição na confirmação. Registros legados sem proposta continuam legíveis. `pending_expires_at` é metadado: não existe expiração automática nesta entrega. -### 5.1 Origem do agendamento +## Validação local repetível -Adicionar ao Prisma: +Use PostgreSQL local e o banco dedicado `bmfluxdb_email_scheduling_e2e`, com as migrations existentes aplicadas. A URL deve ser explícita, usar loopback (`localhost`, `127.0.0.1` ou `::1`) e nome de banco terminado em `email_scheduling_e2e`. O seed não carrega `.env` nem usa `DATABASE_URL` como fallback. -```prisma -enum AppointmentSchedulingMethod { - CALENDLY - EMAIL - PLATFORM -} -``` - -Adicionar a `Appointment`: - -```prisma -scheduling_method AppointmentSchedulingMethod? -specialist_rescheduled_at DateTime? -specialist_rescheduled_from DateTime? -``` - -`scheduling_method` será opcional para permitir uma migração aditiva sem classificar incorretamente registros históricos. Todos os novos agendamentos devem preenchê-lo explicitamente. - -`specialist_rescheduled_at` funciona como a trava da única alteração. `specialist_rescheduled_from` preserva o horário anterior para auditoria. - -Não é necessário um contador: campo vazio significa que a alteração ainda está disponível; campo preenchido significa que ela já foi consumida. - -### 5.2 Estados - -| Método | Criação | Quando passa a `SCHEDULED` | Processo | -|---|---|---|---| -| `CALENDLY` | `PENDING` | após sincronização/confirmação atual | permanece com o comportamento existente | -| `EMAIL` | `PENDING`, sem horário | quando o especialista registra o horário acordado | permanece em `SCHEDULING` até a reunião | -| `PLATFORM` | `SCHEDULED`, com horário | na própria criação | nasce em `SCHEDULING` | - -Confirmar um horário não significa concluir a reunião nem iniciar a negociação financeira. O processo continua em `SCHEDULING` enquanto a conversa ainda não aconteceu. - -## 6. Fluxos - -### 6.1 Especialista sem Calendly - -1. O especialista entra na área autenticada. -2. A plataforma consulta o estado da conexão Calendly. -3. Se não houver conexão ativa, exibe um modal informativo. -4. O especialista pode escolher `Conectar agora` ou `Continuar sem Calendly`. -5. Ao dispensar o modal, continua usando todas as funcionalidades, inclusive cadastro de produtos. -6. O modal não volta durante a mesma sessão do navegador. - -Falha na consulta do Calendly não bloqueia nenhuma tela. O formulário de produto deve ser renderizado independentemente do resultado dessa consulta. - -### 6.2 Cliente escolhe contato por e-mail - -1. Na página do produto, o cliente seleciona `Enviar e-mail`. -2. A plataforma cria `Appointment(PENDING, EMAIL)` e o `Process(SCHEDULING)` associado na mesma transação. -3. A plataforma abre um `mailto:` com destinatário, assunto e texto sugeridos, todos editáveis no cliente de e-mail. -4. A página redireciona para `Meus Processos` e informa que o horário será definido após o contato. -5. O especialista combina o horário com o cliente fora da plataforma. -6. No card do processo, o especialista escolhe `Definir data e hora`. -7. O backend valida e grava o horário, muda o agendamento para `SCHEDULED` e mantém o processo em `SCHEDULING`. -8. O cliente recebe uma notificação e passa a ver o horário no processo. - -Se o navegador não conseguir abrir o cliente de e-mail, a solicitação continua criada. A interface deve exibir o endereço do especialista com uma ação de copiar. - -### 6.3 Cliente escolhe data e hora na plataforma +Configure as variáveis na sessão local, sem salvar ou publicar credenciais: -1. Na página do produto, o cliente seleciona `Escolher data e hora`. -2. Um modal simples exibe um campo `datetime-local`, o fuso local do navegador e o botão `Confirmar agendamento`. -3. O frontend converte o valor local para ISO 8601 UTC. -4. O backend valida o usuário, o produto, o horário futuro, conflito de agenda e processo ativo duplicado. -5. A transação cria `Appointment(SCHEDULED, PLATFORM)` e `Process(SCHEDULING)`. -6. O cliente é redirecionado para `Meus Processos` com o horário confirmado. -7. O especialista é notificado sobre o novo agendamento. +- `EMAIL_SCHEDULING_E2E_DATABASE_URL`; +- `EMAIL_SCHEDULING_E2E_CUSTOMER_EMAIL` e `EMAIL_SCHEDULING_E2E_CUSTOMER_PASSWORD`; +- `EMAIL_SCHEDULING_E2E_SPECIALIST_EMAIL` e `EMAIL_SCHEDULING_E2E_SPECIALIST_PASSWORD`; +- `EMAIL_SCHEDULING_E2E_OUTSIDER_EMAIL` e `EMAIL_SCHEDULING_E2E_OUTSIDER_PASSWORD`; +- `JWT_SECRET_ACCESS`, `JWT_SECRET_REFRESH`, `JWT_SECRET_REFERRAL` e `JWT_SECRET_ADVISOR` para o HTTP E2E; `JWT_SECRET_PASSWORD_RESET` pode ser dedicado ou usar o fallback existente. -O cliente não escolhe a duração no MVP. Será usada a mesma janela de conflito de uma hora já adotada pelo backend. +Os três e-mails devem ser distintos e terminar em `.test`, domínio reservado para testes. As senhas exigem pelo menos seis caracteres e são armazenadas com bcrypt (custo 10). O seed não imprime URL, e-mails, senhas ou hashes. -### 6.4 Alteração única pelo especialista - -1. Um agendamento `SCHEDULED` com horário e `specialist_rescheduled_at` vazio exibe `Alterar horário` somente ao especialista responsável. -2. O especialista escolhe um novo horário futuro. -3. A interface avisa que essa será a única alteração e pede confirmação explícita. -4. O backend trava a agenda do especialista, revalida conflito excluindo o próprio agendamento e atualiza atomicamente: - - `specialist_rescheduled_from` com o horário vigente; - - `appointment_datetime` com o novo horário; - - `specialist_rescheduled_at` com o instante da operação. -5. O novo horário passa a valer imediatamente. -6. O cliente é notificado e a ação desaparece para o especialista. - -Uma segunda tentativa retorna `409 Conflict` com mensagem de que a alteração definitiva já foi utilizada. - -### 6.5 Reunião interna - -1. Enquanto o processo está em `SCHEDULING` e o agendamento está `SCHEDULED`, ambos veem o horário confirmado. -2. Ao chegar o momento, o especialista usa `Iniciar reunião`. -3. O cliente passa a ver `Entrar na reunião` assim que a sessão existir. -4. O encerramento da conversa segue o fluxo atual de avanço para negociação. - -## 7. Backend e contratos HTTP - -### 7.1 Criação direta - -Manter `POST /appointments` como operação de agendamento interno e endurecer suas regras: - -- aceitar somente usuário autenticado com papel `CUSTOMER`; -- exigir `req.user.id === client_id`; -- exigir `appointment_datetime` para esse fluxo; -- definir `scheduling_method = PLATFORM` no servidor; -- criar agendamento e processo na mesma transação; -- manter o processo em `SCHEDULING`. - -O cliente não poderá enviar outro `scheduling_method` nesse endpoint. - -### 7.2 Solicitação por e-mail - -`POST /appointments/pending` passa a aceitar `scheduling_method` apenas com os valores `EMAIL` ou `CALENDLY`. As chamadas da página de produto devem enviar o valor de forma explícita. - -Para reduzir risco de compatibilidade, chamadas antigas sem o campo continuam sendo tratadas como `CALENDLY` no serviço, mas o banco não aplica um default retroativo. - -### 7.3 Definição inicial pelo especialista - -Evoluir `POST /processes/:id/confirm-appointment` para aceitar: - -```json -{ - "appointment_datetime": "2026-09-20T17:00:00.000Z" -} +```sh +rtk docker compose up -d db +rtk docker compose exec -T db pg_isready -U user -d bmfluxdb +# Crie o banco dedicado antes de aplicar as migrations. +rtk env DATABASE_URL="$EMAIL_SCHEDULING_E2E_DATABASE_URL" DIRECT_URL="$EMAIL_SCHEDULING_E2E_DATABASE_URL" npm --prefix backend exec -- prisma migrate deploy +rtk npm --prefix backend run seed:email-scheduling-e2e +rtk node -e 'if (!process.env.EMAIL_SCHEDULING_E2E_DATABASE_URL) process.exit(1)' +rtk npm --prefix backend run test:e2e -- --runInBand --runTestsByPath test/email-scheduling.e2e-spec.ts --json --outputFile=/tmp/email-scheduling-http-e2e.json +rtk node -e 'const r=require("/tmp/email-scheduling-http-e2e.json");if(!r.success||r.numPendingTests!==0)process.exit(1)' ``` -Para `EMAIL`, a data é obrigatória. A operação: +O seed cria ou atualiza três usuários sintéticos e dois carros ativos atribuídos ao especialista sem Calendly. Os IDs-base são fixos: -- exige que o solicitante seja o especialista do processo; -- exige processo em `SCHEDULING` e agendamento em `PENDING`; -- valida data futura e conflito sob a trava já existente; -- muda o agendamento para `SCHEDULED`; -- não preenche os campos de reagendamento; -- não avança o processo para `NEGOTIATION`. +| Fixture | UUID no namespace de navegador | +|---|---| +| Cliente | `c848f474-6492-4ac1-8a7d-000000000001` | +| Especialista atribuído | `c848f474-6492-4ac1-8a7d-000000000002` | +| Especialista não atribuído | `c848f474-6492-4ac1-8a7d-000000000003` | +| Produto A | `c848f474-6492-4ac1-8a7d-000000000101` | +| Produto B | `c848f474-6492-4ac1-8a7d-000000000102` | -### 7.4 Reagendamento definitivo +O HTTP E2E usa outro prefixo, `8c26e2a3-fd13-447a-9b6c`, e deriva aliases `local+http@dominio.test` dos e-mails da sessão. Assim ele não limpa pedidos feitos com o seed de navegador. Ele inicializa o `AppModule` real, autentica as três identidades pelo login e usa guards, validação, serializer e prefixo reais. Somente fronteiras externas (SES/S3/DocuSign), recuperação de jobs e o timer de rate limit são neutralizados; autenticação, autorização, transações e persistência não são simuladas. No ambiente Jest desse E2E, a fronteira `isomorphic-dompurify`/SVG é substituída por um stub *fail-closed*: qualquer chamada ao sanitizador falha imediatamente. Portanto, o HTTP E2E não comprova a sanitização; a implementação de produção e os testes próprios do sanitizador continuam usando a dependência real. Sem a URL explícita, o grupo HTTP é pulado; o gate dedicado exige zero testes pulados. -Adicionar `PATCH /appointments/:id/reschedule`: - -```json -{ - "appointment_datetime": "2026-09-21T19:00:00.000Z" -} -``` +O teste cobre criação pendente, identidade derivada do JWT, IDOR de GET/PATCH, bypass direto, contato autorizado na lista/detalhe, duplicidade, conflito sem PII, confirmação alterada e inalterada, idempotência e estados/cardinalidade no banco. O seed também é executado duas vezes pelo teste para comprovar a idempotência dos IDs-base. -Regras: +A limpeza resolve os IDs gerados de appointments/processes apenas a partir dos usuários/produtos determinísticos e valida ambos os participantes, método e vínculos antes de excluir qualquer registro. Histórico, processo e appointment são apagados nessa ordem dentro de uma transação; tokens são limitados aos usuários da fixture. Contrato, proposta, reunião, `Product` ou vínculo inesperado interrompem o reset integralmente. Usuários e carros são atualizados por ID; nunca são truncados ou apagados. Rodar novamente o seed reinicia somente os pedidos desse namespace. -- somente o especialista responsável; -- agendamento em `SCHEDULED`; -- horário atual existente; -- `specialist_rescheduled_at` ainda vazio; -- novo horário futuro e diferente do atual; -- ausência de conflito com outro agendamento do especialista; -- atualização atômica e protegida contra duas alterações concorrentes. +## Checklist de navegador e gates -## 8. Frontend +Inicie backend e frontend do source atual, apontando ambos para o banco dedicado. No backend, use `NOTIFICATIONS_ENABLED=false` para evitar entrega de notificações; no frontend, `VITE_API_BASE_URL=http://localhost:3000/api`. Use contextos independentes para cliente, especialista atribuído e usuário não atribuído. -### 8.1 `RequireCalendlyModal` +1. No produto A, crie a proposta futura e capture status/payload do POST e do check. Inspecione destinatário, assunto e corpo dos links `mailto:`/Gmail sem afirmar envio externo. +2. Recarregue e revisite o produto: os fallbacks persistem e não ocorre outra tentativa automática de abrir e-mail. +3. Como especialista atribuído, veja proposta, e-mail, telefone e WhatsApp; altere e confirme. Confirme `SCHEDULED`, processo `SCHEDULING` e controles da reunião. +4. Repita no produto B confirmando a sugestão sem alteração. +5. Como não atribuído, tente ler o processo/lista, confirmar e acessar/editar o perfil privado do cliente: as operações retornam `403`, sem contatos e sem alterações. +6. Repita o caminho crítico em viewport móvel e por teclado, observando foco, labels, anúncio de sucesso/erro e retorno de foco do modal. -- Trocar o texto que afirma haver bloqueio. -- Usar `Continuar sem Calendly` no lugar de `Lembrar mais tarde`. -- Manter o comportamento dispensável por sessão. +Após cada confirmação, consulte o banco em modo somente leitura usando os IDs-base acima e os IDs retornados pelo POST. Exija exatamente um appointment e um processo por produto, vínculo recíproco correto, `appointment_datetime` efetiva, `SCHEDULED/SCHEDULING` e ambos os campos de remarcação nulos. A aparência do navegador sozinha não comprova essas condições. -### 8.2 `ProductFormPage` - -- Remover o gate de Calendly. -- Não esperar a consulta da conexão para renderizar o formulário. -- O modal global continua responsável por recomendar a conexão. - -### 8.3 `ProductPage` - -- Manter o popup atual quando existe URL Calendly. -- Sem URL, apresentar duas ações claras: - - `Enviar e-mail`; - - `Escolher data e hora`. -- Reutilizar um modal de agendamento enxuto para o segundo caminho. -- Manter o tratamento de duplicidade e o redirecionamento para processos. - -### 8.4 `ProcessCard` - -- Para `EMAIL + PENDING`, substituir a confirmação sem horário por `Definir data e hora`. -- Para `SCHEDULED`, exibir o horário aos dois participantes. -- Exibir `Alterar horário` ao especialista apenas quando a alteração ainda estiver disponível. -- Após o reagendamento, exibir `Horário alterado definitivamente`. -- Manter o início da sala exclusivamente com o especialista; o cliente entra depois que a sessão é criada. - -## 9. Erros e mensagens - -| Situação | Resposta | Comportamento da interface | -|---|---|---| -| Horário passado | `400` | manter modal aberto e explicar que deve ser futuro | -| Conflito de agenda | `409` | manter modal aberto e pedir outro horário | -| Processo ativo duplicado | `409` | direcionar para o processo existente | -| Cliente agendando por outro usuário | `403` | negar sem criar registros | -| Usuário que não é o especialista tentando definir/alterar | `403` | negar sem alterar registros | -| Segunda alteração do especialista | `409` | informar que a alteração definitiva já foi usada | -| Falha no envio da notificação | operação continua | registrar erro; não reverter agendamento | -| Falha ao consultar Calendly | nenhuma restrição | manter produtos e alternativas disponíveis | -| Falha ao abrir `mailto:` | solicitação continua | mostrar e-mail copiável e link para processos | - -## 10. Notificações - -As notificações continuam assíncronas e não críticas, seguindo o padrão existente do `NotificationService`. - -- Agendamento interno criado: avisar o especialista com cliente, produto e horário. -- Horário do fluxo por e-mail definido: avisar o cliente. -- Horário alterado definitivamente: avisar o cliente, mostrando horário anterior e novo. - -Não será implementada resposta por e-mail, convite de calendário ou confirmação adicional no MVP. - -## 11. Segurança e concorrência - -- Toda decisão de autorização ocorre no backend; o frontend apenas oculta ações indisponíveis. -- O agendamento direto verifica a identidade do cliente autenticado. -- Definição e alteração do horário verificam o especialista vinculado ao processo/agendamento. -- A validação de produto continua exigindo produto ativo, do tipo correto e pertencente ao especialista. -- A trava de agenda do especialista é adquirida antes de verificar conflitos e escrever. -- A alteração única usa atualização condicional com `specialist_rescheduled_at: null`; duas requisições concorrentes não podem consumir a alteração duas vezes. -- Criação de `Appointment`, `Process` e histórico permanece atômica. - -## 12. Estratégia de testes - -### Frontend - -- `ProductFormPage` renderiza e envia o formulário mesmo sem Calendly. -- O modal Calendly é dispensável e comunica que a integração é opcional. -- `ProductPage` mantém Calendly quando conectado e mostra as duas alternativas quando desconectado. -- O modal interno converte corretamente a data local para UTC. -- O fluxo de e-mail cria solicitação antes de abrir `mailto:` e oferece fallback copiável. -- `ProcessCard` exige data na confirmação por e-mail. -- A ação de alterar horário aparece uma vez e desaparece após sucesso. - -### Backend - -- Cliente só agenda para si mesmo. -- Agendamento interno exige horário futuro e nasce `SCHEDULED/PLATFORM`. -- Solicitação por e-mail nasce `PENDING/EMAIL` sem horário. -- Apenas o especialista registra o primeiro horário do fluxo por e-mail. -- Definição inicial mantém o processo em `SCHEDULING` e não consome reagendamento. -- Primeira alteração grava horário anterior e instante da alteração. -- Segunda alteração retorna conflito. -- Requisições concorrentes permitem apenas uma alteração. -- Conflito de agenda, produto incorreto e processo duplicado continuam bloqueados. -- Falha ao criar o processo reverte o agendamento. -- Falha de notificação não reverte alterações confirmadas. -- Testes existentes do Calendly continuam passando. - -### Verificação integrada - -Validar manualmente com dois usuários, cliente e especialista sem Calendly: - -1. cadastrar um produto; -2. iniciar uma solicitação por e-mail e registrar o horário pelo especialista; -3. criar outro agendamento escolhendo o horário na plataforma; -4. alterar uma vez e confirmar que a segunda alteração é bloqueada; -5. iniciar e acessar a sala pelos dois participantes. - -## 13. Critérios de aceite - -- Especialista sem Calendly cadastra, edita e publica produtos sem bloqueio. -- O lembrete de Calendly pode ser fechado e não contém mensagem de bloqueio. -- Cliente de produto sem Calendly escolhe entre e-mail e data/hora interna. -- Os dois caminhos criam processo rastreável em `SCHEDULING`. -- O fluxo de e-mail só ganha horário quando o especialista o registra. -- O agendamento interno nasce confirmado. -- Ambos visualizam o horário vigente. -- O especialista consegue alterá-lo uma vez, com efeito imediato. -- A segunda alteração é recusada também sob concorrência. -- O cliente é notificado quando o especialista define ou altera o horário. -- A sala interna continua acessível pelo processo no momento combinado. -- O fluxo Calendly existente não sofre regressão. - -## 14. Fora de escopo - -- agenda de disponibilidade recorrente do especialista; -- bloqueio de feriados, horário comercial ou intervalos personalizados; -- aprovação do cliente após alteração; -- múltiplas propostas de reagendamento; -- integração com Google Calendar, Outlook ou convites `.ics`; -- abertura automática da sala exatamente no horário; -- escolha de duração pelo cliente; -- chat interno para substituir o e-mail. +O gate de concorrência PostgreSQL usa `POSTGRES_CONCURRENCY_TEST_URL` no banco dedicado e executa `src/features/appointments/appointments-concurrency.postgres.spec.ts` com `--runInBand`; confira zero skips no resultado JSON. Depois execute sequencialmente os testes/builds de backend e frontend e o lint. Limite Jest a dois workers ou `--runInBand`, Vitest a dois workers/forks, e verifique `rtk free -h` antes das suites amplas. Preserve somente evidência sem credenciais ou PII no repositório. diff --git a/docs/e2e-evidence/commission-total-value.md b/docs/e2e-evidence/commission-total-value.md index 0ce8f40b..075b138a 100644 --- a/docs/e2e-evidence/commission-total-value.md +++ b/docs/e2e-evidence/commission-total-value.md @@ -20,4 +20,3 @@ Ao informar `10%` sobre uma venda de `R$ 100.000,00`, a mesma seção exibe: ![Etapa de comissão mostrando o total e o ganho estimado](./commission-after.jpg) O DOM foi verificado pelos rótulos e valores exatos, e o console do navegador não registrou erros nem avisos durante o fluxo. - diff --git a/docs/superpowers/plans/2026-10-13-remover-modal-global-calendly.md b/docs/superpowers/plans/2026-10-13-remover-modal-global-calendly.md index 61eba7ee..25aa30eb 100644 --- a/docs/superpowers/plans/2026-10-13-remover-modal-global-calendly.md +++ b/docs/superpowers/plans/2026-10-13-remover-modal-global-calendly.md @@ -140,4 +140,3 @@ git commit -m "fix(frontend): remove Calendly modal from product flow" git push -u origin codex/fix-calendly-product-modal gh pr create --base develop --head codex/fix-calendly-product-modal ``` - diff --git a/docs/superpowers/plans/2026-10-14-agendamento-sem-calendly-por-email.md b/docs/superpowers/plans/2026-10-14-agendamento-sem-calendly-por-email.md new file mode 100644 index 00000000..eafb16be --- /dev/null +++ b/docs/superpowers/plans/2026-10-14-agendamento-sem-calendly-por-email.md @@ -0,0 +1,702 @@ +# Agendamento sem Calendly por e-mail — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Entregar o pedido de reunião por e-mail com data proposta, composição externa de mensagem, confirmação do especialista, contatos autorizados e fechamento dos vazamentos/atalhos descobertos. + +**Architecture:** O backend será a fonte de verdade para capacidade Calendly, autorização, deduplicação e ocupação de agenda. O frontend consumirá contratos discriminados, usará helpers puros para links externos e manterá um painel recuperável após a criação. A confirmação canônica continuará em `ProcessesService.confirmAppointment`, mantendo o processo em `SCHEDULING`. + +**Tech Stack:** NestJS, Prisma/PostgreSQL, Jest, React, TypeScript, Vite, Vitest/Testing Library e navegador local controlado. + +## Global Constraints + +- Não criar migration nem alterar `backend/prisma/schema.prisma`. +- Todo shell do repositório usa prefixo `rtk`. +- Jest roda com `--runInBand` ou no máximo `--maxWorkers=2`; Vitest usa no máximo dois forks. +- `PENDING/EMAIL` com produto é proposta e não ocupa agenda; consultoria sem produto continua aceitando EMAIL sem data. +- Confirmação muda apenas `Appointment` para `SCHEDULED`; `Process` permanece `SCHEDULING`. +- `calendly_scheduling_available` só é verdadeiro com URL HTTPS do domínio Calendly e conexão OAuth ativa. +- E-mail comercial do especialista é público por decisão de produto; documentos, telefone pessoal e dados OAuth nunca são públicos. +- Ações externas só ocorrem depois de persistência confirmada; o navegador não comprova envio de e-mail. +- `pending_expires_at` continua apenas como metadado; esta entrega não implementa expiração automática. + +--- + +### Task 1: Capacidade Calendly e projeção pública segura + +**Files:** +- Create: `backend/src/shared/utils/calendly-scheduling-capability.ts` +- Create: `backend/src/shared/utils/calendly-scheduling-capability.spec.ts` +- Create: `backend/src/features/specialists/specialists.controller.spec.ts` +- Modify: `backend/src/features/appointments/calendly-integration.service.ts` +- Modify: `backend/src/features/appointments/calendly-integration.service.spec.ts` +- Modify: `backend/src/features/specialists/specialists.controller.ts` +- Modify: `backend/src/features/specialists/specialists.service.ts` +- Modify: `backend/src/features/specialists/specialists.service.spec.ts` + +**Interfaces:** +- Produces: `isCalendlySchedulingAvailable(input: { calendlyUrl: string | null; connectionActive: boolean }): boolean`. +- Produces: `GET /specialists/:id/public-profile` e o tipo de resposta `PublicSpecialistProfile` com allowlist exata. +- Consumes: `CalendlyConnection.is_active` e `me.resource.scheduling_url` do callback OAuth. + +- [ ] **Step 1: Write failing capability and projection tests** + +```ts +expect(isCalendlySchedulingAvailable({ + calendlyUrl: 'https://calendly.com/especialista/reuniao', + connectionActive: true, +})).toBe(true); + +for (const calendlyUrl of [ + 'http://calendly.com/a', + 'https://evilcalendly.com/a', + 'https://calendly.com.evil.test/a', + 'https://calendly.com@evil.test/a', + 'not-a-url', +]) { + expect(isCalendlySchedulingAvailable({ calendlyUrl, connectionActive: true })).toBe(false); +} + +expect(await service.findPublicProfile('specialist-1')).toEqual({ + id: 'specialist-1', + name: 'Ana', + surname: 'Silva', + email: 'ana@example.com', + speciality: 'CAR', + calendly_url: 'https://calendly.com/ana/reuniao', + calendly_scheduling_available: true, +}); +``` + +In the same RED phase, extend `calendly-integration.service.spec.ts` to assert that OAuth callback stores a validated `scheduling_url`, disconnect clears URL/URIs and deactivates the connection in one transaction, access-token expiry with successful refresh remains active, and `invalid_grant` persists `is_active=false` plus `last_error`. + +- [ ] **Step 2: Run focused tests and verify RED** + +Run: + +```bash +rtk npm --prefix backend test -- --runInBand src/shared/utils/calendly-scheduling-capability.spec.ts src/features/appointments/calendly-integration.service.spec.ts src/features/specialists/specialists.service.spec.ts src/features/specialists/specialists.controller.spec.ts +``` + +Expected: FAIL because the capability helper, public projection and route do not exist. + +- [ ] **Step 3: Implement the domain helper and safe serializer** + +```ts +export function isCalendlySchedulingAvailable(input: { + calendlyUrl: string | null; + connectionActive: boolean; +}): boolean { + if (!input.connectionActive || !input.calendlyUrl) return false; + try { + const url = new URL(input.calendlyUrl); + const host = url.hostname.toLowerCase(); + return url.protocol === 'https:' && + (host === 'calendly.com' || host.endsWith('.calendly.com')); + } catch { + return false; + } +} +``` + +Implement `findPublicProfile` with a Prisma `select` allowlisting only `id`, `name`, `surname`, `email`, `speciality`, `calendly_url` and `calendly_connection.is_active`. Declare `@Public()` and `@Get(':id/public-profile')` before `@Get(':id')`. Reuse the serializer in public specialist lists so CPF/CNPJ and RG are never selected. + +- [ ] **Step 4: Persist and clear Calendly state consistently** + +Update the OAuth callback to validate and store `me.resource.scheduling_url`. Update disconnect so one transaction sets `CalendlyConnection.is_active=false` and clears `calendly_url`, `calendly_user_uri` and `calendly_organization_uri`. Add tests for expired access token with valid refresh and for definitive `invalid_grant` deactivation. + +- [ ] **Step 5: Run tests and commit** + +```bash +rtk npm --prefix backend test -- --runInBand src/shared/utils/calendly-scheduling-capability.spec.ts src/features/appointments/calendly-integration.service.spec.ts src/features/specialists/specialists.service.spec.ts src/features/specialists/specialists.controller.spec.ts +rtk git add backend/src/shared/utils/calendly-scheduling-capability.ts backend/src/shared/utils/calendly-scheduling-capability.spec.ts backend/src/features/appointments backend/src/features/specialists +rtk git commit -m "feat: centralize Calendly scheduling capability" +``` + +Expected: all focused tests PASS. + +--- + +### Task 2: Autorizar perfil e impedir IDOR + +**Files:** +- Create: `backend/src/features/users/users.controller.spec.ts` +- Modify: `backend/src/features/users/users.controller.ts` +- Modify: `backend/src/features/users/users.service.ts` +- Modify: `backend/src/features/users/users.service.spec.ts` +- Modify: `backend/src/features/users/dto/update-user.dto.ts` +- Modify: `frontend/src/services/specialists.service.ts` +- Modify: `frontend/src/services/specialists.service.test.ts` +- Modify: `frontend/src/pages/catalog/ProductPage.tsx` +- Modify: `frontend/src/pages/catalog/ProductPage.test.tsx` +- Modify: `frontend/src/components/processes/StartProcessForClientModal.tsx` +- Create: `frontend/src/components/processes/StartProcessForClientModal.test.tsx` + +**Interfaces:** +- Produces: `GET /users/:id` e `PATCH /users/:id` autorizados para self ou `ADMIN`. +- Produces: `calendly_url?: string | null`; somente `SPECIALIST` pode definir valor não nulo. + +- [ ] **Step 1: Write controller authorization tests** + +```ts +await expect(controller.getById(targetId, { user: outsider })).rejects.toThrow(ForbiddenException); +await expect(controller.update(targetId, { name: 'X' }, { user: outsider })).rejects.toThrow(ForbiddenException); +expect(usersService.getById).not.toHaveBeenCalled(); +expect(usersService.update).not.toHaveBeenCalled(); + +await expect(controller.getById(self.id, { user: self })).resolves.toMatchObject({ success: true }); +await expect(controller.getById(targetId, { user: admin })).resolves.toMatchObject({ success: true }); +``` + +Also validate that a customer cannot submit `calendly_url`, while a specialist can set a valid Calendly URL or remove it with `null`. + +- [ ] **Step 2: Run tests and verify RED** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/users/users.controller.spec.ts src/features/users/users.service.spec.ts +``` + +Expected: FAIL because controller methods do not receive/request the authenticated actor and `null` is rejected by the DTO. + +- [ ] **Step 3: Implement fail-closed authorization before database access** + +```ts +private assertSelfOrAdmin(targetId: string, actor: UserEntity): void { + if (actor.id !== targetId && actor.role !== UserRole.ADMIN) { + throw new ForbiddenException('Acesso não autorizado'); + } +} +``` + +Remove `@Public()` from `GET /users/:id`, read `req.user`, call the guard before the service, and apply the same rule to PATCH. In the service reject a non-null `calendly_url` unless the target role is `SPECIALIST`; normalize empty/null removal to `null`. + +- [ ] **Step 4: Migrate public specialist consumers before hardening is committed** + +Add `getPublicSpecialistById(id)` to the specialist service using `/specialists/:id/public-profile`. Replace `getUserById` only in ProductPage and StartProcessForClientModal; ProfilePage continues using the authenticated self endpoint. Update their existing mocks without changing scheduling behavior yet. + +Before production changes, add `StartProcessForClientModal.test.tsx` asserting that specialist display loads through `getPublicSpecialistById` and never invokes `getUserById`. + +- [ ] **Step 5: Run tests and commit** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/users/users.controller.spec.ts src/features/users/users.service.spec.ts +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/services/specialists.service.test.ts src/pages/catalog/ProductPage.test.tsx src/components/processes/StartProcessForClientModal.test.tsx +rtk git add backend/src/features/users frontend/src/services/specialists.service.ts frontend/src/services/specialists.service.test.ts frontend/src/pages/catalog/ProductPage.tsx frontend/src/pages/catalog/ProductPage.test.tsx frontend/src/components/processes/StartProcessForClientModal.tsx frontend/src/components/processes/StartProcessForClientModal.test.tsx +rtk git commit -m "fix: authorize private user profile access" +``` + +Expected: tests PASS and outsider cases do not call Prisma/service. + +--- + +### Task 3: Contrato seguro de pedido pendente e consulta própria + +**Files:** +- Create: `backend/src/features/appointments/dto/check-existing-appointment.dto.ts` +- Create: `backend/src/features/appointments/appointments.controller.spec.ts` +- Create: `backend/src/features/appointments/appointment-schedule-lock.spec.ts` +- Modify: `backend/src/features/appointments/dto/create-pending-appointment.dto.ts` +- Modify: `backend/src/features/appointments/dto/index.ts` +- Modify: `backend/src/features/appointments/entities/appointment.response.ts` +- Modify: `backend/src/features/appointments/appointments.controller.ts` +- Modify: `backend/src/features/appointments/appointments.service.ts` +- Modify: `backend/src/features/appointments/appointments.service.spec.ts` +- Modify: `backend/src/features/appointments/appointment-schedule-lock.ts` +- Modify: `backend/src/features/processes/process-dedup-lock.ts` +- Modify: `backend/src/features/processes/process-dedup-lock.spec.ts` + +**Interfaces:** +- Consumes: `isCalendlySchedulingAvailable` from Task 1. +- Produces: `ExistingAppointmentCheck = { exists: false } | { exists: true; appointment_id; process_id; appointment_status; scheduling_method; appointment_datetime }`. +- Produces: successful pending creation response containing `process_id`. +- Produces: `409/CALENDLY_UNAVAILABLE`, `409/EMAIL_FLOW_UNAVAILABLE` and own-only `409/ACTIVE_PROCESS_EXISTS` snapshot at `error.details.existing_request`. The duplicate snapshot always has `process_id`; appointment fields are nullable because an active process may exist without an appointment. +- Produces: the shared occupation predicate before EMAIL requests can carry a datetime. + +- [ ] **Step 1: Write the schedule occupation matrix tests** + +Preserve the existing ±1-hour conflict window: + +```ts +expect(buildOccupiedScheduleWhere('s1', when)).toMatchObject({ + specialist_id: 's1', + appointment_datetime: { + gte: new Date(when.getTime() - 60 * 60 * 1000), + lte: new Date(when.getTime() + 60 * 60 * 1000), + }, + OR: [ + { status: StatusAgendamento.SCHEDULED }, + { + status: StatusAgendamento.PENDING, + scheduling_method: AppointmentSchedulingMethod.CALENDLY, + calendly_sync_status: CalendlySyncStatus.SYNCED, + }, + { status: StatusAgendamento.PENDING, scheduling_method: null }, + ], +}); +``` + +Test exact boundaries at -60 minutes, +60 minutes and one millisecond outside. Assert `PENDING/EMAIL` and unsynced `PENDING/CALENDLY` never match, and conflict errors contain no competing appointment/client/process IDs. + +- [ ] **Step 2: Run the predicate test and implement the shared builder** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/appointments/appointment-schedule-lock.spec.ts +``` + +Expected RED: the builder does not exist and the old query includes all PENDING records. Implement `buildOccupiedScheduleWhere` and make `assertSpecialistScheduleAvailable` consume it; rerun until PASS before changing EMAIL creation. + +- [ ] **Step 3: Write RED service, dedup and controller tests** + +```ts +await expect(service.createPending(productEmailWithoutDate, customer.id, UserRole.CUSTOMER)).rejects.toThrow(BadRequestException); +await expect(service.createPending(productEmailWithPastDate, customer.id, UserRole.CUSTOMER)).rejects.toThrow(BadRequestException); +await expect(service.createPending(consultancyEmailWithoutDate, customer.id, UserRole.CUSTOMER)).resolves.toBeDefined(); +await expect(service.createPending(calendlyWithClientDate, customer.id, UserRole.CUSTOMER)).rejects.toThrow(BadRequestException); + +expect(await controller.checkExisting(query, customerRequest)).toEqual({ + success: true, + message: 'Consulta realizada com sucesso', + data: { + exists: true, + appointment_id: 'appointment-1', + process_id: 'process-1', + appointment_status: 'PENDING', + scheduling_method: 'EMAIL', + appointment_datetime: proposedDate, + }, +}); +``` + +Freeze the duplicate response shape: + +```ts +expect((error as ConflictException).getResponse()).toEqual({ + success: false, + error: { + code: 'ACTIVE_PROCESS_EXISTS', + message: expect.any(String), + details: { + existing_request: { + appointment_id: null, + process_id: 'process-1', + appointment_status: null, + scheduling_method: null, + appointment_datetime: null, + }, + }, + }, +}); +``` + +Add a second case with an attached `PENDING/EMAIL` appointment asserting the same shape with non-null appointment fields, so ProductPage can recover the e-mail panel only for that owned case. + +Cover the reciprocal method/capability matrix, mismatched `client_id`, non-customer check calls, atomic rollback and direct `POST /appointments` PLATFORM bypass. + +- [ ] **Step 4: Run tests and verify RED** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/appointments/appointments.controller.spec.ts src/features/appointments/appointments.service.spec.ts src/features/processes/process-dedup-lock.spec.ts +``` + +Expected: FAIL on the current EMAIL datetime rejection, arbitrary `client_id`, full Appointment return and direct PLATFORM creation. + +- [ ] **Step 5: Implement DTOs and discriminated responses** + +```ts +export class CheckExistingAppointmentDto { + @IsUUID() specialist_id: string; + @IsEnum(ProductType) product_type: ProductType; + @IsUUID() product_id: string; +} + +export type ExistingAppointmentCheck = + | { exists: false } + | { + exists: true; + appointment_id: string; + process_id: string; + appointment_status: StatusAgendamento; + scheduling_method: AppointmentSchedulingMethod | null; + appointment_datetime: Date | null; + }; + +export interface ActiveProcessSnapshot { + process_id: string; + appointment_id: string | null; + appointment_status: StatusAgendamento | null; + scheduling_method: AppointmentSchedulingMethod | null; + appointment_datetime: Date | null; +} +``` + +Derive customer ID only from JWT. Require a future datetime only for product EMAIL. Reject client datetime for CALENDLY. Validate method against backend capability. Return `process.id` from the creation transaction and only return an existing snapshot after proving ownership. Update `process-dedup-lock.ts` to select and return the exact snapshot above without PII. + +- [ ] **Step 6: Disable the direct PLATFORM path** + +No authorized internal caller exists today. In `AppointmentsService.create`, reject the current direct product scheduling path with a stable `403` before locking/inserting; the product UI must use pending EMAIL or CALENDLY. + +- [ ] **Step 7: Run tests and commit** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/appointments/appointment-schedule-lock.spec.ts src/features/appointments/appointments.controller.spec.ts src/features/appointments/appointments.service.spec.ts src/features/processes/process-dedup-lock.spec.ts +rtk git add backend/src/features/appointments backend/src/features/processes/process-dedup-lock.ts backend/src/features/processes/process-dedup-lock.spec.ts +rtk git commit -m "feat: create dated email appointment requests safely" +``` + +Expected: all contract tests PASS. + +--- + +### Task 4: Aplicar ocupação compartilhada e confirmação canônica + +**Files:** +- Modify: `backend/src/features/appointments/appointments.service.ts` +- Modify: `backend/src/features/processes/processes.service.ts` +- Modify: `backend/src/features/processes/processes.service.spec.ts` +- Modify: `backend/src/features/processes/processes.controller.spec.ts` +- Modify: `backend/src/features/processes/entity/process.response.entity.ts` +- Modify: `backend/src/features/appointments/appointments-concurrency.postgres.spec.ts` + +**Interfaces:** +- Consumes: `buildOccupiedScheduleWhere(specialistId, datetime, excludeAppointmentId?)` from Task 3 in every schedule writer. +- Produces: canonical `ProcessesService.confirmAppointment(processId, specialistId, datetime?)` behavior. +- Produces: assigned-specialist-only contact projection in list and detail. + +- [ ] **Step 1: Write canonical confirmation/contact RED tests** + +Test suggested-time confirmation, changed-time confirmation, future validation, specialist-only authorization, `Appointment=SCHEDULED`, `Process=SCHEDULING`, null reschedule audit fields, proposal/confirmed timestamps in notes, atomic rollback on conflict and idempotent double submission. For both list and detail assert the exact contact matrix: assigned specialist sees client email/phone for `PENDING/EMAIL`, `SCHEDULED` and `COMPLETED`; `PENDING/CALENDLY`, other specialist, OFFICE, CONSULTANT and public/client projections do not receive those contacts early. + +- [ ] **Step 2: Run focused tests and verify RED** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/appointments/appointment-schedule-lock.spec.ts src/features/processes/processes.service.spec.ts src/features/processes/processes.controller.spec.ts +``` + +Expected: FAIL because callers do not yet share the new predicate, contact projections differ and confirmation does not preserve all new invariants. + +- [ ] **Step 3: Apply the shared predicate and implement the canonical transaction** + +Use the same helper in direct creation, confirmation, Calendly callback and reschedule. Confirmation must acquire specialist lock, reread process/appointment in the transaction, validate the chosen future instant, update only the appointment status/date/audit confirmation fields and append notes without setting reschedule audit fields. + +- [ ] **Step 4: Add real PostgreSQL concurrency coverage** + +Exercise `ProcessesService.confirmAppointment`, not `AppointmentsService.confirmPending`: + +```ts +const [first, second] = await Promise.allSettled([ + firstService.confirmAppointment(firstProcessId, specialistId, proposedIso), + secondService.confirmAppointment(secondProcessId, specialistId, proposedIso), +]); +expect([first, second].filter((result) => result.status === 'fulfilled')).toHaveLength(1); +expect(await prisma.appointment.count({ + where: { specialist_id: specialistId, appointment_datetime: proposedDate, status: 'SCHEDULED' }, +})).toBe(1); +``` + +Also cover two concurrent `PENDING/EMAIL` creations for the same specialist/time both succeeding, two specialists at the same time, double-click on one process and absence of partial writes. + +- [ ] **Step 5: Run unit tests and commit** + +```bash +rtk npm --prefix backend test -- --runInBand src/features/appointments/appointment-schedule-lock.spec.ts src/features/processes/processes.service.spec.ts src/features/processes/processes.controller.spec.ts +rtk git add backend/src/features/appointments backend/src/features/processes +rtk git commit -m "fix: confirm email proposals under schedule lock" +``` + +Expected: focused unit tests PASS. PostgreSQL test is executed later with a real URL. + +--- + +### Task 5: Contratos e helpers puros do frontend + +**Files:** +- Create: `frontend/src/lib/email-scheduling.ts` +- Create: `frontend/src/lib/email-scheduling.test.ts` +- Create: `frontend/src/lib/whatsapp.ts` +- Create: `frontend/src/lib/whatsapp.test.ts` +- Create: `frontend/src/services/appointments.service.test.ts` +- Create: `frontend/src/hooks/useCheckAppointment.test.tsx` +- Modify: `frontend/src/lib/appointment-datetime.ts` +- Modify: `frontend/src/lib/appointment-datetime.test.ts` +- Modify: `frontend/src/services/appointments.service.ts` +- Modify: `frontend/src/services/specialists.service.ts` +- Modify: `frontend/src/services/specialists.service.test.ts` +- Modify: `frontend/src/hooks/useCheckAppointment.ts` + +**Interfaces:** +- Produces: `buildEmailSchedulingLinks(input): { mailtoHref; gmailHref; subject; body }`. +- Produces: `buildWhatsAppHref(phone): string | null`. +- Produces: `isoToLocalDateTimeInput(iso): string`. +- Produces: `useCheckAppointment(specialistId, productType, productId)` returning the discriminated own-request check. +- Consumes: backend DTOs from Tasks 1 and 3. + +- [ ] **Step 1: Write helper and service RED tests** + +```ts +const links = buildEmailSchedulingLinks({ + recipient: 'especialista@example.com\r\nBcc:evil@example.com', + specialistName: 'Ana', + clientName: 'João', + productLabel: 'Carro A&B?#', + appointmentDatetime: '2026-10-20T17:30:00.000Z', + timeZone: 'America/Sao_Paulo', +}); +expect(links.mailtoHref).toContain('subject='); +expect(decodeURIComponent(links.mailtoHref)).not.toContain('\r\nBcc:'); +expect(links.gmailHref).toMatch(/^https:\/\/mail\.google\.com\/mail\/\?/); + +expect(buildWhatsAppHref('(11) 98765-4321')).toBe('https://wa.me/5511987654321'); +expect(buildWhatsAppHref('+55 11 98765-4321')).toBe('https://wa.me/5511987654321'); +expect(buildWhatsAppHref('123')).toBeNull(); +``` + +Assert that appointment check sends no `client_id`, EMAIL creation requires datetime at type/runtime boundary, CALENDLY rejects a client datetime type, and public specialist service calls `/specialists/:id/public-profile`. Hook tests use fake timers to cover the 500ms debounce, missing parameters, propagated service error, cleanup on unmount and a stale earlier response not overwriting the latest request. + +Frontend parsing of duplicates must read exactly `response.data.error.code === 'ACTIVE_PROCESS_EXISTS'` and `response.data.error.details.existing_request`, matching Task 3; other 409 responses remain ordinary errors. + +- [ ] **Step 2: Run tests and verify RED** + +```bash +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/lib/email-scheduling.test.ts src/lib/whatsapp.test.ts src/lib/appointment-datetime.test.ts src/services/appointments.service.test.ts src/services/specialists.service.test.ts src/hooks/useCheckAppointment.test.tsx +``` + +Expected: FAIL because helpers and discriminated service contracts do not exist. + +- [ ] **Step 3: Implement pure helpers and types** + +```ts +export type ProductPendingAppointmentInput = + | (BaseProductRequest & { scheduling_method: 'EMAIL'; appointment_datetime: string }) + | (BaseProductRequest & { scheduling_method: 'CALENDLY'; appointment_datetime?: never }); + +export function buildWhatsAppHref(phone: string): string | null { + const digits = phone.replace(/\D/g, ''); + const normalized = /^\d{10,11}$/.test(digits) + ? `55${digits}` + : /^55\d{10,11}$/.test(digits) ? digits : null; + return normalized ? `https://wa.me/${normalized}` : null; +} +``` + +For e-mail, strip CR/LF from recipient and subject, limit subject to 160 and body to 1800 characters, and encode fields separately. Existing check returns a discriminated object and propagates errors rather than converting them to `null`. + +Remove `clientId` from the hook signature and dependency list. Use a monotonically increasing request token so only the latest resolved promise can update `existingAppointment`, `isLoading` or `error`. + +- [ ] **Step 4: Preserve an unchanged ISO in datetime editing** + +Add `isoToLocalDateTimeInput`. Components compare the submitted local value to the initial local value; unchanged sends the original ISO, edited sends `new Date(localValue).toISOString()`. + +- [ ] **Step 5: Run tests and commit** + +```bash +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/lib/email-scheduling.test.ts src/lib/whatsapp.test.ts src/lib/appointment-datetime.test.ts src/services/appointments.service.test.ts src/services/specialists.service.test.ts src/hooks/useCheckAppointment.test.tsx +rtk git add frontend/src/lib frontend/src/services frontend/src/hooks/useCheckAppointment.ts frontend/src/hooks/useCheckAppointment.test.tsx +rtk git commit -m "feat: add safe email scheduling frontend contracts" +``` + +Expected: focused tests PASS. + +--- + +### Task 6: Unificar ProductPage e painel recuperável de e-mail + +**Files:** +- Create: `frontend/src/components/appointments/EmailSchedulingSuccess.tsx` +- Create: `frontend/src/components/appointments/EmailSchedulingSuccess.test.tsx` +- Modify: `frontend/src/components/appointments/NoCalendlySchedulingActions.tsx` +- Modify: `frontend/src/components/appointments/NoCalendlySchedulingActions.test.tsx` +- Modify: `frontend/src/pages/catalog/ProductPage.tsx` +- Modify: `frontend/src/pages/catalog/ProductPage.test.tsx` + +**Interfaces:** +- Consumes: helpers/services from Task 5 and backend capability/check contracts. +- Produces: one CTA `Solicitar reunião` when capability is false and persistent success fallbacks. + +- [ ] **Step 1: Write EmailSchedulingSuccess RED tests** + +```tsx +render(); +expect(screen.getByRole('status')).toBeInTheDocument(); +expect(screen.getByRole('link', { name: /gmail/i })).toHaveAttribute('rel', 'noopener noreferrer'); +await waitFor(() => expect(openMailClient).toHaveBeenCalledTimes(1)); +rerender(); +expect(openMailClient).toHaveBeenCalledTimes(1); +``` + +Cover clipboard success/failure, selectable fallback address, heading focus, `autoOpen=false` and session key `email-request-opened:`. + +- [ ] **Step 2: Write ProductPage RED tests** + +Cover stale URL + capability false, capability true, dated EMAIL payload, no `createPlatformAppointment`, no opener before 201, generic 409 staying an error, own `ACTIVE_PROCESS_EXISTS` reconstruction without auto-open, reload reconstruction, existing CALENDLY/SCHEDULED messaging and double-submit busy behavior. + +- [ ] **Step 3: Run tests and verify RED** + +```bash +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/components/appointments/EmailSchedulingSuccess.test.tsx src/components/appointments/NoCalendlySchedulingActions.test.tsx src/pages/catalog/ProductPage.test.tsx +``` + +Expected: FAIL on the current split EMAIL/PLATFORM UI and eager mail opening. + +- [ ] **Step 4: Implement the unified flow** + +Fetch the public specialist projection. Gate only on `calendly_scheduling_available`. For no Calendly, open `AppointmentDateTimeModal`, create `PENDING/EMAIL` with ISO, render success, then schedule the one-shot external attempt. Recover the same panel from own existing check/duplicate snapshots with `autoOpen=false`. + +- [ ] **Step 5: Run tests and commit** + +```bash +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/components/appointments/EmailSchedulingSuccess.test.tsx src/components/appointments/NoCalendlySchedulingActions.test.tsx src/pages/catalog/ProductPage.test.tsx +rtk git add frontend/src/components/appointments frontend/src/pages/catalog/ProductPage.tsx frontend/src/pages/catalog/ProductPage.test.tsx +rtk git commit -m "feat: unify no-Calendly email request flow" +``` + +Expected: focused tests PASS. + +--- + +### Task 7: Confirmar proposta, WhatsApp e remoção real do Calendly + +**Files:** +- Modify: `frontend/src/components/appointments/AppointmentDateTimeModal.tsx` +- Modify: `frontend/src/components/appointments/AppointmentDateTimeModal.test.tsx` +- Modify: `frontend/src/components/processes/ProcessCard.tsx` +- Modify: `frontend/src/components/processes/ProcessCard.test.tsx` +- Modify: `frontend/src/components/processes/StartProcessForClientModal.tsx` +- Create: `frontend/src/components/processes/StartProcessForClientModal.test.tsx` +- Modify: `frontend/src/pages/customer/ConsultoriaPage.tsx` +- Create: `frontend/src/pages/customer/ConsultoriaPage.test.tsx` +- Modify: `frontend/src/pages/profile/ProfilePage.tsx` +- Create: `frontend/src/pages/profile/ProfilePage.test.tsx` +- Modify: `frontend/src/services/users.service.ts` + +**Interfaces:** +- Consumes: `buildWhatsAppHref`, public Calendly capability and `confirmAppointment`. +- Produces: `AppointmentDateTimeModal.initialValue?: string` and distinct confirm/change actions. + +- [ ] **Step 1: Write modal and ProcessCard RED tests** + +```tsx +expect(screen.getByRole('button', { name: 'Confirmar horário' })).toBeEnabled(); +expect(screen.getByRole('button', { name: 'Alterar e confirmar' })).toBeEnabled(); +await user.click(screen.getByRole('button', { name: 'Confirmar horário' })); +expect(confirmAppointment).toHaveBeenCalledWith(process.id, process.appointment_datetime); +expect(rescheduleAppointment).not.toHaveBeenCalled(); +``` + +Assert changed confirmation uses the modal initial value, a 409 opens/keeps it with inline `role=alert`, busy disables both actions, invalid phone has no `wa.me`, and `SCHEDULED + SCHEDULING` keeps meeting actions. + +- [ ] **Step 2: Write capability/profile regression RED tests** + +Consultoria and StartProcess use the boolean, not stale URL. Consultoria without product can create EMAIL without date. Profile specialist clearing input sends `calendly_url: null`; customer never sends that field. + +- [ ] **Step 3: Run tests and verify RED** + +```bash +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/components/appointments/AppointmentDateTimeModal.test.tsx src/components/processes/ProcessCard.test.tsx src/components/processes/StartProcessForClientModal.test.tsx src/pages/customer/ConsultoriaPage.test.tsx src/pages/profile/ProfilePage.test.tsx +``` + +Expected: FAIL because confirmation is a single action, modal lacks initial value and profile omits empty Calendly URL. + +- [ ] **Step 4: Implement specialist actions and contact links** + +Direct confirmation sends the stored ISO. Alteration opens the modal with `initialValue` and calls the same confirmation endpoint. Do not call reschedule before initial confirmation. Render WhatsApp only from `buildWhatsAppHref`, with `target="_blank" rel="noopener noreferrer"`, while preserving the textual/copyable phone. + +- [ ] **Step 5: Align remaining capability consumers and profile payload** + +Replace raw `calendly_url` gates with the backend boolean in Consultoria and StartProcess. Extend `UpdateUserData.calendly_url` to `string | null` and send null for an emptied specialist field. + +- [ ] **Step 6: Run tests and commit** + +```bash +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 src/components/appointments/AppointmentDateTimeModal.test.tsx src/components/processes/ProcessCard.test.tsx src/components/processes/StartProcessForClientModal.test.tsx src/pages/customer/ConsultoriaPage.test.tsx src/pages/profile/ProfilePage.test.tsx +rtk git add frontend/src/components frontend/src/pages frontend/src/services/users.service.ts +rtk git commit -m "feat: confirm proposed times and expose WhatsApp safely" +``` + +Expected: focused tests PASS. + +--- + +### Task 8: Stack local, E2E real, revisão adversarial e PR + +**Files:** +- Create: `backend/prisma/seed-email-scheduling-e2e.ts` +- Create: `backend/test/email-scheduling.e2e-spec.ts` +- Modify: `backend/package.json` +- Modify: `docs/docs/agendamento-sem-calendly.md` + +**Interfaces:** +- Consumes: the complete backend/frontend behavior from Tasks 1–7. +- Produces: repeatable local fixtures, HTTP assertions, browser evidence and the PR to `develop`. + +- [ ] **Step 1: Add idempotent E2E fixtures and HTTP tests** + +The seed removes only its known deterministic records, never truncates. It creates one customer with phone, assigned specialist without Calendly, another specialist/user and two assigned products. Credentials come from test environment variables. HTTP tests prove own check shape, IDOR rejection, pending creation, assigned contact projection and confirmation state. + +Add the script `"seed:email-scheduling-e2e": "ts-node prisma/seed-email-scheduling-e2e.ts"`. Do not execute it until the database health check and migrations in Step 2 succeed. + +- [ ] **Step 2: Start stack and execute PostgreSQL concurrency test for real** + +```bash +rtk free -h +rtk docker compose up -d db +rtk docker compose exec -T db sh -lc 'until pg_isready -U user -d bmfluxdb; do sleep 1; done' +rtk env DATABASE_URL='postgresql://user:password@localhost:5432/bmfluxdb?schema=public' DIRECT_URL='postgresql://user:password@localhost:5432/bmfluxdb?schema=public' npm --prefix backend exec -- prisma migrate deploy +rtk env DATABASE_URL='postgresql://user:password@localhost:5432/bmfluxdb?schema=public' npm --prefix backend run seed:email-scheduling-e2e +rtk env POSTGRES_CONCURRENCY_TEST_URL='postgresql://user:password@localhost:5432/bmfluxdb?schema=public' node -e "if (!process.env.POSTGRES_CONCURRENCY_TEST_URL) process.exit(1)" +rtk env POSTGRES_CONCURRENCY_TEST_URL='postgresql://user:password@localhost:5432/bmfluxdb?schema=public' npm --prefix backend test -- --runInBand --runTestsByPath src/features/appointments/appointments-concurrency.postgres.spec.ts --json --outputFile=/tmp/high-class-shop-email-scheduling-jest.json +rtk node -e "const r=require('/tmp/high-class-shop-email-scheduling-jest.json');if(!r.success||r.numPendingTests!==0)process.exit(1)" +``` + +Expected: database is healthy, migrations/seed succeed, and the focused concurrency command executes with zero skipped tests and PASS. Keep the existing `describe.skip` behavior when the URL is absent so ordinary unit suites remain independent of PostgreSQL; the explicit precheck and URL in this dedicated gate prevent an accidental skip here. + +- [ ] **Step 3: Run HTTP E2E and browser scenarios** + +```bash +rtk env DATABASE_URL='postgresql://user:password@localhost:5432/bmfluxdb?schema=public' JWT_SECRET_ACCESS='local-e2e-access-secret' JWT_SECRET_REFRESH='local-e2e-refresh-secret' JWT_SECRET_REFERRAL='local-e2e-referral-secret' JWT_SECRET_ADVISOR='local-e2e-advisor-secret' JWT_SECRET_PASSWORD_RESET='local-e2e-reset-secret' npm --prefix backend run test:e2e -- --runInBand --runTestsByPath test/email-scheduling.e2e-spec.ts +``` + +Start backend and frontend from the checked-out source in separate terminal sessions, using the same local-only environment values and `VITE_API_BASE_URL=http://localhost:3000/api`. This avoids stale application images; Docker is used only for PostgreSQL. + +In independent browser contexts: + +1. Customer creates Product A request and inspect mailto/Gmail href without asserting external send. +2. Reload and verify fallbacks persist without another auto-open. +3. Assigned specialist sees proposal/email/phone/WhatsApp, changes and confirms; appointment becomes `SCHEDULED`, process remains `SCHEDULING`, meeting controls remain and reschedule audit stays null. +4. Product B repeats confirmation without change. +5. Unassigned user cannot read contacts, confirm, or access another private GET/PATCH user profile. +6. Repeat the critical request path on mobile viewport and by keyboard. + +Capture request/response status and payloads for creation, check and confirmation. After each confirmation, use a read-only Prisma/SQL query against the deterministic fixture IDs to assert appointment status/date, process status, null reschedule audit fields and exact appointment/process cardinality. Browser-visible assertions alone are insufficient for these database postconditions. + +- [ ] **Step 4: Run full verification sequentially** + +```bash +rtk free -h +rtk git diff --check +rtk npm --prefix backend test -- --maxWorkers=2 +rtk npm --prefix backend run test:e2e -- --runInBand +rtk npm --prefix backend run build +rtk npm --prefix frontend test -- --pool=forks --poolOptions.forks.maxForks=2 +rtk npm --prefix frontend run lint +rtk npm --prefix frontend run build +rtk rg -n 'client_id' frontend/src backend/src/features/appointments | rtk rg 'appointments/check' || true +``` + +Expected: all tests/builds PASS, no schema/migration diff, and no check request sends client identity. + +- [ ] **Step 5: Update documentation and commit E2E evidence code** + +Document the final manual flow, external e-mail limitation, confirmation semantics and contacts. Commit only source/tests/docs, never screenshots containing PII or local credentials. + +```bash +rtk git add backend/package.json backend/prisma/seed-email-scheduling-e2e.ts backend/test docs/docs/agendamento-sem-calendly.md +rtk git commit -m "test: cover no-Calendly email scheduling end to end" +``` + +- [ ] **Step 6: Run adversarial review and resolve every CRITICAL/HIGH** + +Use the `adversarial-review` skill across business rules, authorization/PII, concurrency, frontend UX/accessibility and E2E fidelity. Apply accepted fixes with their own RED/GREEN cycle and repeat affected verification. + +- [ ] **Step 7: Sync with develop, reverify and open PR** + +Fetch `origin/develop`, use `safe-main-sync` if it diverged materially, rerun affected suites/builds, push `codex/fix-no-calendly-email-flow` and create a PR targeting `develop`. Attach the created PR to the task. diff --git a/docs/superpowers/specs/2026-10-13-agendamento-sem-calendly-por-email-design.md b/docs/superpowers/specs/2026-10-13-agendamento-sem-calendly-por-email-design.md new file mode 100644 index 00000000..d546c06b --- /dev/null +++ b/docs/superpowers/specs/2026-10-13-agendamento-sem-calendly-por-email-design.md @@ -0,0 +1,236 @@ +# Agendamento sem Calendly por e-mail + +## Contexto e problema + +Quando o especialista não tem uma integração ativa com o Calendly, a página de produto oferece hoje dois fluxos incompatíveis: + +- o fluxo por e-mail cria um agendamento `PENDING/EMAIL` sem data e abre um `mailto:`; +- o fluxo pela plataforma coleta data e hora, mas cria um agendamento `SCHEDULED/PLATFORM`, pulando a confirmação do especialista e sem abrir o cliente de e-mail. + +O backend reforça essa divisão ao rejeitar data em agendamentos `EMAIL`. Além disso, o especialista não vê o telefone do cliente enquanto o pedido está pendente, a disponibilidade de Calendly é inferida de fontes diferentes no frontend e no backend, e existem respostas públicas que expõem dados pessoais além do necessário. + +## Objetivo + +Unificar o caso sem Calendly em um único pedido de reunião: o cliente propõe data e hora, o sistema registra o pedido pendente, oferece a composição de um e-mail ao especialista e mantém o processo rastreável. O especialista recebe os contatos do cliente, podendo confirmar a sugestão ou alterar a data e confirmar. + +## Fora de escopo + +- enviar e-mail pelo servidor ou garantir que o usuário concluiu o envio no aplicativo externo; +- sincronizar reuniões por e-mail com calendários externos; +- criar novos estados ou novas tabelas para o agendamento; +- implementar expiração automática dos pedidos pendentes; +- alterar o fluxo já conectado ao Calendly, exceto por tornar a detecção da conexão consistente; +- refatorações sem relação direta com privacidade ou com esse fluxo. + +## Decisão de produto + +Na ausência de Calendly, haverá uma única ação, **Solicitar reunião**. Ela abre o seletor de data e hora e, após a confirmação do cliente: + +1. cria atomicamente o `Appointment` com `status=PENDING`, `scheduling_method=EMAIL` e `appointment_datetime` preenchido; +2. cria o `Process` associado no estágio `SCHEDULING`; +3. apresenta o sucesso dentro da aplicação e tenta abrir o cliente padrão com um `mailto:`; +4. mantém alternativas visíveis para abrir novamente o cliente padrão, abrir o Gmail Web, copiar o e-mail do especialista e acompanhar o processo, inclusive após recarregar ou revisitar a página. + +O horário pendente é uma proposta, não uma reserva. Ele não bloqueia o horário do especialista. Somente a confirmação transforma a proposta em compromisso e deve validar conflitos novamente. + +## Fluxo do cliente + +### Especialista com Calendly ativo + +O comportamento permanece o atual: a interface oferece o fluxo Calendly e o backend só aceita `scheduling_method=CALENDLY` se a capacidade estiver ativa para o especialista. + +### Especialista sem Calendly ativo + +1. O cliente autenticado seleciona um produto e aciona **Solicitar reunião**. +2. O modal exige uma data/hora futura e exibe o fuso horário local usado na apresentação. +3. O frontend envia a data em ISO 8601 para `POST /appointments/pending` com `scheduling_method=EMAIL`. +4. Após `201`, a página mostra o estado de sucesso antes de iniciar a navegação externa. O painel também é reconstruído após reload ou revisita quando a consulta autenticada encontra o próprio pedido `PENDING/EMAIL` com data. +5. O e-mail pré-preenchido contém: + - destinatário: e-mail profissional do especialista; + - assunto: interesse no produto e nome do produto; + - corpo: nome do cliente, produto, data/hora sugerida com fuso e um texto editável de interesse. +6. A tentativa automática de `mailto:` é complementar e ocorre no máximo uma vez para o appointment recém-criado, controlada pelo ID em memória/sessão. Ela nunca se repete por rerender, reload, retorno do histórico ou recuperação de duplicidade. O pedido criado continua válido se o navegador bloquear a navegação ou se não houver aplicativo padrão configurado. +7. A tela mantém as ações de fallback **Abrir aplicativo de e-mail**, **Abrir no Gmail**, **Copiar e-mail** e **Acompanhar processo**. O Gmail usa `https://mail.google.com/mail/?view=cm&fs=1...` em nova aba com `noopener noreferrer`; não há tentativa de detectar o provedor do usuário. + +Erros de criação nunca abrem o cliente de e-mail. Um `409` só é tratado como pedido já existente quando o backend devolver o código de erro específico desse caso. Nesse caso, a resposta autorizada traz o snapshot mínimo do próprio pedido e a UI recupera o painel de sucesso, sem autoabrir o e-mail. Um processo ativo de outro método ou estágio apenas orienta o cliente a acompanhá-lo. Conflitos genéricos continuam sendo exibidos como erro. + +O assunto e o corpo são sugestões editáveis somente no compositor externo; a aplicação não captura nem persiste esse texto. Um helper puro monta os links, remove CR/LF de destinatário e assunto, limita o comprimento dos valores e aplica percent-encoding separado. O corpo preserva as quebras de linha intencionais. + +## Fluxo do especialista + +No card do processo em `SCHEDULING`, o especialista atribuído vê: + +- data e hora propostas pelo cliente; +- e-mail do cliente; +- telefone do cliente, quando preenchido; +- atalho para WhatsApp somente quando o telefone puder ser normalizado para um número válido; +- ação **Confirmar horário**; +- ação **Alterar e confirmar** com seletor de data/hora. + +As duas ações usam o endpoint canônico de confirmação do processo. Confirmar a sugestão envia a própria `appointment_datetime`; alterar e confirmar envia o novo horário. Em ambos os casos, o `Appointment` é atualizado para `SCHEDULED`, enquanto o `Process` permanece em `SCHEDULING`. Esse estado é necessário para iniciar ou entrar na reunião; o processo só avança no fluxo já existente após a conversa/reunião e a associação de produto quando ela for exigida. + +A alteração feita antes da primeira confirmação não consome nem preenche os campos de uma remarcação posterior. Os campos de auditoria de remarcação passam a ser usados apenas depois de um horário já confirmado. Se a data for alterada na confirmação, a proposta original e o horário confirmado são anexados ao histórico/notas do processo; a UI do cliente passa a mostrar o horário efetivamente confirmado. + +## Modelo de dados e regras + +Não haverá migração. O modelo existente representa o fluxo: + +- `Appointment.status = PENDING`; +- `Appointment.scheduling_method = EMAIL`; +- `Appointment.appointment_datetime = horário proposto`; +- `Process.status = SCHEDULING`. + +Para novos pedidos `EMAIL` com produto, `appointment_datetime` é obrigatório, deve ser uma data ISO válida e futura. Em consultoria sem produto ele permanece opcional e deve ser informado pelo especialista na confirmação. Registros legados `EMAIL` sem data continuam legíveis e aparecem ao especialista como pedido sem horário definido, exigindo **Alterar e confirmar**. + +Um único helper de domínio define compromissos que ocupam agenda e é usado na criação direta, confirmação, callback Calendly e reagendamento. Pedidos `PENDING/EMAIL` não entram nesse predicado porque são propostas não confirmadas. Continuam ocupando agenda: + +- agendamentos `SCHEDULED`; +- agendamentos `PENDING/CALENDLY` com `calendly_sync_status=SYNCED` e horário; +- registros legados pendentes com horário e sem método definido, preservando compatibilidade. + +Na confirmação, o backend adquire o lock já usado para a agenda do especialista, relê o compromisso dentro da transação, valida conflito para o horário escolhido e só então atualiza agendamento e processo. Respostas de conflito não retornam IDs de clientes, processos ou agendamentos concorrentes. + +O campo existente `pending_expires_at` continua sendo preenchido, mas a expiração automática e seus efeitos sobre `Appointment` e `Process` permanecem fora desta entrega porque não existe estado de processo expirado. O risco conhecido é que pedidos abandonados continuam ativos até cancelamento/recusa. O plano não deve sugerir que sete dias já sejam aplicados como regra de negócio. + +## Contratos de API + +### Criar pedido pendente + +`POST /appointments/pending` + +- `EMAIL` com produto: exige `appointment_datetime` válido e futuro; consultoria sem produto preserva o campo opcional; +- `CALENDLY`: exige que o especialista possua capacidade Calendly ativa; +- `EMAIL` com produto é aceito somente quando a capacidade Calendly estiver inativa; `CALENDLY` é aceito somente quando ela estiver ativa; +- `CALENDLY` rejeita `appointment_datetime` enviado pelo cliente; apenas callback/webhook sincronizado pode preenchê-lo; +- a criação do agendamento e do processo é atômica; +- a resposta retorna o appointment e seu `process_id`, ambos pertencentes ao cliente autenticado, sem dados de terceiros. + +O caminho direto `POST /appointments`, hoje usado para criar `SCHEDULED/PLATFORM`, deixa de aceitar esse cenário para cliente e produto. Um cliente HTTP sem Calendly deve usar o pedido pendente `EMAIL`; ele não pode contornar a confirmação do especialista criando um compromisso direto. + +### Confirmar pelo processo + +`POST /processes/:processId/confirm-appointment` + +- permitido somente ao especialista atribuído; administradores podem inspecionar conforme as permissões existentes, mas não confirmam em nome dele; +- aceita o horário sugerido ou um novo horário futuro; +- confirma o appointment sob lock e mantém o processo em `SCHEDULING`; +- não registra a primeira alteração como remarcação. + +O endpoint alternativo de confirmação direta de appointment não será usado pelo frontend desse fluxo, evitando semânticas diferentes para o avanço do processo. + +### Consultar pedido existente + +`GET /appointments/check` é uma consulta de pedido existente, não de disponibilidade de horário, aceita somente `CUSTOMER` e deixa de receber `client_id`. O cliente vem exclusivamente do JWT e a consulta aceita apenas especialista e produto. A resposta discriminada é: + +- `{ exists: false }`; ou +- `{ exists: true, appointment_id, process_id, appointment_status, scheduling_method, appointment_datetime }` para um appointment pertencente ao próprio cliente. + +Ela não contém nomes, e-mails, telefones nem IDs de outros clientes. Esses dados são suficientes para a página escolher entre o CTA, o aviso de processo existente e a recuperação do painel de e-mail. + +### Projeção pública do especialista + +A página de produto usa `GET /specialists/:id/public-profile`, uma projeção dedicada com apenas os campos necessários para exibição e contato comercial. Antes de endurecer o endpoint genérico, seus consumidores de exibição de especialista, incluindo o modal de abertura de processo, migram para essa projeção. As listagens públicas `GET /specialists` e `GET /specialists/grouped-by-category` reutilizam o mesmo serializer seguro e deixam de selecionar CPF/CNPJ e RG. `GET /users/:id`, que hoje pode devolver CPF, RG, telefone e estado civil, passa a aceitar somente o próprio usuário ou `ADMIN`; os demais recebem `403`. + +Como a remoção da URL do Calendly passa por `PATCH /users/:id`, esse endpoint também deve validar o alvo: somente o próprio usuário ou um `ADMIN` pode alterá-lo. Além disso, somente usuários `SPECIALIST` podem definir `calendly_url`; `null` continua permitido para remover o valor. Conhecer o UUID de outra conta não autoriza a edição. A correção e o teste de IDOR fazem parte desta entrega porque, sem ela, qualquer usuário autenticado poderia modificar a configuração de Calendly e outros dados do perfil de terceiros. + +## Fonte de verdade do Calendly + +A aplicação terá um único campo derivado no backend, `calendly_scheduling_available`. Para este fluxo ele é `true` somente quando existe uma URL HTTPS cujo hostname pertence ao Calendly **e** uma `CalendlyConnection` com `is_active=true`. Token de acesso expirado não desativa a capacidade enquanto o refresh continua válido; uma falha definitiva como `invalid_grant` marca a conexão como inativa. + +O backend devolve essa capacidade na projeção usada pela página do produto, e o frontend escolhe o fluxo com base nela. O backend repete a validação ao criar o pedido para impedir bypass pelo cliente HTTP. + +O callback OAuth persiste também a `scheduling_url` devolvida pelo Calendly como `calendly_url`, para que uma conexão válida tenha o link necessário ao popup. Ao desconectar, a conexão é desativada e URL/URIs derivados são limpos na mesma transação. A edição de perfil envia `null` ao apagar a URL, em vez de omitir o campo e preservar o valor antigo. + +O backend aplica a exigência de data ao `EMAIL` relacionado a produto (`product_id` presente). A consultoria sem produto mantém o contrato atual de `PENDING/EMAIL` sem data, evitando ampliar esta correção para um segundo fluxo de produto. Ela continua exigindo definição do horário pelo especialista ao confirmar. + +## Privacidade e autorização dos contatos + +Enquanto o pedido `PENDING/EMAIL` estiver no estágio `SCHEDULING`, somente o especialista atribuído pode ver e-mail e telefone do cliente. Essa projeção é aplicada tanto na listagem `GET /processes/specialist/:specialistId` quanto no detalhe `GET /processes/:id`, sempre validando que o usuário autenticado é o especialista da rota/processo. Ela continua disponível ao especialista atribuído durante `SCHEDULED`, `COMPLETED` e no histórico do processo. As listagens de cliente, `OFFICE`, `CONSULTANT`, outros especialistas e respostas públicas não recebem esses contatos por causa desse estado; `ADMIN` só os recebe nos endpoints administrativos que já exigem esse papel, nunca por herança de uma projeção pública. + +O cliente não passa a ver o telefone privado do especialista antes da confirmação. O e-mail comercial necessário para compor a mensagem vem da projeção segura do produto/especialista. Esse e-mail comercial é intencionalmente público e, portanto, sujeito a coleta automatizada; a projeção pública fica limitada a ID, nome comercial, especialidade, e-mail comercial, URL de agendamento e o booleano de capacidade, nunca documentos, telefone pessoal, estado civil, tokens, URIs OAuth ou detalhes da conexão. + +## Componentes de frontend + +- `ProductPage`: escolhe Calendly ou solicitação por e-mail usando a capacidade devolvida pelo backend; remove a bifurcação atual entre `EMAIL` sem data e `PLATFORM` já confirmado. +- `AppointmentDateTimeModal`: coleta a proposta futura e aceita `initialValue`. Na ação **Alterar e confirmar**, converte o ISO existente para `datetime-local` no fuso do navegador. Se o campo não for editado, envia o ISO original e preserva exatamente o instante; se o usuário editar uma hora local ambígua em transição de horário de verão, vale o offset escolhido pelo navegador. +- componente dedicado de sucesso do pedido: concentra `mailto:`, Gmail, cópia do endereço e navegação ao processo, mantendo a página de produto focada na orquestração. +- `ProcessCard`: separa explicitamente **Confirmar horário** de **Alterar e confirmar** e exibe os contatos autorizados. +- serviço de appointments: representa o contrato `PENDING/EMAIL` com data obrigatória e não chama a criação `PLATFORM` nesse cenário. +- perfil: permite remover de fato a URL do Calendly. + +## Tratamento de erros + +- data ausente, inválida ou passada: `400` com mensagem específica; +- `CALENDLY` solicitado sem capacidade ativa: `409/CALENDLY_UNAVAILABLE` e orientação para usar o fluxo por e-mail; +- `EMAIL` com produto solicitado quando há capacidade Calendly ativa: `409/EMAIL_FLOW_UNAVAILABLE`; +- pedido ativo duplicado: `409/ACTIVE_PROCESS_EXISTS`, devolvendo `process_id` e o snapshot mínimo somente depois de comprovar que o cliente autenticado é o dono; +- conflito descoberto na confirmação: `409` sem PII e com orientação para escolher outro horário; +- falha ao criar pedido/processo: transação revertida e nenhuma tentativa de abrir e-mail; +- falha ao abrir aplicativo externo: pedido permanece criado e fallbacks continuam disponíveis; +- telefone ausente: o atalho de telefone/WhatsApp não é exibido; telefone preenchido mas não normalizável: o valor original é exibido como texto, sem gerar link `wa.me` incorreto. + +Ao receber `409` em **Confirmar horário**, o frontend abre e mantém o modal **Alterar e confirmar**, pré-preenchido com a proposta e com erro inline associado ao campo. Os botões ficam desabilitados e com estado busy durante a requisição para impedir dupla submissão. + +O backend recebe e armazena um instante UTC (`toISOString()`). A interface mostra o fuso IANA do navegador, e o corpo do e-mail formata o instante nesse fuso, por exemplo `20/10/2026 14:30 (America/Sao_Paulo)`. O fuso não é persistido separadamente. + +Para WhatsApp, o helper remove caracteres não numéricos; números brasileiros com 10 ou 11 dígitos recebem prefixo `55`, e números com 12 ou 13 dígitos iniciados por `55` são aceitos. Os demais não geram link. O link usa `https://wa.me/` em nova aba com `noopener noreferrer`, mantendo o número original visível para o especialista. + +O painel recebe foco no título após a criação, anuncia sucesso com `role=status`/`aria-live=polite` e erros com `role=alert`. O modal preserva foco, rótulos, `aria-describedby` para erros e devolve o foco ao acionador. Falha ou indisponibilidade do clipboard mantém o endereço selecionável e anuncia que a cópia não ocorreu. + +## Estratégia de testes + +### Backend + +- TDD para exigir horário futuro no `PENDING/EMAIL` com produto, preservar consultoria sem produto e aceitar registros legados na leitura; +- teste da transação de criação `Appointment + Process`; +- teste da matriz de capacidade Calendly, incluindo URL/domínio, OAuth ativo/inativo, disconnect, data proibida no `CALENDLY` e rejeição recíproca de método; +- teste de bypass comprovando que o cliente não cria `SCHEDULED/PLATFORM` por `POST /appointments`; +- teste de confirmação no mesmo horário e em horário alterado; +- testes concorrentes PostgreSQL: duas propostas diferentes para o mesmo especialista/horário são aceitas, confirmações simultâneas deixam exatamente uma `SCHEDULED`, duplo clique não duplica histórico e especialistas diferentes podem usar o mesmo horário; +- teste de que o predicado central ignora propostas `PENDING/EMAIL` em todos os chamadores; +- testes de autorização e projeção de contatos em lista e detalhe; +- teste de IDOR em `PATCH /users/:id`, permitindo somente o próprio usuário ou `ADMIN`; +- teste de que não especialista não altera `calendly_url`; +- testes de não exposição de PII na consulta de pedido, conflitos e perfil público/privado. + +### Frontend + +- TDD do único CTA e do envio de `appointment_datetime` no fluxo sem Calendly; +- teste de que o e-mail só é aberto após resposta de sucesso e no máximo uma vez por appointment; +- teste das alternativas de e-mail e recuperação após reload/duplicidade; +- teste do helper de composição com acentos, `&`, `?`, `#`, CR/LF e valores longos; +- teste do tratamento específico de duplicidade sem confundir outros `409`; +- teste das ações distintas de confirmar e alterar/confirmar, incluindo valor inicial, preservação do ISO quando inalterado, escolha do navegador em horário DST editado e conflito inline; +- teste de telefone ausente ou inválido e da remoção da URL do Calendly. + +### E2E local + +Com a stack local, dois produtos/processos e três identidades — cliente com telefone, especialista atribuído e outro usuário/especialista — em contextos de navegador independentes: + +1. publicar ou selecionar produto de especialista sem Calendly; +2. como cliente, escolher uma data futura e criar o pedido; +3. verificar a URL `mailto:`/Gmail gerada, sem afirmar que um e-mail externo foi enviado; +4. verificar processo pendente e persistência da proposta; +5. como especialista atribuído, verificar e-mail, telefone e WhatsApp do cliente; +6. alterar e confirmar o horário; +7. verificar o agendamento `SCHEDULED`, o processo ainda em `SCHEDULING`, os controles da reunião e a ausência de consumo de remarcação; +8. repetir o caminho confirmando a sugestão sem alteração; +9. validar que usuário não atribuído não recebe os contatos. + +O E2E inspeciona o `href` de `mailto:` sem navegar para um aplicativo externo. O caminho Gmail só é aberto em aba controlável quando houver sessão apropriada. O cenário crítico é repetido em viewport móvel e com navegação por teclado. + +## Critérios de aceite + +- sem Calendly, o cliente sempre informa data e hora antes de criar o pedido; +- a criação resulta em `PENDING/EMAIL`, não em `SCHEDULED/PLATFORM`; +- o cliente consegue iniciar um e-mail com destinatário, assunto e corpo pré-preenchidos e possui fallbacks persistentes; +- o especialista atribuído vê a proposta, o e-mail e o WhatsApp/telefone válido do cliente; +- o especialista pode confirmar ou alterar e confirmar; +- somente a confirmação reserva o horário; o processo permanece em `SCHEDULING` para permitir a reunião; +- o backend impede bypass do tipo de integração e confirma sob lock; +- erros não disparam composição de e-mail indevidamente; +- endpoints tocados pelo fluxo não expõem dados pessoais a usuários não autorizados; +- a edição de perfil rejeita tentativas de alterar outro usuário sem papel `ADMIN`; +- recarregar ou revisitar a página recupera os fallbacks do próprio pedido sem repetir a abertura automática do e-mail; +- a consultoria sem produto continua podendo criar pedido `PENDING/EMAIL` sem data; +- testes automatizados e o E2E local cobrem os dois lados do fluxo. diff --git a/docs/superpowers/specs/2026-10-13-remover-modal-global-calendly-design.md b/docs/superpowers/specs/2026-10-13-remover-modal-global-calendly-design.md index 611e0a28..a11967da 100644 --- a/docs/superpowers/specs/2026-10-13-remover-modal-global-calendly-design.md +++ b/docs/superpowers/specs/2026-10-13-remover-modal-global-calendly-design.md @@ -25,4 +25,3 @@ Nenhum novo tratamento é necessário. Ao remover a consulta global, falhas no e - Alterar OAuth, webhooks ou sincronização do Calendly. - Alterar agendamentos ou a página de perfil. - Alterar autorização, validação ou persistência de produtos no backend. - diff --git a/frontend/src/components/admin/AdminCreateProcessDialog.tsx b/frontend/src/components/admin/AdminCreateProcessDialog.tsx new file mode 100644 index 00000000..664cb07e --- /dev/null +++ b/frontend/src/components/admin/AdminCreateProcessDialog.tsx @@ -0,0 +1,115 @@ +import { useEffect, useState } from "react"; +import { useAdminSpecialistJourney } from "../../contexts/AdminSpecialistJourneyContext"; +import { + getAdminClientOptions, + getAdminSpecialistProducts, + type AdminCatalogProduct, + type AdminClientOption, +} from "../../services/admin-specialist-journey.service"; +import { createProcess } from "../../services/processes.service"; +import Button from "../ui/button"; +import { Dialog, DialogContent } from "../ui/dialog"; + +export default function AdminCreateProcessDialog({ + open, + onClose, + onCreated, +}: { + open: boolean; + onClose: () => void; + onCreated: () => void; +}) { + const context = useAdminSpecialistJourney(); + const [clients, setClients] = useState([]); + const [products, setProducts] = useState([]); + const [clientId, setClientId] = useState(""); + const [productId, setProductId] = useState(""); + const [notes, setNotes] = useState(""); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + if (!open || !context) return; + setError(null); + void Promise.all([ + getAdminClientOptions(), + getAdminSpecialistProducts(context.specialist.speciality, 1, 100), + ]) + .then(([clientOptions, catalog]) => { + setClients(clientOptions); + setProducts(catalog.products.filter((product) => product.is_active)); + }) + .catch(() => setError("Não foi possível carregar clientes e produtos.")); + }, [open, context?.targetSpecialistId]); + + if (!context) return null; + + const submit = async (event: React.FormEvent) => { + event.preventDefault(); + if (!clientId) return; + setSubmitting(true); + setError(null); + try { + await createProcess({ + client_id: clientId, + specialist_id: context.targetSpecialistId, + ...(productId + ? { + product_id: productId, + product_type: context.specialist.speciality, + } + : {}), + notes: notes || undefined, + }); + setClientId(""); + setProductId(""); + setNotes(""); + onCreated(); + onClose(); + } catch (caught: any) { + setError( + caught?.friendlyMessage || + caught?.response?.data?.message || + "Não foi possível criar o processo e seu agendamento.", + ); + } finally { + setSubmitting(false); + } + }; + + return ( +

!next && onClose()}> + +
+

+ O processo e o agendamento pendente por e-mail serão criados juntos + para {context.specialist.name}. +

+ {error &&

{error}

} + + +