feat(alta): guardado progresivo por etapa con réplica a Monday
- Al avanzar cada paso del wizard: upsert silencioso del borrador local + sync a Monday (iniciar → Contacto en PROSPECTO; pasos siguientes → PATCH con los campos mapeables: datos generales, dirección armada, actividad económica) - Al completar: Contacto pasa a CLIENTE + Apartado + funnel (dedup) - progresoId viaja con el borrador (se restaura solo); fallos de sync no bloquean el avance (aviso ámbar no bloqueante); submit final con fallback al endpoint legado si nunca hubo sync - API: POST /clientes/progreso/iniciar, PATCH /clientes/progreso/:id, POST /clientes/progreso/:id/completar; POST /clientes legado intacto - Tests: API 338 (+16), alta-clientes 112 (+4); smoke en vivo verificado (PROSPECTO → patch → CLIENTE + Apartado) y limpiado
This commit is contained in:
@@ -5,7 +5,7 @@ import { randomUUID } from 'node:crypto'
|
||||
import multer from 'multer'
|
||||
import { z } from 'zod'
|
||||
import { config } from '../config/index.js'
|
||||
import { mondayService } from '../services/monday.service.js'
|
||||
import { mondayService, type DatosContacto } from '../services/monday.service.js'
|
||||
import { funnelService } from '../services/funnel.service.js'
|
||||
import { prismaStateStore } from '../services/automatizaciones.service.js'
|
||||
import { prisma } from '../services/prisma.js'
|
||||
@@ -157,6 +157,45 @@ const hoyMas = (dias: number): string => {
|
||||
return `${d.getFullYear()}-${m}-${dia}`
|
||||
}
|
||||
|
||||
// ---------- Helpers compartidos (alta directa y alta progresiva) ----------
|
||||
|
||||
/**
|
||||
* Si el alta viene de un lead del funnel (la app alta-clientes manda
|
||||
* leadMondayId en la raíz del payload), su oportunidad pasa a 'Aparto'.
|
||||
* moverAApartoConDedup escribe el dedup `apartado-creado:<opId>` ANTES del
|
||||
* cambio de etapa, para que el webhook/cron no cree un Apartado duplicado.
|
||||
* Un fallo aquí no rompe el alta.
|
||||
*/
|
||||
async function moverLeadAApartoSiAplica(body: Record<string, unknown>): Promise<void> {
|
||||
const leadMondayId = body['leadMondayId']
|
||||
if (typeof leadMondayId === 'string' && leadMondayId !== '') {
|
||||
try {
|
||||
await funnelService.moverAApartoConDedup(leadMondayId, prismaStateStore)
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`No se pudo mover a 'Aparto' la oportunidad del lead ${leadMondayId}:`, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Item en el tablero Apartado (pipeline Enkontrol); solo si hay valor de venta */
|
||||
async function crearApartadoSiAplica(
|
||||
dg: { nombreCompleto: string },
|
||||
vc: { ubicacion?: string | undefined; valorVenta?: string | number | undefined; enganche?: string | number | undefined },
|
||||
): Promise<string | null> {
|
||||
const valorVenta = aNumero(vc.valorVenta)
|
||||
if (valorVenta <= 0) return null
|
||||
const enganche = aNumero(vc.enganche)
|
||||
return mondayService.crearApartado({
|
||||
clienteNombre: dg.nombreCompleto,
|
||||
unidadCodigo: vc.ubicacion ?? '',
|
||||
...(enganche > 0 ? { montoApartado: enganche } : {}),
|
||||
fechaApartado: hoyMas(0),
|
||||
fechaLimite: hoyMas(15),
|
||||
estadoLabel: 'Pago Apartado', // primer paso del pipeline Enkontrol
|
||||
})
|
||||
}
|
||||
|
||||
/** POST /api/clientes — persiste el alta y la replica en Monday (Contactos y Apartado) */
|
||||
export async function crearCliente(req: Request, res: Response): Promise<void> {
|
||||
const body = crearClienteSchema.parse(req.body)
|
||||
@@ -177,20 +216,7 @@ export async function crearCliente(req: Request, res: Response): Promise<void> {
|
||||
},
|
||||
})
|
||||
|
||||
// Si el alta viene de un lead del funnel (la app alta-clientes manda
|
||||
// leadMondayId en la raíz del payload), su oportunidad pasa a 'Aparto'.
|
||||
// moverAApartoConDedup escribe el dedup `apartado-creado:<opId>` ANTES del
|
||||
// cambio de etapa, para que el webhook/cron no cree un Apartado duplicado.
|
||||
// Un fallo aquí no rompe el alta.
|
||||
const leadMondayId = (body as Record<string, unknown>)['leadMondayId']
|
||||
if (typeof leadMondayId === 'string' && leadMondayId !== '') {
|
||||
try {
|
||||
await funnelService.moverAApartoConDedup(leadMondayId, prismaStateStore)
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`No se pudo mover a 'Aparto' la oportunidad del lead ${leadMondayId}:`, err)
|
||||
}
|
||||
}
|
||||
await moverLeadAApartoSiAplica(body as Record<string, unknown>)
|
||||
|
||||
// Réplica en Monday; si falla, el alta ya quedó persistida y se reportan ids null
|
||||
let mondayContactoId: string | null = null
|
||||
@@ -211,18 +237,7 @@ export async function crearCliente(req: Request, res: Response): Promise<void> {
|
||||
...{ actividadEconomicaLabel: actividadEconomicaLabel(body.empleo?.tipoEmpleo) },
|
||||
})
|
||||
|
||||
const valorVenta = aNumero(vc.valorVenta)
|
||||
if (valorVenta > 0) {
|
||||
const enganche = aNumero(vc.enganche)
|
||||
mondayApartadoId = await mondayService.crearApartado({
|
||||
clienteNombre: dg.nombreCompleto,
|
||||
unidadCodigo: vc.ubicacion ?? '',
|
||||
...(enganche > 0 ? { montoApartado: enganche } : {}),
|
||||
fechaApartado: hoyMas(0),
|
||||
fechaLimite: hoyMas(15),
|
||||
estadoLabel: 'Pago Apartado', // primer paso del pipeline Enkontrol
|
||||
})
|
||||
}
|
||||
mondayApartadoId = await crearApartadoSiAplica(dg, vc)
|
||||
|
||||
await prisma.cliente.update({
|
||||
where: { id: cliente.id },
|
||||
@@ -236,6 +251,209 @@ export async function crearCliente(req: Request, res: Response): Promise<void> {
|
||||
res.status(201).json({ ...cliente, mondayContactoId, mondayApartadoId })
|
||||
}
|
||||
|
||||
// ---------- Alta progresiva (guardado etapa por etapa del wizard) ----------
|
||||
|
||||
/**
|
||||
* POST /progreso/iniciar — solo exige el nombre; curp/rfc/email/celular son
|
||||
* opcionales porque el Contacto PROSPECTO se crea en cuanto hay nombre.
|
||||
*/
|
||||
export const iniciarProgresoSchema = z
|
||||
.object({
|
||||
datosGenerales: z
|
||||
.object({
|
||||
nombreCompleto: z.string().min(1),
|
||||
curp: z.string().optional(),
|
||||
rfc: z.string().optional(),
|
||||
email: z.string().optional(),
|
||||
celular: z.string().optional(),
|
||||
direccion: z.string().optional(),
|
||||
fechaNacimiento: z.string().optional(),
|
||||
estadoCivil: z.string().optional(),
|
||||
tipoVivienda: z.string().optional(),
|
||||
tipoCompra: z.string().optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
leadMondayId: z.string().optional(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
/** PATCH /progreso/:id — passthrough libre; solo se valida que sea un objeto */
|
||||
const actualizarProgresoSchema = z.object({}).passthrough()
|
||||
|
||||
const seccionDe = (datos: Record<string, unknown>, clave: string): Record<string, unknown> => {
|
||||
const v = datos[clave]
|
||||
return typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {}
|
||||
}
|
||||
|
||||
const textoDe = (v: unknown): string | undefined =>
|
||||
typeof v === 'string' && v.trim() !== '' ? v : undefined
|
||||
|
||||
/** Texto de la columna Dirección del Contacto a partir del domicilio capturado */
|
||||
export function textoDireccion(dom: Record<string, unknown>): string | undefined {
|
||||
const t = (k: string): string => textoDe(dom[k])?.trim() ?? ''
|
||||
const calleNum = [t('calle'), t('numExt')].filter((p) => p !== '').join(' ')
|
||||
const numInt = t('numInt')
|
||||
const linea1 = [calleNum, numInt !== '' ? `Int. ${numInt}` : ''].filter((p) => p !== '').join(', ')
|
||||
const cp = t('cp')
|
||||
const partes = [linea1, t('colonia'), cp !== '' ? `CP ${cp}` : '', t('municipio'), t('estado')].filter(
|
||||
(p) => p !== '',
|
||||
)
|
||||
return partes.length > 0 ? partes.join(', ') : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Deriva TODOS los campos mapeables del Contacto de Monday presentes en el
|
||||
* estado del wizard (idempotente: se manda el estado completo en cada avance).
|
||||
*/
|
||||
export function contactoDesdeDatos(datos: Record<string, unknown>): Omit<DatosContacto, 'estadoLabel'> {
|
||||
const dg = seccionDe(datos, 'datosGenerales')
|
||||
const empleo = seccionDe(datos, 'empleo')
|
||||
const vc = seccionDe(datos, 'viviendaCredito')
|
||||
// El domicilio puede venir suelto ('domicilio') o como domicilioFiscal del paso Vivienda
|
||||
const domRaiz = seccionDe(datos, 'domicilio')
|
||||
const dom = Object.keys(domRaiz).length > 0 ? domRaiz : seccionDe(vc, 'domicilioFiscal')
|
||||
const curp = textoDe(dg['curp'])
|
||||
const rfc = textoDe(dg['rfc'])
|
||||
const email = textoDe(dg['email'])
|
||||
const telefono = textoDe(dg['celular'])
|
||||
const direccion = textoDireccion(dom) ?? textoDe(dg['direccion'])
|
||||
const actividadEconomica = actividadEconomicaLabel(textoDe(empleo['tipoEmpleo']))
|
||||
return {
|
||||
nombre: textoDe(dg['nombreCompleto']) ?? '',
|
||||
...(curp !== undefined ? { curp } : {}),
|
||||
...(rfc !== undefined ? { rfc } : {}),
|
||||
...(email !== undefined ? { email } : {}),
|
||||
...(telefono !== undefined ? { telefono } : {}),
|
||||
...(direccion !== undefined ? { direccion } : {}),
|
||||
...perfilDemografico({
|
||||
estadoCivil: textoDe(dg['estadoCivil']),
|
||||
tipoVivienda: textoDe(dg['tipoVivienda']),
|
||||
tipoCompra: textoDe(dg['tipoCompra']),
|
||||
fechaNacimiento: textoDe(dg['fechaNacimiento']),
|
||||
}),
|
||||
...(actividadEconomica !== undefined ? { actividadEconomicaLabel: actividadEconomica } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** POST /api/clientes/progreso/iniciar — crea el alta en progreso + Contacto PROSPECTO */
|
||||
export async function iniciarProgreso(req: Request, res: Response): Promise<void> {
|
||||
const body = iniciarProgresoSchema.parse(req.body)
|
||||
const dg = body.datosGenerales
|
||||
|
||||
const cliente = await prisma.cliente.create({
|
||||
data: {
|
||||
nombreCompleto: dg.nombreCompleto,
|
||||
curp: dg.curp ?? '',
|
||||
rfc: dg.rfc ?? '',
|
||||
email: dg.email ?? null,
|
||||
celular: dg.celular ?? null,
|
||||
proyecto: '', // se define al completar el alta
|
||||
payloadJson: JSON.stringify(body),
|
||||
},
|
||||
})
|
||||
|
||||
// Contacto PROSPECTO en Monday; si falla, el progreso local ya quedó
|
||||
let mondayContactoId: string | null = null
|
||||
try {
|
||||
mondayContactoId = await mondayService.crearContacto({
|
||||
...contactoDesdeDatos(body as Record<string, unknown>),
|
||||
estadoLabel: 'PROSPECTO',
|
||||
})
|
||||
await prisma.cliente.update({ where: { id: cliente.id }, data: { mondayContactoId } })
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('No se pudo crear el Contacto PROSPECTO en Monday:', err)
|
||||
}
|
||||
|
||||
res.status(201).json({ id: cliente.id, mondayContactoId })
|
||||
}
|
||||
|
||||
/** PATCH /api/clientes/progreso/:id — guarda el avance y lo replica en el Contacto */
|
||||
export async function actualizarProgreso(req: Request, res: Response): Promise<void> {
|
||||
const id = String(req.params['id'])
|
||||
const body = actualizarProgresoSchema.parse(req.body)
|
||||
const cliente = await prisma.cliente.findUnique({ where: { id } })
|
||||
if (!cliente) throw new NotFoundError('Cliente no encontrado')
|
||||
|
||||
await prisma.cliente.update({ where: { id }, data: { payloadJson: JSON.stringify(body) } })
|
||||
|
||||
// Réplica idempotente en Monday; un fallo no rompe el avance del wizard
|
||||
let mondaySync = false
|
||||
if (cliente.mondayContactoId !== null) {
|
||||
try {
|
||||
await mondayService.actualizarContacto(cliente.mondayContactoId, contactoDesdeDatos(body))
|
||||
mondaySync = true
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`No se pudo actualizar el Contacto ${cliente.mondayContactoId} en Monday:`, err)
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ id, mondaySync })
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/clientes/progreso/:id/completar — cierra el alta iniciada con el
|
||||
* guardado progresivo. Misma validación y shape de respuesta que POST /clientes.
|
||||
*/
|
||||
export async function completarProgreso(req: Request, res: Response): Promise<void> {
|
||||
const id = String(req.params['id'])
|
||||
const body = crearClienteSchema.parse(req.body)
|
||||
const dg = body.datosGenerales
|
||||
const vc = body.viviendaCredito
|
||||
const cliente = await prisma.cliente.findUnique({ where: { id } })
|
||||
if (!cliente) throw new NotFoundError('Cliente no encontrado')
|
||||
|
||||
const actualizado = await prisma.cliente.update({
|
||||
where: { id },
|
||||
data: {
|
||||
nombreCompleto: dg.nombreCompleto,
|
||||
curp: dg.curp,
|
||||
rfc: dg.rfc,
|
||||
email: dg.email ?? null,
|
||||
celular: dg.celular ?? null,
|
||||
proyecto: vc.proyecto,
|
||||
unidadCodigo: vc.ubicacion ?? '',
|
||||
payloadJson: JSON.stringify(body),
|
||||
firmaPng: body.firma?.firmaDataUrl ?? null,
|
||||
},
|
||||
})
|
||||
|
||||
await moverLeadAApartoSiAplica(body as Record<string, unknown>)
|
||||
|
||||
// El Contacto (creado como PROSPECTO al iniciar) pasa a CLIENTE con los
|
||||
// datos finales; si no existe (nunca hubo Monday), se crea como en el alta directa
|
||||
let mondayContactoId: string | null = cliente.mondayContactoId
|
||||
let mondayApartadoId: string | null = cliente.mondayApartadoId
|
||||
try {
|
||||
if (mondayContactoId !== null) {
|
||||
await mondayService.actualizarContacto(mondayContactoId, {
|
||||
...contactoDesdeDatos(body as Record<string, unknown>),
|
||||
estadoLabel: 'CLIENTE',
|
||||
})
|
||||
} else {
|
||||
mondayContactoId = await mondayService.crearContacto({
|
||||
...contactoDesdeDatos(body as Record<string, unknown>),
|
||||
estadoLabel: 'CLIENTE',
|
||||
})
|
||||
}
|
||||
|
||||
if (mondayApartadoId === null) {
|
||||
mondayApartadoId = await crearApartadoSiAplica(dg, vc)
|
||||
}
|
||||
|
||||
await prisma.cliente.update({
|
||||
where: { id },
|
||||
data: { mondayContactoId, mondayApartadoId },
|
||||
})
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('No se pudo replicar el cliente en Monday:', err)
|
||||
}
|
||||
|
||||
res.status(201).json({ ...actualizado, mondayContactoId, mondayApartadoId })
|
||||
}
|
||||
|
||||
/** GET /api/clientes/:id */
|
||||
export async function obtenerCliente(req: Request, res: Response): Promise<void> {
|
||||
const cliente = await prisma.cliente.findUnique({
|
||||
|
||||
Reference in New Issue
Block a user