Repository navigation
feat(api): make the Prospector ↔ CRM contract work end to end - #92
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Qué cambia
Cierra el contrato que el Prospector necesita para bailar con el CRM. Los ocho puntos del pedido, uno por uno:
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 constatus: "Interesado", reenviar sinstatus, esperar"Interesado".null= conservar,""= borrar. Aplica al upsert y aPATCH /api/leads/{id}. Además,nullya no es un 400: los campos opcionales sonnullish.POST /api/notes,POST /api/activitiesyPATCH /api/leads/{id}/statusaceptanX-API-Key. Como esas requests usan el cliente service-role (bypassa RLS), cada query se filtra poruser_iddel dueño de la key, y una nota/actividad que apunte al lead de otro usuario se rechaza.externalIden notas y actividades. Único por usuario, con el mismo comportamiento que leads: 201 al crear, 200 al actualizar. Migración nueva.id. 200 y 201 dePOST /api/leadsincluyenid. Ningún/api/*redirige.{ "error": "...", "fields": { "rating": "Expected number" } }.rating,reviewsCount,opportunityScore,estimatedValueaceptan número o string numérico ("4.9"→4.9).README.mdy 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
src/core/application/leads/leadPayload.tssrc/core/domain/LeadSchema.tsnullish, números tolerantes,""para limpiarsrc/app/api/leads/route.tssrc/infrastructure/repositories/SupabaseLeadRepository.tsupsertByExternalId(externalId, create, patch)src/infrastructure/repositories/BaseRepository.tsscopedUserId,resolveUserId,scopeToUsersrc/app/api/notes/route.ts,src/app/api/activities/route.tsexternalIdsrc/app/api/leads/[id]/status/route.tssupabase/migrations/20261113000000_notes_activities_external_id.sqlexternal_id+ índices únicos parcialessrc/lib/api/validation.ts,src/lib/api/api-handler.ts{ error, fields }src/app/api/docs/openapi.json/route.ts,README.mdCómo se probó
tsc --noEmitlimpiojest: 115 suites / 855 testseslint .: 0 errores (12 warnings preexistentes)POST /api/leadsdos veces conexternalId(201 y después 200)Antes de mergear
20261113000000_notes_activities_external_id.sqlno está aplicada en producción. El gateVerify production schema matches the app contractcomparadatabase.types.tscontra 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:nulldeja de ser 400, y los defaults solo aplican al crear) y item 1 (migración nueva con índices únicos).