feat: API Gateway (Express 5 + Prisma + Monday) y conexion de apps al API
- api-gateway: servicio Monday (retry 429/complejidad, paginacion cursor, column IDs por titulo), endpoints unidades/cotizaciones/clientes/planes, webhook con handshake challenge, Prisma SQLite dev, 55 tests - cotizador: inventario desde /api/unidades con fallback a seed - alta-clientes: POST /api/clientes + upload multipart de documentos - cobranza: persistencia via API con respaldo offline en localStorage - .env.example con board IDs del workspace Frasa-CAS
This commit is contained in:
191
api-gateway/src/controllers/clientes.controller.ts
Normal file
191
api-gateway/src/controllers/clientes.controller.ts
Normal file
@@ -0,0 +1,191 @@
|
||||
import type { Request, Response } from 'express'
|
||||
import path from 'node:path'
|
||||
import fs from 'node:fs'
|
||||
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 { prisma } from '../services/prisma.js'
|
||||
import { NotFoundError, BadRequestError } from '../utils/errors.js'
|
||||
|
||||
// ---------- Alta de clientes ----------
|
||||
|
||||
const crearClienteSchema = z
|
||||
.object({
|
||||
datosGenerales: z
|
||||
.object({
|
||||
nombreCompleto: z.string().min(1),
|
||||
curp: z.string().min(1),
|
||||
rfc: z.string().min(1),
|
||||
email: z.string().optional(),
|
||||
celular: z.string().optional(),
|
||||
direccion: z.string().optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
viviendaCredito: z
|
||||
.object({
|
||||
proyecto: z.string().min(1),
|
||||
ubicacion: z.string().min(1),
|
||||
valorVenta: z.union([z.string(), z.number()]).optional(),
|
||||
enganche: z.union([z.string(), z.number()]).optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
firma: z.object({ firmaDataUrl: z.string().optional() }).passthrough().optional(),
|
||||
})
|
||||
.passthrough() // el resto del payload pasa tal cual a payloadJson
|
||||
|
||||
const aNumero = (v: string | number | undefined): number => {
|
||||
if (v === undefined) return 0
|
||||
const n = typeof v === 'number' ? v : Number(String(v).replace(/[^0-9.-]/g, ''))
|
||||
return Number.isFinite(n) ? n : 0
|
||||
}
|
||||
|
||||
const hoyMas = (dias: number): string => {
|
||||
const d = new Date()
|
||||
d.setDate(d.getDate() + dias)
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0')
|
||||
const dia = String(d.getDate()).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${m}-${dia}`
|
||||
}
|
||||
|
||||
/** 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)
|
||||
const dg = body.datosGenerales
|
||||
const vc = body.viviendaCredito
|
||||
|
||||
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: vc.proyecto,
|
||||
unidadCodigo: vc.ubicacion, // la "ubicación" del formato es el código de unidad (U-101, etc.)
|
||||
payloadJson: JSON.stringify(body),
|
||||
firmaPng: body.firma?.firmaDataUrl ?? null,
|
||||
},
|
||||
})
|
||||
|
||||
// Réplica en Monday; si falla, el alta ya quedó persistida y se reportan ids null
|
||||
let mondayContactoId: string | null = null
|
||||
let mondayApartadoId: string | null = null
|
||||
try {
|
||||
mondayContactoId = await mondayService.crearContacto({
|
||||
nombre: dg.nombreCompleto,
|
||||
estadoLabel: 'CLIENTE',
|
||||
...(dg.celular !== undefined ? { telefono: dg.celular } : {}),
|
||||
...(dg.email !== undefined ? { email: dg.email } : {}),
|
||||
curp: dg.curp,
|
||||
rfc: dg.rfc,
|
||||
...(dg.direccion !== undefined ? { direccion: dg.direccion } : {}),
|
||||
})
|
||||
|
||||
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: 'VIGENTE',
|
||||
})
|
||||
}
|
||||
|
||||
await prisma.cliente.update({
|
||||
where: { id: cliente.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({ ...cliente, mondayContactoId, mondayApartadoId })
|
||||
}
|
||||
|
||||
/** GET /api/clientes/:id */
|
||||
export async function obtenerCliente(req: Request, res: Response): Promise<void> {
|
||||
const cliente = await prisma.cliente.findUnique({
|
||||
where: { id: String(req.params['id']) },
|
||||
include: { documentos: true },
|
||||
})
|
||||
if (!cliente) throw new NotFoundError('Cliente no encontrado')
|
||||
res.json(cliente)
|
||||
}
|
||||
|
||||
// ---------- Documentos ----------
|
||||
|
||||
const MIME_PERMITIDOS = new Set(['application/pdf', 'image/jpeg', 'image/jpg', 'image/png'])
|
||||
const EXT_POR_MIME: Record<string, string> = {
|
||||
'application/pdf': 'pdf',
|
||||
'image/jpeg': 'jpg',
|
||||
'image/jpg': 'jpg',
|
||||
'image/png': 'png',
|
||||
}
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (req, _file, cb) => {
|
||||
const dir = path.join(config.uploadsDir, String(req.params['id']))
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
cb(null, dir)
|
||||
},
|
||||
filename: (req, file, cb) => {
|
||||
const tipo = String(req.body['tipo'] ?? 'OTRO').toUpperCase()
|
||||
const ext = EXT_POR_MIME[file.mimetype] ?? 'bin'
|
||||
cb(null, `${tipo}_${randomUUID()}.${ext}`)
|
||||
},
|
||||
})
|
||||
|
||||
export const uploadDocumentos = multer({
|
||||
storage,
|
||||
limits: { fileSize: 10 * 1024 * 1024, files: 10 }, // 10 MB por archivo, máx 10
|
||||
fileFilter: (_req, file, cb) => {
|
||||
if (!MIME_PERMITIDOS.has(file.mimetype)) {
|
||||
cb(new BadRequestError(`Tipo de archivo no permitido: ${file.mimetype}`))
|
||||
return
|
||||
}
|
||||
cb(null, true)
|
||||
},
|
||||
})
|
||||
|
||||
/** POST /api/clientes/:id/documentos — multipart, campo `archivos` (hasta 10) */
|
||||
export async function subirDocumentos(req: Request, res: Response): Promise<void> {
|
||||
const clienteId = String(req.params['id'])
|
||||
const cliente = await prisma.cliente.findUnique({ where: { id: clienteId } })
|
||||
if (!cliente) throw new NotFoundError('Cliente no encontrado')
|
||||
|
||||
const archivos = (req.files ?? []) as Express.Multer.File[]
|
||||
const tipo = String(req.body['tipo'] ?? 'OTRO').toUpperCase()
|
||||
const documentos = await Promise.all(
|
||||
archivos.map((f) =>
|
||||
prisma.documento.create({
|
||||
data: {
|
||||
clienteId,
|
||||
tipo,
|
||||
nombreArchivo: f.originalname,
|
||||
ruta: path.relative(config.uploadsDir, f.path),
|
||||
mime: f.mimetype,
|
||||
tamano: f.size,
|
||||
},
|
||||
}),
|
||||
),
|
||||
)
|
||||
res.status(201).json(documentos)
|
||||
}
|
||||
|
||||
/** GET /api/clientes/:id/documentos */
|
||||
export async function listarDocumentos(req: Request, res: Response): Promise<void> {
|
||||
const clienteId = String(req.params['id'])
|
||||
const cliente = await prisma.cliente.findUnique({ where: { id: clienteId } })
|
||||
if (!cliente) throw new NotFoundError('Cliente no encontrado')
|
||||
const documentos = await prisma.documento.findMany({
|
||||
where: { clienteId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
res.json(documentos)
|
||||
}
|
||||
Reference in New Issue
Block a user