Skip to content

feat(api): make the Prospector ↔ CRM contract work end to end - #92

Merged
juancodedev merged 4 commits into
mainfrom
feat/prospector-crm-contract
Nov 13, 2026
Merged

juancodedev merged 4 commits into
mainfrom
feat/prospector-crm-contract

Conversation

@juancodedev

Copy link
Copy Markdown
Owner

Qué cambia

Cierra el contrato que el Prospector necesita para bailar con el CRM. Los ocho puntos del pedido, uno por uno:

  1. [Blocker] El upsert ya no pisa lo que no enviaste. Los defaults (status: "Nuevo", name = compañía) viven solo en el DTO de creación. Si el lead existe, se escribe únicamente lo que mandó el cliente. Test de regresión textual del pedido: crear con status: "Interesado", reenviar sin status, esperar "Interesado".
  2. null = conservar, "" = borrar. Aplica al upsert y a PATCH /api/leads/{id}. Además, null ya no es un 400: los campos opcionales son nullish.
  3. API key en notas, actividades y estado. POST /api/notes, POST /api/activities y PATCH /api/leads/{id}/status aceptan X-API-Key. Como esas requests usan el cliente service-role (bypassa RLS), cada query se filtra por user_id del dueño de la key, y una nota/actividad que apunte al lead de otro usuario se rechaza.
  4. externalId en notas y actividades. Único por usuario, con el mismo comportamiento que leads: 201 al crear, 200 al actualizar. Migración nueva.
  5. Siempre devuelve el id. 200 y 201 de POST /api/leads incluyen id. Ningún /api/* redirige.
  6. 400 con campo culpable. { "error": "...", "fields": { "rating": "Expected number" } }.
  7. Números tolerantes. rating, reviewsCount, opportunityScore, estimatedValue aceptan número o string numérico ("4.9" → 4.9).
  8. Mapeo de nombres documentado (el punto 4 del pedido llegó cortado): tabla en README.md y en /api/docs.

Fuera de alcance: el punto 8 del pedido (sync do-not-contact CRM → Prospector) está marcado "Phase 2" y no se implementa acá.

Archivos

Archivo Cambio
src/core/application/leads/leadPayload.ts DTO de creación vs patch parcial; defaults solo al crear
src/core/domain/LeadSchema.ts Schemas nullish, números tolerantes, "" para limpiar
src/app/api/leads/route.ts Upsert con create + patch, errores por campo
src/infrastructure/repositories/SupabaseLeadRepository.ts upsertByExternalId(externalId, create, patch)
src/infrastructure/repositories/BaseRepository.ts scopedUserId, resolveUserId, scopeToUser
src/app/api/notes/route.ts, src/app/api/activities/route.ts API key + externalId
src/app/api/leads/[id]/status/route.ts API key + repos scopeados + actor de auditoría
supabase/migrations/20261113000000_notes_activities_external_id.sql external_id + índices únicos parciales
src/lib/api/validation.ts, src/lib/api/api-handler.ts { error, fields }
src/app/api/docs/openapi.json/route.ts, README.md Contrato + tabla de mapeo

Cómo se probó

  • tsc --noEmit limpio
  • jest: 115 suites / 855 tests
  • eslint .: 0 errores (12 warnings preexistentes)
  • End-to-end contra producción: falta crear una API key real y mandar el mismo POST /api/leads dos veces con externalId (201 y después 200)

Antes de mergear

⚠️ La migración 20261113000000_notes_activities_external_id.sql no está aplicada en producción. El gate Verify production schema matches the app contract compara database.types.ts contra el schema real y va a fallar el deploy si se mergea sin aplicarla. Aplicarla desde el SQL Editor de Supabase primero.

Risk: item 3 (cambia el contrato público de /api/leads: null deja de ser 400, y los defaults solo aplican al crear) y item 1 (migración nueva con índices únicos).

Validation failures now answer { error, fields } so an integration UI can
show which field failed instead of a generic message. The first message per
field wins, keeping the most specific one Zod reported.
POST /api/leads built a single DTO with status 'Nuevo' and name = company,
then fed it to the update path, so every re-send reset the status the user
had set in the CRM.

Defaults now live only in the create DTO. An existing lead receives only the
fields the client sent: null or absent keeps the stored value, "" clears a
clearable one. Numbers accept numeric strings, and null no longer 400s.
The Prospector can now log each sent email as a COMPLETED activity with its
date, store research as a note instead of overwriting the lead's notes field,
and change the status when the user answers.

API-key requests run on the service-role client, which bypasses RLS, so the
base repository resolves the key owner and scopes every query by user_id; a
note or activity pointing at another user's lead or idea is rejected.

Notes and activities take an optional externalId, unique per user, so pressing
the button twice upserts (201 create, 200 update) instead of duplicating rows.
README and /api/docs now describe the partial upsert (null keeps, "" clears),
the tolerant numeric fields, the { error, fields } shape, the apiKeyAuth
coverage on notes/activities/status, and the mapping from Prospector's names
to the CRM columns.
@juancodedev
juancodedev merged commit b89fd2b into main Nov 13, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant