feat(mi-dia): app /hoy + CRM ligero para vendedores
- App Mi día: KPIs, mis actividades, mis leads con acciones rápidas (contactado/intento/agenda cita/descartar con motivo), captura rápida de lead (409 en duplicado por teléfono), vista equipo para coordinadores - API: GET /api/mi-dia/resumen, POST /api/leads, /leads/:id/estado, /leads/:id/descartar; mapeo Usuario.mondayUserId (seed listo para cuando inviten a los vendedores a Monday) - Landing: tarjeta Mi día; tests api 188, mi-dia 8, landing 4
This commit is contained in:
@@ -145,6 +145,9 @@ model Usuario {
|
||||
rol String // vendedor | coordinador | corporativo | admin
|
||||
asignacion String? // ATELIER | RESIDENCIAL | MONTEBELLO | BROKER | ACORPORATIVO
|
||||
empleadoId Int?
|
||||
// User ID de Monday (people). null = el usuario aún no tiene cuenta Monday;
|
||||
// los filtros "míos" de /api/mi-dia responden vacíos con sinMapeoMonday: true
|
||||
mondayUserId Int?
|
||||
activo Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -21,6 +21,7 @@ const datos: DatosUsuarioSeed = {
|
||||
rol: 'vendedor',
|
||||
asignacion: 'MONTEBELLO',
|
||||
empleadoId: 13676,
|
||||
mondayUserId: null,
|
||||
passwordHash: 'hash-inicial',
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ export interface DatosUsuarioSeed {
|
||||
rol: string
|
||||
asignacion: string | null
|
||||
empleadoId: number | null
|
||||
mondayUserId: number | null
|
||||
passwordHash: string
|
||||
}
|
||||
|
||||
@@ -51,6 +52,7 @@ export async function upsertUsuario(
|
||||
rol: datos.rol,
|
||||
asignacion: datos.asignacion,
|
||||
empleadoId: datos.empleadoId,
|
||||
mondayUserId: datos.mondayUserId,
|
||||
...(resetPasswords ? { passwordHash: datos.passwordHash } : {}),
|
||||
},
|
||||
})
|
||||
@@ -62,6 +64,8 @@ interface VendedorJson {
|
||||
nombre: string
|
||||
asignacion: string | null
|
||||
rol: string
|
||||
// User ID de Monday cuando el vendedor ya tiene cuenta (hoy solo Martin Zavala)
|
||||
mondayUserId?: number | null
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
@@ -83,6 +87,7 @@ async function main(): Promise<void> {
|
||||
rol: v.rol,
|
||||
asignacion: v.asignacion,
|
||||
empleadoId: v.empleadoId,
|
||||
mondayUserId: v.mondayUserId ?? null,
|
||||
passwordHash: hashVendedores,
|
||||
},
|
||||
resetPasswords,
|
||||
@@ -102,6 +107,7 @@ async function main(): Promise<void> {
|
||||
rol: 'admin',
|
||||
asignacion: null,
|
||||
empleadoId: null,
|
||||
mondayUserId: null,
|
||||
passwordHash: hashAdmin,
|
||||
},
|
||||
resetPasswords,
|
||||
|
||||
133
api-gateway/src/controllers/leads.controller.test.ts
Normal file
133
api-gateway/src/controllers/leads.controller.test.ts
Normal file
@@ -0,0 +1,133 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
cambiarEstadoLead,
|
||||
crearLead,
|
||||
descartarLead,
|
||||
ESTADOS_LEAD_PERMITIDOS,
|
||||
} from './leads.controller.js'
|
||||
import type { LeadMonday } from '../services/monday.service.js'
|
||||
|
||||
/** Monday mockeado: registra escrituras y devuelve catálogos controlados */
|
||||
function mondayMock(opts: { labelsOrigen?: string[]; duplicado?: LeadMonday | null } = {}) {
|
||||
return {
|
||||
cambios: [] as { boardId: string; itemId: string; columna: string; valor: unknown }[],
|
||||
motivos: [] as { nombre: string; categoria: string; descripcion?: string }[],
|
||||
leadsCreados: [] as Record<string, unknown>[],
|
||||
async cambiarValorColumna(boardId: string, itemId: string, columna: string, valor: string | number | boolean) {
|
||||
this.cambios.push({ boardId, itemId, columna, valor })
|
||||
},
|
||||
async crearLead(datos: Record<string, unknown>) {
|
||||
this.leadsCreados.push(datos)
|
||||
return 'lead-nuevo-1'
|
||||
},
|
||||
async buscarLeadPorTelefono(_telefono: string) {
|
||||
return opts.duplicado ?? null
|
||||
},
|
||||
async labelsDeColumna(_boardId: string, _titulo: string) {
|
||||
return opts.labelsOrigen ?? ['WhatsApp', 'Web', 'Recomendado', 'Facebook', 'Otro']
|
||||
},
|
||||
async obtenerNombreItem(_itemId: string) {
|
||||
return 'Lead Prueba'
|
||||
},
|
||||
async crearMotivoNoCompra(datos: { nombre: string; categoria: string; descripcion?: string }) {
|
||||
this.motivos.push(datos)
|
||||
return 'motivo-item-1'
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const datosBase = { nombre: 'Lead Prueba', telefono: '4771234567' }
|
||||
|
||||
describe('crearLead (POST /api/leads)', () => {
|
||||
it('crea el item en Monday con Estado NUEVO y devuelve su id', async () => {
|
||||
const monday = mondayMock()
|
||||
const r = await crearLead(monday, { ...datosBase, origen: 'Facebook', notas: 'Vio el volante' })
|
||||
expect(r).toEqual({ id: 'lead-nuevo-1' })
|
||||
expect(monday.leadsCreados).toEqual([
|
||||
{ nombre: 'Lead Prueba', telefono: '4771234567', email: undefined, origenLabel: 'Facebook', notas: 'Vio el volante' },
|
||||
])
|
||||
})
|
||||
|
||||
it('duplicado por teléfono: no crea nada y devuelve el lead existente (endpoint → 409)', async () => {
|
||||
const existente: LeadMonday = {
|
||||
id: 'lead-viejo-9',
|
||||
nombre: 'Lead Prueba',
|
||||
createdAt: '',
|
||||
updatedAt: '',
|
||||
estado: 'NUEVO',
|
||||
origen: '',
|
||||
telefono: '4771234567',
|
||||
email: '',
|
||||
vendedorIds: [],
|
||||
}
|
||||
const monday = mondayMock({ duplicado: existente })
|
||||
const r = await crearLead(monday, datosBase)
|
||||
expect(r).toEqual({ duplicado: existente })
|
||||
expect(monday.leadsCreados).toEqual([])
|
||||
})
|
||||
|
||||
it('rechaza un origen que no sea label real de la columna Origen', async () => {
|
||||
const monday = mondayMock()
|
||||
await expect(crearLead(monday, { ...datosBase, origen: 'Volanteo' })).rejects.toThrow(/Origen inválido/)
|
||||
expect(monday.leadsCreados).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('cambiarEstadoLead (POST /api/leads/:itemId/estado)', () => {
|
||||
it('la whitelist solo permite las transiciones del vendedor', () => {
|
||||
expect(ESTADOS_LEAD_PERMITIDOS).toEqual(['CONTACTADO', 'Intento de contacto', 'AGENDA CITA', 'CALIFICADO'])
|
||||
// DESCARTADO tiene su propio endpoint (lleva motivo); NUEVO no es acción
|
||||
expect(ESTADOS_LEAD_PERMITIDOS).not.toContain('DESCARTADO')
|
||||
expect(ESTADOS_LEAD_PERMITIDOS).not.toContain('NUEVO')
|
||||
})
|
||||
|
||||
it('cambia solo la columna Estado en el board Leads (444 en tests)', async () => {
|
||||
const monday = mondayMock()
|
||||
await cambiarEstadoLead(monday, 'lead-1', 'CONTACTADO')
|
||||
expect(monday.cambios).toEqual([{ boardId: '444', itemId: 'lead-1', columna: 'Estado', valor: 'CONTACTADO' }])
|
||||
})
|
||||
|
||||
it('AGENDA CITA con fecha también setea la columna Fecha', async () => {
|
||||
const monday = mondayMock()
|
||||
await cambiarEstadoLead(monday, 'lead-1', 'AGENDA CITA', '2026-09-01')
|
||||
expect(monday.cambios).toEqual([
|
||||
{ boardId: '444', itemId: 'lead-1', columna: 'Estado', valor: 'AGENDA CITA' },
|
||||
{ boardId: '444', itemId: 'lead-1', columna: 'Fecha', valor: '2026-09-01' },
|
||||
])
|
||||
})
|
||||
|
||||
it('AGENDA CITA sin fecha no toca la columna Fecha', async () => {
|
||||
const monday = mondayMock()
|
||||
await cambiarEstadoLead(monday, 'lead-1', 'AGENDA CITA')
|
||||
expect(monday.cambios).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('descartarLead (POST /api/leads/:itemId/descartar)', () => {
|
||||
it('Estado DESCARTADO + Notas + registro en Motivos No Compra', async () => {
|
||||
const monday = mondayMock()
|
||||
const motivoItemId = await descartarLead(monday, 'lead-1', 'Precio', 'Se le hizo caro')
|
||||
expect(motivoItemId).toBe('motivo-item-1')
|
||||
expect(monday.cambios).toEqual([
|
||||
{ boardId: '444', itemId: 'lead-1', columna: 'Estado', valor: 'DESCARTADO' },
|
||||
{ boardId: '444', itemId: 'lead-1', columna: 'Notas', valor: 'Se le hizo caro' },
|
||||
])
|
||||
expect(monday.motivos).toEqual([
|
||||
{ nombre: 'Precio — Lead Prueba', categoria: 'Precio', descripcion: 'Se le hizo caro' },
|
||||
])
|
||||
})
|
||||
|
||||
it('sin comentario no escribe Notas', async () => {
|
||||
const monday = mondayMock()
|
||||
await descartarLead(monday, 'lead-1', 'Timing')
|
||||
expect(monday.cambios).toEqual([{ boardId: '444', itemId: 'lead-1', columna: 'Estado', valor: 'DESCARTADO' }])
|
||||
expect(monday.motivos[0]).toEqual({ nombre: 'Timing — Lead Prueba', categoria: 'Timing' })
|
||||
})
|
||||
|
||||
it('propaga el error si Monday falla (el error handler responde 5xx, no truena el server)', async () => {
|
||||
const monday = mondayMock()
|
||||
vi.spyOn(monday, 'cambiarValorColumna').mockRejectedValueOnce(new Error('Monday caído'))
|
||||
await expect(descartarLead(monday, 'lead-1', 'Cliente')).rejects.toThrow('Monday caído')
|
||||
expect(monday.motivos).toEqual([])
|
||||
})
|
||||
})
|
||||
146
api-gateway/src/controllers/leads.controller.ts
Normal file
146
api-gateway/src/controllers/leads.controller.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import type { Request, Response } from 'express'
|
||||
import { z } from 'zod'
|
||||
import { config } from '../config/index.js'
|
||||
import { mondayService, type LeadMonday, type MondayService } from '../services/monday.service.js'
|
||||
import { MOTIVOS_NO_COMPRA } from './oportunidades.controller.js'
|
||||
import { AppError } from '../utils/errors.js'
|
||||
|
||||
/**
|
||||
* CRM ligero sobre el tablero Leads: captura rápida y acciones del vendedor.
|
||||
* Los labels de estado/origen son los reales del board (verificados contra
|
||||
* Monday); la whitelist evita escribir labels que el status no tenga dados de alta.
|
||||
*/
|
||||
|
||||
// Transiciones que el vendedor puede hacer desde la app Mi día
|
||||
export const ESTADOS_LEAD_PERMITIDOS = ['CONTACTADO', 'Intento de contacto', 'AGENDA CITA', 'CALIFICADO'] as const
|
||||
|
||||
const crearLeadSchema = z.object({
|
||||
nombre: z.string().trim().min(1, 'El nombre es obligatorio'),
|
||||
telefono: z.string().trim().min(1).optional(),
|
||||
email: z.string().trim().email('Email inválido').optional(),
|
||||
origen: z.string().trim().min(1).optional(),
|
||||
notas: z.string().trim().min(1).optional(),
|
||||
})
|
||||
|
||||
const cambiarEstadoSchema = z.object({
|
||||
estado: z.enum(ESTADOS_LEAD_PERMITIDOS),
|
||||
fecha: z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}-\d{2}$/, 'La fecha debe ser YYYY-MM-DD')
|
||||
.optional(),
|
||||
})
|
||||
|
||||
const descartarSchema = z.object({
|
||||
motivo: z.enum(MOTIVOS_NO_COMPRA),
|
||||
comentario: z.string().trim().min(1).optional(),
|
||||
})
|
||||
|
||||
type MondayLeads = Pick<
|
||||
MondayService,
|
||||
| 'cambiarValorColumna'
|
||||
| 'crearLead'
|
||||
| 'crearMotivoNoCompra'
|
||||
| 'buscarLeadPorTelefono'
|
||||
| 'labelsDeColumna'
|
||||
| 'obtenerNombreItem'
|
||||
>
|
||||
|
||||
export type ResultadoCrearLead = { id: string } | { duplicado: LeadMonday }
|
||||
|
||||
/**
|
||||
* Crea un lead en Monday (Estado NUEVO). Si viene teléfono y ya existe un lead
|
||||
* con ese número, no crea nada y devuelve { duplicado } (el endpoint → 409).
|
||||
* El origen se valida contra los labels reales de la columna del board.
|
||||
*/
|
||||
export async function crearLead(
|
||||
monday: MondayLeads,
|
||||
datos: z.infer<typeof crearLeadSchema>,
|
||||
): Promise<ResultadoCrearLead> {
|
||||
const boardLeads = config.monday.boards.leads
|
||||
|
||||
if (datos.telefono !== undefined) {
|
||||
const existente = await monday.buscarLeadPorTelefono(datos.telefono)
|
||||
if (existente) return { duplicado: existente }
|
||||
}
|
||||
|
||||
if (datos.origen !== undefined) {
|
||||
const labels = await monday.labelsDeColumna(boardLeads, 'Origen')
|
||||
if (!labels.includes(datos.origen)) {
|
||||
throw new AppError(400, `Origen inválido: "${datos.origen}". Labels válidos: ${labels.join(', ')}`)
|
||||
}
|
||||
}
|
||||
|
||||
const id = await monday.crearLead({
|
||||
nombre: datos.nombre,
|
||||
telefono: datos.telefono,
|
||||
email: datos.email,
|
||||
origenLabel: datos.origen,
|
||||
notas: datos.notas,
|
||||
})
|
||||
return { id }
|
||||
}
|
||||
|
||||
/** Cambia el estado del lead (whitelist) y, en AGENDA CITA, puede setear la Fecha */
|
||||
export async function cambiarEstadoLead(
|
||||
monday: MondayLeads,
|
||||
itemId: string,
|
||||
estado: (typeof ESTADOS_LEAD_PERMITIDOS)[number],
|
||||
fecha?: string,
|
||||
): Promise<void> {
|
||||
const boardLeads = config.monday.boards.leads
|
||||
await monday.cambiarValorColumna(boardLeads, itemId, 'Estado', estado)
|
||||
if (estado === 'AGENDA CITA' && fecha !== undefined) {
|
||||
await monday.cambiarValorColumna(boardLeads, itemId, 'Fecha', fecha)
|
||||
}
|
||||
}
|
||||
|
||||
/** Estado DESCARTADO + registro en el catálogo Motivos No Compra (+ Notas opcional) */
|
||||
export async function descartarLead(
|
||||
monday: MondayLeads,
|
||||
itemId: string,
|
||||
motivo: string,
|
||||
comentario?: string,
|
||||
): Promise<string> {
|
||||
const boardLeads = config.monday.boards.leads
|
||||
const nombreItem = await monday.obtenerNombreItem(itemId)
|
||||
await monday.cambiarValorColumna(boardLeads, itemId, 'Estado', 'DESCARTADO')
|
||||
if (comentario !== undefined) {
|
||||
await monday.cambiarValorColumna(boardLeads, itemId, 'Notas', comentario)
|
||||
}
|
||||
return monday.crearMotivoNoCompra({
|
||||
nombre: `${motivo} — ${nombreItem}`,
|
||||
categoria: motivo,
|
||||
...(comentario !== undefined ? { descripcion: comentario } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
/** POST /api/leads { nombre, telefono?, email?, origen?, notas? } */
|
||||
export async function crearLeadEndpoint(req: Request, res: Response): Promise<void> {
|
||||
const body = crearLeadSchema.parse(req.body)
|
||||
const resultado = await crearLead(mondayService, body)
|
||||
if ('duplicado' in resultado) {
|
||||
res.status(409).json({
|
||||
error: 'Ya existe un lead con ese teléfono',
|
||||
leadId: resultado.duplicado.id,
|
||||
nombre: resultado.duplicado.nombre,
|
||||
})
|
||||
return
|
||||
}
|
||||
res.status(201).json({ id: resultado.id, estado: 'NUEVO' })
|
||||
}
|
||||
|
||||
/** POST /api/leads/:itemId/estado { estado, fecha? } */
|
||||
export async function cambiarEstadoLeadEndpoint(req: Request, res: Response): Promise<void> {
|
||||
const body = cambiarEstadoSchema.parse(req.body)
|
||||
const itemId = String(req.params['itemId'])
|
||||
await cambiarEstadoLead(mondayService, itemId, body.estado, body.fecha)
|
||||
res.json({ itemId, estado: body.estado, ...(body.fecha !== undefined ? { fecha: body.fecha } : {}) })
|
||||
}
|
||||
|
||||
/** POST /api/leads/:itemId/descartar { motivo, comentario? } */
|
||||
export async function descartarLeadEndpoint(req: Request, res: Response): Promise<void> {
|
||||
const body = descartarSchema.parse(req.body)
|
||||
const itemId = String(req.params['itemId'])
|
||||
const motivoItemId = await descartarLead(mondayService, itemId, body.motivo, body.comentario)
|
||||
res.json({ itemId, estado: 'DESCARTADO', motivo: body.motivo, motivoItemId })
|
||||
}
|
||||
36
api-gateway/src/controllers/mi-dia.controller.ts
Normal file
36
api-gateway/src/controllers/mi-dia.controller.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import type { Request, Response } from 'express'
|
||||
import { prisma } from '../services/prisma.js'
|
||||
import { mondayService } from '../services/monday.service.js'
|
||||
import { resumenMiDia } from '../services/mi-dia.service.js'
|
||||
import { AppError } from '../utils/errors.js'
|
||||
|
||||
/**
|
||||
* GET /api/mi-dia/resumen — agenda del vendedor logueado.
|
||||
* El "mío" se resuelve por Usuario.mondayUserId (mapeo usuario↔Monday);
|
||||
* sin mapeo, las listas personales van vacías con sinMapeoMonday: true.
|
||||
*/
|
||||
export async function resumenMiDiaEndpoint(req: Request, res: Response): Promise<void> {
|
||||
// Con AUTH_ENABLED=false (arranque temprano/tests) no hay token: se usa el admin
|
||||
const sub = req.usuarioToken?.sub
|
||||
const usuario = sub
|
||||
? await prisma.usuario.findUnique({ where: { id: sub } })
|
||||
: await prisma.usuario.findUnique({ where: { username: 'admin' } })
|
||||
if (!usuario || !usuario.activo) throw new AppError(401, 'Credenciales inválidas')
|
||||
|
||||
// Nombres de los usuarios ya mapeados a Monday (para la sección equipo)
|
||||
const mapeados = await prisma.usuario.findMany({
|
||||
where: { mondayUserId: { not: null }, activo: true },
|
||||
select: { nombre: true, mondayUserId: true },
|
||||
})
|
||||
const nombresPorMondayId = new Map<number, string>(
|
||||
mapeados.filter((m) => m.mondayUserId !== null).map((m) => [m.mondayUserId!, m.nombre]),
|
||||
)
|
||||
|
||||
res.json(
|
||||
await resumenMiDia(
|
||||
mondayService,
|
||||
{ nombre: usuario.nombre, rol: usuario.rol, mondayUserId: usuario.mondayUserId },
|
||||
nombresPorMondayId,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -24,6 +24,12 @@ import {
|
||||
registrarAbonoEndpoint,
|
||||
} from '../controllers/planes.controller.js'
|
||||
import { perderOportunidadEndpoint } from '../controllers/oportunidades.controller.js'
|
||||
import {
|
||||
cambiarEstadoLeadEndpoint,
|
||||
crearLeadEndpoint,
|
||||
descartarLeadEndpoint,
|
||||
} from '../controllers/leads.controller.js'
|
||||
import { resumenMiDiaEndpoint } from '../controllers/mi-dia.controller.js'
|
||||
import { webhookMonday } from '../controllers/webhooks.controller.js'
|
||||
import {
|
||||
correrRoundRobin,
|
||||
@@ -71,6 +77,12 @@ apiRouter.patch('/planes/:id/monday', ligarMondayItem)
|
||||
|
||||
apiRouter.post('/oportunidades/:mondayItemId/perder', perderOportunidadEndpoint)
|
||||
|
||||
apiRouter.get('/mi-dia/resumen', resumenMiDiaEndpoint)
|
||||
|
||||
apiRouter.post('/leads', crearLeadEndpoint)
|
||||
apiRouter.post('/leads/:itemId/estado', cambiarEstadoLeadEndpoint)
|
||||
apiRouter.post('/leads/:itemId/descartar', descartarLeadEndpoint)
|
||||
|
||||
apiRouter.get('/reportes/resumen', resumenReportes)
|
||||
|
||||
apiRouter.post('/webhooks/monday', webhookMonday)
|
||||
|
||||
207
api-gateway/src/services/mi-dia.service.test.ts
Normal file
207
api-gateway/src/services/mi-dia.service.test.ts
Normal file
@@ -0,0 +1,207 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
esEstadoFinalApartado,
|
||||
esEstadoTerminalLead,
|
||||
resumenMiDia,
|
||||
type UsuarioMiDia,
|
||||
} from './mi-dia.service.js'
|
||||
import type { ActividadMonday, ApartadoMonday, LeadMonday } from './monday.service.js'
|
||||
|
||||
const MI_ID = 106736727
|
||||
const OTRO_ID = 111111111
|
||||
|
||||
const AHORA = new Date('2026-08-28T12:00:00') // viernes
|
||||
const HOY = '2026-08-28'
|
||||
const MANANA = '2026-08-29'
|
||||
|
||||
function lead(parcial: Partial<LeadMonday> & { id: string }): LeadMonday {
|
||||
return {
|
||||
nombre: `Lead ${parcial.id}`,
|
||||
createdAt: '2026-08-25T10:00:00Z',
|
||||
updatedAt: '2026-08-27T10:00:00Z',
|
||||
estado: 'NUEVO',
|
||||
origen: 'Facebook',
|
||||
telefono: '',
|
||||
email: '',
|
||||
vendedorIds: [MI_ID],
|
||||
...parcial,
|
||||
}
|
||||
}
|
||||
|
||||
function actividad(parcial: Partial<ActividadMonday> & { id: string }): ActividadMonday {
|
||||
return {
|
||||
nombre: `Actividad ${parcial.id}`,
|
||||
tipo: 'Llamada',
|
||||
fecha: HOY,
|
||||
estado: 'Abierto',
|
||||
responsableIds: [MI_ID],
|
||||
...parcial,
|
||||
}
|
||||
}
|
||||
|
||||
function apartado(parcial: Partial<ApartadoMonday> & { id: string }): ApartadoMonday {
|
||||
return {
|
||||
nombre: `Cliente ${parcial.id}`,
|
||||
unidadCodigo: 'U-101',
|
||||
fechaLimite: '2026-09-02', // dentro de 7 días
|
||||
estado: 'Pago Apartado',
|
||||
...parcial,
|
||||
}
|
||||
}
|
||||
|
||||
function mondayMock(datos: {
|
||||
leads?: LeadMonday[]
|
||||
actividades?: ActividadMonday[]
|
||||
apartados?: ApartadoMonday[]
|
||||
}) {
|
||||
return {
|
||||
async getLeads() {
|
||||
return datos.leads ?? []
|
||||
},
|
||||
async getActividades() {
|
||||
return datos.actividades ?? []
|
||||
},
|
||||
async getApartados() {
|
||||
return datos.apartados ?? []
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const vendedor: UsuarioMiDia = { nombre: 'Martin Zavala', rol: 'vendedor', mondayUserId: MI_ID }
|
||||
const sinMapeo: UsuarioMiDia = { nombre: 'Erick Peña', rol: 'vendedor', mondayUserId: null }
|
||||
const coordinador: UsuarioMiDia = { nombre: 'Daniel Alvarado', rol: 'coordinador', mondayUserId: null }
|
||||
|
||||
describe('resumenMiDia (GET /api/mi-dia/resumen)', () => {
|
||||
it('filtra mis leads por mondayUserId y excluye estados terminales', async () => {
|
||||
const monday = mondayMock({
|
||||
leads: [
|
||||
lead({ id: '1', estado: 'NUEVO' }),
|
||||
lead({ id: '2', estado: 'CONTACTADO', telefono: '4771234567' }),
|
||||
lead({ id: '3', estado: 'DESCARTADO' }),
|
||||
lead({ id: '4', estado: 'CALIFICADO' }),
|
||||
lead({ id: '5', estado: 'Abandono' }),
|
||||
lead({ id: '6', estado: 'NUEVO', vendedorIds: [OTRO_ID] }),
|
||||
],
|
||||
})
|
||||
const r = await resumenMiDia(monday, vendedor, new Map(), AHORA)
|
||||
expect(r.sinMapeoMonday).toBe(false)
|
||||
expect(r.misLeads.map((l) => l.id)).toEqual(['1', '2'])
|
||||
expect(r.misLeads[1]?.telefono).toBe('4771234567')
|
||||
})
|
||||
|
||||
it('actividades de hoy: solo abiertas con fecha <= mañana y mías', async () => {
|
||||
const monday = mondayMock({
|
||||
actividades: [
|
||||
actividad({ id: 'a1', fecha: HOY }),
|
||||
actividad({ id: 'a2', fecha: MANANA, tipo: 'Reunion' }),
|
||||
actividad({ id: 'a3', fecha: '2026-08-20' }), // vencida: también entra
|
||||
actividad({ id: 'a4', fecha: '2026-09-05' }), // futura lejana: no
|
||||
actividad({ id: 'a5', fecha: HOY, estado: 'Listo' }), // cerrada: no
|
||||
actividad({ id: 'a6', fecha: HOY, responsableIds: [OTRO_ID] }), // de otro: no
|
||||
actividad({ id: 'a7', fecha: '' }), // sin fecha: no
|
||||
],
|
||||
})
|
||||
const r = await resumenMiDia(monday, vendedor, new Map(), AHORA)
|
||||
// Ordenadas por fecha: vencida primero
|
||||
expect(r.misActividadesHoy.map((a) => a.id)).toEqual(['a3', 'a1', 'a2'])
|
||||
expect(r.conteos.actividadesAbiertas).toBe(5) // abiertas mías: a1,a2,a3,a4,a7
|
||||
})
|
||||
|
||||
it('apartados por vencer: próximos 7 días, excluye estados finales', async () => {
|
||||
const monday = mondayMock({
|
||||
apartados: [
|
||||
apartado({ id: 'p1', fechaLimite: HOY }), // vence hoy
|
||||
apartado({ id: 'p2', fechaLimite: '2026-09-04' }), // justo en 7 días
|
||||
apartado({ id: 'p3', fechaLimite: '2026-09-05' }), // fuera de rango
|
||||
apartado({ id: 'p4', fechaLimite: '2026-08-27' }), // ya venció
|
||||
apartado({ id: 'p5', fechaLimite: '2026-09-01', estado: 'Escriturado' }),
|
||||
apartado({ id: 'p6', fechaLimite: '2026-09-01', estado: 'Cancelacion' }),
|
||||
],
|
||||
})
|
||||
const r = await resumenMiDia(monday, vendedor, new Map(), AHORA)
|
||||
expect(r.apartadosPorVencer.map((a) => a.id)).toEqual(['p1', 'p2'])
|
||||
expect(r.apartadosPorVencer[0]?.diasRestantes).toBe(0)
|
||||
expect(r.apartadosPorVencer[1]?.diasRestantes).toBe(7)
|
||||
})
|
||||
|
||||
it('sin mapeo Monday: listas personales vacías y sinMapeoMonday: true', async () => {
|
||||
const monday = mondayMock({
|
||||
leads: [lead({ id: '1' })],
|
||||
actividades: [actividad({ id: 'a1' })],
|
||||
apartados: [apartado({ id: 'p1' })],
|
||||
})
|
||||
const r = await resumenMiDia(monday, sinMapeo, new Map(), AHORA)
|
||||
expect(r.sinMapeoMonday).toBe(true)
|
||||
expect(r.misLeads).toEqual([])
|
||||
expect(r.misActividadesHoy).toEqual([])
|
||||
expect(r.conteos).toEqual({ leadsNuevosSemana: 0, actividadesAbiertas: 0 })
|
||||
// Los apartados por vencer son del pipeline completo: sí se muestran
|
||||
expect(r.apartadosPorVencer).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('conteos: leads nuevos de los últimos 7 días (incluye terminales recientes)', async () => {
|
||||
const monday = mondayMock({
|
||||
leads: [
|
||||
lead({ id: '1', createdAt: '2026-08-28T08:00:00' }), // hoy
|
||||
lead({ id: '2', createdAt: '2026-08-22T08:00:00' }), // hace 6 días
|
||||
lead({ id: '3', createdAt: '2026-08-10T08:00:00' }), // viejo
|
||||
lead({ id: '4', createdAt: '2026-08-27T08:00:00', vendedorIds: [OTRO_ID] }), // de otro
|
||||
],
|
||||
})
|
||||
const r = await resumenMiDia(monday, vendedor, new Map(), AHORA)
|
||||
expect(r.conteos.leadsNuevosSemana).toBe(2)
|
||||
})
|
||||
|
||||
it('oportunidades se omiten con nota (el board no tiene columna de asesor)', async () => {
|
||||
const r = await resumenMiDia(mondayMock({}), vendedor, new Map(), AHORA)
|
||||
expect(r.misOportunidades).toBeNull()
|
||||
expect(r.notaOportunidades).toContain('asesor')
|
||||
})
|
||||
|
||||
it('vendedor no ve sección equipo; coordinador sí (conteos por vendedor y sin asignar)', async () => {
|
||||
const monday = mondayMock({
|
||||
leads: [
|
||||
lead({ id: '1', vendedorIds: [] }), // sin asignar, NUEVO
|
||||
lead({ id: '2', vendedorIds: [], estado: 'CONTACTADO' }), // sin asignar, no NUEVO
|
||||
lead({ id: '3', vendedorIds: [MI_ID] }),
|
||||
lead({ id: '4', vendedorIds: [MI_ID], estado: 'DESCARTADO' }), // terminal: no cuenta
|
||||
lead({ id: '5', vendedorIds: [OTRO_ID] }),
|
||||
],
|
||||
})
|
||||
const nombres = new Map([[MI_ID, 'Martin Zavala']])
|
||||
|
||||
const rVendedor = await resumenMiDia(monday, vendedor, nombres, AHORA)
|
||||
expect(rVendedor.equipo).toBeUndefined()
|
||||
|
||||
const rCoord = await resumenMiDia(monday, coordinador, nombres, AHORA)
|
||||
expect(rCoord.equipo?.leadsNuevosSinAsignar).toBe(1)
|
||||
expect(rCoord.equipo?.porVendedor).toEqual([
|
||||
{ mondayUserId: MI_ID, nombre: 'Martin Zavala', leadsAsignados: 1 },
|
||||
{ mondayUserId: OTRO_ID, nombre: null, leadsAsignados: 1 },
|
||||
])
|
||||
})
|
||||
|
||||
it('corporativo y admin también ven equipo', async () => {
|
||||
const monday = mondayMock({ leads: [lead({ id: '1' })] })
|
||||
for (const rol of ['corporativo', 'admin']) {
|
||||
const r = await resumenMiDia(monday, { nombre: 'X', rol, mondayUserId: null }, new Map(), AHORA)
|
||||
expect(r.equipo).toBeDefined()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('clasificadores de estado', () => {
|
||||
it('estados terminales de lead (case-insensitive)', () => {
|
||||
expect(esEstadoTerminalLead('DESCARTADO')).toBe(true)
|
||||
expect(esEstadoTerminalLead('calificado')).toBe(true)
|
||||
expect(esEstadoTerminalLead('Abandono')).toBe(true)
|
||||
expect(esEstadoTerminalLead('NUEVO')).toBe(false)
|
||||
expect(esEstadoTerminalLead('Intento de contacto')).toBe(false)
|
||||
})
|
||||
|
||||
it('estados finales de apartado', () => {
|
||||
expect(esEstadoFinalApartado('Escriturado')).toBe(true)
|
||||
expect(esEstadoFinalApartado('CANCELADO')).toBe(true)
|
||||
expect(esEstadoFinalApartado('Pago Apartado')).toBe(false)
|
||||
})
|
||||
})
|
||||
190
api-gateway/src/services/mi-dia.service.ts
Normal file
190
api-gateway/src/services/mi-dia.service.ts
Normal file
@@ -0,0 +1,190 @@
|
||||
import type { MondayService } from './monday.service.js'
|
||||
|
||||
/**
|
||||
* Agregador "Mi día": lo que un vendedor necesita al abrir la app /hoy.
|
||||
* Todo se filtra por su mondayUserId (columna people de cada tablero); si el
|
||||
* usuario aún no tiene cuenta Monday (mondayUserId null), las listas personales
|
||||
* van vacías con sinMapeoMonday: true (las acciones del CRM siguen funcionando).
|
||||
*/
|
||||
|
||||
// Estados del board Leads en los que el lead ya no es trabajo activo del vendedor
|
||||
export const ESTADOS_TERMINALES_LEAD = ['DESCARTADO', 'CALIFICADO', 'ABANDONO']
|
||||
|
||||
// Estados del board Apartado que cierran el pipeline Enkontrol
|
||||
export const ESTADOS_FINALES_APARTADO = ['ESCRITURADO', 'CANCELACION', 'CANCELADO', 'LIBERADO', 'FORMALIZADO']
|
||||
|
||||
const ROLES_CON_EQUIPO = ['coordinador', 'corporativo', 'admin']
|
||||
|
||||
export interface UsuarioMiDia {
|
||||
nombre: string
|
||||
rol: string
|
||||
mondayUserId: number | null
|
||||
}
|
||||
|
||||
export interface LeadMiDia {
|
||||
id: string
|
||||
nombre: string
|
||||
telefono: string
|
||||
email: string
|
||||
estado: string
|
||||
origen: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface ActividadMiDia {
|
||||
id: string
|
||||
nombre: string
|
||||
tipo: string
|
||||
fecha: string
|
||||
estado: string
|
||||
}
|
||||
|
||||
export interface ApartadoPorVencer {
|
||||
id: string
|
||||
nombre: string
|
||||
unidadCodigo: string
|
||||
fechaLimite: string
|
||||
estado: string
|
||||
diasRestantes: number
|
||||
}
|
||||
|
||||
export interface ResumenMiDia {
|
||||
generadoEn: string
|
||||
sinMapeoMonday: boolean
|
||||
misLeads: LeadMiDia[]
|
||||
misActividadesHoy: ActividadMiDia[]
|
||||
apartadosPorVencer: ApartadoPorVencer[]
|
||||
// null = el tablero Oportunidades no tiene columna people de asesor (hoy no existe)
|
||||
misOportunidades: { porEtapa: Record<string, number> } | null
|
||||
notaOportunidades: string | null
|
||||
conteos: {
|
||||
leadsNuevosSemana: number // míos, últimos 7 días naturales
|
||||
actividadesAbiertas: number // mías, Estado Abierto
|
||||
}
|
||||
// Solo roles coordinador/corporativo/admin
|
||||
equipo?: {
|
||||
leadsNuevosSinAsignar: number
|
||||
porVendedor: { mondayUserId: number; nombre: string | null; leadsAsignados: number }[]
|
||||
}
|
||||
}
|
||||
|
||||
type MondayMiDia = Pick<MondayService, 'getLeads' | 'getActividades' | 'getApartados'>
|
||||
|
||||
const MS_DIA = 24 * 60 * 60 * 1000
|
||||
|
||||
/** Fecha local 'YYYY-MM-DD' desplazada n días desde `base` */
|
||||
function fechaLocal(base: Date, dias: number): string {
|
||||
const d = new Date(base.getTime() + dias * MS_DIA)
|
||||
const y = d.getFullYear()
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0')
|
||||
const dd = String(d.getDate()).padStart(2, '0')
|
||||
return `${y}-${m}-${dd}`
|
||||
}
|
||||
|
||||
export function esEstadoTerminalLead(estado: string): boolean {
|
||||
return ESTADOS_TERMINALES_LEAD.includes(estado.trim().toUpperCase())
|
||||
}
|
||||
|
||||
export function esEstadoFinalApartado(estado: string): boolean {
|
||||
return ESTADOS_FINALES_APARTADO.includes(estado.trim().toUpperCase())
|
||||
}
|
||||
|
||||
export async function resumenMiDia(
|
||||
monday: MondayMiDia,
|
||||
usuario: UsuarioMiDia,
|
||||
/** mondayUserId -> nombre para mostrar (usuarios del ecosistema ya mapeados) */
|
||||
nombresPorMondayId: Map<number, string>,
|
||||
ahora: Date = new Date(),
|
||||
): Promise<ResumenMiDia> {
|
||||
const miId = usuario.mondayUserId
|
||||
const sinMapeo = miId === null
|
||||
|
||||
const [leads, actividades, apartados] = await Promise.all([
|
||||
monday.getLeads(),
|
||||
monday.getActividades(),
|
||||
monday.getApartados(),
|
||||
])
|
||||
|
||||
const hoy = fechaLocal(ahora, 0)
|
||||
const manana = fechaLocal(ahora, 1)
|
||||
const en7Dias = fechaLocal(ahora, 7)
|
||||
const hace7DiasMs = ahora.getTime() - 7 * MS_DIA
|
||||
|
||||
// --- Listas personales (vacías si no hay mapeo Monday) ---
|
||||
const mios = sinMapeo ? [] : leads.filter((l) => l.vendedorIds.includes(miId))
|
||||
const misLeads: LeadMiDia[] = mios
|
||||
.filter((l) => !esEstadoTerminalLead(l.estado))
|
||||
.map((l) => ({
|
||||
id: l.id,
|
||||
nombre: l.nombre,
|
||||
telefono: l.telefono,
|
||||
email: l.email,
|
||||
estado: l.estado,
|
||||
origen: l.origen,
|
||||
updatedAt: l.updatedAt,
|
||||
}))
|
||||
|
||||
const misActividades = sinMapeo ? [] : actividades.filter((a) => a.responsableIds.includes(miId))
|
||||
const misActividadesHoy: ActividadMiDia[] = misActividades
|
||||
.filter((a) => a.estado.trim().toUpperCase() === 'ABIERTO' && a.fecha !== '' && a.fecha <= manana)
|
||||
.sort((a, b) => a.fecha.localeCompare(b.fecha))
|
||||
.map((a) => ({ id: a.id, nombre: a.nombre, tipo: a.tipo, fecha: a.fecha, estado: a.estado }))
|
||||
|
||||
// Apartados por vencer es del pipeline completo (Enkontrol no lleva asesor people)
|
||||
const apartadosPorVencer: ApartadoPorVencer[] = apartados
|
||||
.filter(
|
||||
(a) =>
|
||||
a.fechaLimite !== '' &&
|
||||
a.fechaLimite >= hoy &&
|
||||
a.fechaLimite <= en7Dias &&
|
||||
!esEstadoFinalApartado(a.estado),
|
||||
)
|
||||
.sort((a, b) => a.fechaLimite.localeCompare(b.fechaLimite))
|
||||
.map((a) => ({
|
||||
id: a.id,
|
||||
nombre: a.nombre,
|
||||
unidadCodigo: a.unidadCodigo,
|
||||
fechaLimite: a.fechaLimite,
|
||||
estado: a.estado,
|
||||
diasRestantes: Math.round((Date.parse(`${a.fechaLimite}T00:00:00`) - Date.parse(`${hoy}T00:00:00`)) / MS_DIA),
|
||||
}))
|
||||
|
||||
const conteos = {
|
||||
leadsNuevosSemana: mios.filter((l) => Date.parse(l.createdAt) >= hace7DiasMs).length,
|
||||
actividadesAbiertas: misActividades.filter((a) => a.estado.trim().toUpperCase() === 'ABIERTO').length,
|
||||
}
|
||||
|
||||
const resumen: ResumenMiDia = {
|
||||
generadoEn: ahora.toISOString(),
|
||||
sinMapeoMonday: sinMapeo,
|
||||
misLeads,
|
||||
misActividadesHoy,
|
||||
apartadosPorVencer,
|
||||
// El tablero Oportunidades no tiene columna people de asesor: no se puede
|
||||
// filtrar "mío"; se omite con nota explícita
|
||||
misOportunidades: null,
|
||||
notaOportunidades: 'El tablero Oportunidades no tiene columna de asesor (people); no se puede filtrar por vendedor',
|
||||
conteos,
|
||||
}
|
||||
|
||||
if (ROLES_CON_EQUIPO.includes(usuario.rol)) {
|
||||
const sinAsignar = leads.filter((l) => l.vendedorIds.length === 0 && !esEstadoTerminalLead(l.estado))
|
||||
const conteoPorId = new Map<number, number>()
|
||||
for (const l of leads) {
|
||||
if (esEstadoTerminalLead(l.estado)) continue
|
||||
for (const id of l.vendedorIds) conteoPorId.set(id, (conteoPorId.get(id) ?? 0) + 1)
|
||||
}
|
||||
resumen.equipo = {
|
||||
leadsNuevosSinAsignar: sinAsignar.filter((l) => l.estado.trim().toUpperCase() === 'NUEVO').length,
|
||||
porVendedor: [...conteoPorId.entries()]
|
||||
.map(([mondayUserId, leadsAsignados]) => ({
|
||||
mondayUserId,
|
||||
nombre: nombresPorMondayId.get(mondayUserId) ?? null,
|
||||
leadsAsignados,
|
||||
}))
|
||||
.sort((a, b) => b.leadsAsignados - a.leadsAsignados),
|
||||
}
|
||||
}
|
||||
|
||||
return resumen
|
||||
}
|
||||
@@ -36,9 +36,30 @@ export interface LeadMonday {
|
||||
updatedAt: string // ISO (updated_at del item en Monday)
|
||||
estado: string // label de la columna status 'Estado' ('' si no tiene)
|
||||
origen: string // label de la columna status 'Origen' ('' si no tiene)
|
||||
telefono: string // columna phone 'Teléfono' ('' si no tiene)
|
||||
email: string // columna email 'Email' ('' si no tiene)
|
||||
vendedorIds: number[] // user IDs asignados en la columna people 'Vendedor'
|
||||
}
|
||||
|
||||
/** Actividad del tablero Actividades (agenda de seguimiento del CRM) */
|
||||
export interface ActividadMonday {
|
||||
id: string
|
||||
nombre: string
|
||||
tipo: string // label de la columna status 'Tipo' (Llamada | Reunion | Tarea | ...)
|
||||
fecha: string // 'YYYY-MM-DD' de la columna date 'Fecha' ('' si no tiene)
|
||||
estado: string // label de la columna status 'Estado' (Abierto | Listo | ...)
|
||||
responsableIds: number[] // user IDs de la columna people 'Responsable'
|
||||
}
|
||||
|
||||
/** Apartado del tablero Apartado (pipeline Enkontrol) */
|
||||
export interface ApartadoMonday {
|
||||
id: string
|
||||
nombre: string // nombre del cliente
|
||||
unidadCodigo: string // columna text 'Unidad' ('' si no tiene)
|
||||
fechaLimite: string // 'YYYY-MM-DD' de 'Fecha límite' ('' si no tiene)
|
||||
estado: string // label de la columna status 'Estado'
|
||||
}
|
||||
|
||||
/** Oportunidad del tablero Oportunidades (pipeline comercial) */
|
||||
export interface OportunidadMonday {
|
||||
id: string
|
||||
@@ -544,6 +565,8 @@ export class MondayService {
|
||||
}
|
||||
}
|
||||
const colOrigen = cols.get('Origen')
|
||||
const colTelefono = cols.get('Teléfono')
|
||||
const colEmail = cols.get('Email')
|
||||
return {
|
||||
id: item.id,
|
||||
nombre: item.name,
|
||||
@@ -551,6 +574,8 @@ export class MondayService {
|
||||
updatedAt: item.updated_at,
|
||||
estado: colEstado ? (porId.get(colEstado.id)?.text ?? '') : '',
|
||||
origen: colOrigen ? (porId.get(colOrigen.id)?.text ?? '') : '',
|
||||
telefono: colTelefono ? (porId.get(colTelefono.id)?.text ?? '') : '',
|
||||
email: colEmail ? (porId.get(colEmail.id)?.text ?? '') : '',
|
||||
vendedorIds,
|
||||
}
|
||||
})
|
||||
@@ -615,6 +640,188 @@ export class MondayService {
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- Mi día (CRM ligero para vendedores) ----------
|
||||
|
||||
/** Parsea el value JSON de una columna people a los user IDs (solo personas) */
|
||||
private peopleIds(raw: string | null | undefined): number[] {
|
||||
if (!raw) return []
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as { personsAndTeams?: { id: number; kind: string }[] }
|
||||
return (parsed.personsAndTeams ?? []).filter((p) => p.kind === 'person').map((p) => p.id)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** Todas las actividades del tablero Actividades, con tipo, fecha, estado y responsables */
|
||||
async getActividades(): Promise<ActividadMonday[]> {
|
||||
const boardId = config.monday.boards.actividades
|
||||
if (boardId === '') return []
|
||||
const cols = await this.columnasDe(boardId)
|
||||
const colTipo = cols.get('Tipo')
|
||||
const colFecha = cols.get('Fecha')
|
||||
const colEstado = cols.get('Estado')
|
||||
const colResponsable = cols.get('Responsable')
|
||||
|
||||
const items: ItemMonday[] = []
|
||||
let cursor: string | null = null
|
||||
do {
|
||||
const data: { boards: { items_page: { cursor: string | null; items: ItemMonday[] } }[] } =
|
||||
cursor === null
|
||||
? await this.graphql(
|
||||
`query ($ids: [ID!]) {
|
||||
boards(ids: $ids) {
|
||||
items_page(limit: 500) {
|
||||
cursor
|
||||
items { id name column_values { id text value } }
|
||||
}
|
||||
}
|
||||
}`,
|
||||
{ ids: [boardId] },
|
||||
)
|
||||
: await this.graphql(
|
||||
`query ($ids: [ID!], $cursor: String!) {
|
||||
boards(ids: $ids) {
|
||||
items_page(limit: 500, cursor: $cursor) {
|
||||
cursor
|
||||
items { id name column_values { id text value } }
|
||||
}
|
||||
}
|
||||
}`,
|
||||
{ ids: [boardId], cursor },
|
||||
)
|
||||
const page = data.boards[0]?.items_page
|
||||
if (!page) break
|
||||
items.push(...page.items)
|
||||
cursor = page.cursor
|
||||
} while (cursor !== null)
|
||||
|
||||
return items.map((item) => {
|
||||
const porId = new Map(item.column_values.map((cv) => [cv.id, cv]))
|
||||
return {
|
||||
id: item.id,
|
||||
nombre: item.name,
|
||||
tipo: colTipo ? (porId.get(colTipo.id)?.text ?? '') : '',
|
||||
fecha: colFecha ? (porId.get(colFecha.id)?.text ?? '') : '',
|
||||
estado: colEstado ? (porId.get(colEstado.id)?.text ?? '') : '',
|
||||
responsableIds: colResponsable ? this.peopleIds(porId.get(colResponsable.id)?.value) : [],
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** Todos los apartados del tablero Apartado, con unidad, fecha límite y estado */
|
||||
async getApartados(): Promise<ApartadoMonday[]> {
|
||||
const boardId = config.monday.boards.apartado
|
||||
const cols = await this.columnasDe(boardId)
|
||||
const colUnidad = cols.get('Unidad')
|
||||
const colFechaLimite = cols.get('Fecha límite')
|
||||
const colEstado = cols.get('Estado')
|
||||
|
||||
const items: ItemMonday[] = []
|
||||
let cursor: string | null = null
|
||||
do {
|
||||
const data: { boards: { items_page: { cursor: string | null; items: ItemMonday[] } }[] } =
|
||||
cursor === null
|
||||
? await this.graphql(
|
||||
`query ($ids: [ID!]) {
|
||||
boards(ids: $ids) {
|
||||
items_page(limit: 500) {
|
||||
cursor
|
||||
items { id name column_values { id text value } }
|
||||
}
|
||||
}
|
||||
}`,
|
||||
{ ids: [boardId] },
|
||||
)
|
||||
: await this.graphql(
|
||||
`query ($ids: [ID!], $cursor: String!) {
|
||||
boards(ids: $ids) {
|
||||
items_page(limit: 500, cursor: $cursor) {
|
||||
cursor
|
||||
items { id name column_values { id text value } }
|
||||
}
|
||||
}
|
||||
}`,
|
||||
{ ids: [boardId], cursor },
|
||||
)
|
||||
const page = data.boards[0]?.items_page
|
||||
if (!page) break
|
||||
items.push(...page.items)
|
||||
cursor = page.cursor
|
||||
} while (cursor !== null)
|
||||
|
||||
return items.map((item) => {
|
||||
const porId = new Map(item.column_values.map((cv) => [cv.id, cv]))
|
||||
return {
|
||||
id: item.id,
|
||||
nombre: item.name,
|
||||
unidadCodigo: colUnidad ? (porId.get(colUnidad.id)?.text ?? '') : '',
|
||||
fechaLimite: colFechaLimite ? (porId.get(colFechaLimite.id)?.text ?? '') : '',
|
||||
estado: colEstado ? (porId.get(colEstado.id)?.text ?? '') : '',
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Labels de una columna status/dropdown (settings_str del board).
|
||||
* Monday los devuelve como objeto {index: label} o como arreglo [{id, name}].
|
||||
*/
|
||||
async labelsDeColumna(boardId: string, titulo: string): Promise<string[]> {
|
||||
const data = await this.graphql<{ boards: { columns: { id: string; title: string; settings_str: string }[] }[] }>(
|
||||
`query ($ids: [ID!]) { boards(ids: $ids) { columns { id title settings_str } } }`,
|
||||
{ ids: [boardId] },
|
||||
)
|
||||
const col = data.boards[0]?.columns.find((c) => c.title === titulo)
|
||||
if (!col) throw new AppError(500, `Columna "${titulo}" no existe en el tablero ${boardId}`)
|
||||
try {
|
||||
const settings = JSON.parse(col.settings_str || '{}') as { labels?: Record<string, string> | { name: string }[] }
|
||||
const labels = settings.labels
|
||||
if (Array.isArray(labels)) return labels.map((l) => l.name)
|
||||
if (labels && typeof labels === 'object') return Object.values(labels)
|
||||
return []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** Item en el tablero Leads (Estado NUEVO; captura rápida del vendedor) */
|
||||
async crearLead(datos: DatosLead): Promise<string> {
|
||||
const boardId = config.monday.boards.leads
|
||||
const columnValues = await this.construirColumnValues(boardId, {
|
||||
Estado: 'NUEVO',
|
||||
Teléfono: datos.telefono,
|
||||
Email: datos.email,
|
||||
Origen: datos.origenLabel,
|
||||
Notas: datos.notas,
|
||||
})
|
||||
return this.crearItem(boardId, datos.nombre, columnValues)
|
||||
}
|
||||
|
||||
/**
|
||||
* Lead con el mismo teléfono (dedup de captura rápida). Compara solo dígitos
|
||||
* y los últimos 10 (tolerante a lada/prefijo 52). null si no hay duplicado.
|
||||
*/
|
||||
async buscarLeadPorTelefono(telefono: string): Promise<LeadMonday | null> {
|
||||
const digitos = telefono.replace(/\D/g, '')
|
||||
if (digitos.length < 10) return null
|
||||
const clave = digitos.slice(-10)
|
||||
const leads = await this.getLeads()
|
||||
return (
|
||||
leads.find((l) => {
|
||||
const d = l.telefono.replace(/\D/g, '')
|
||||
return d.length >= 10 && d.slice(-10) === clave
|
||||
}) ?? null
|
||||
)
|
||||
}
|
||||
|
||||
/** Borra un item de cualquier tablero (limpieza de datos de prueba) */
|
||||
async eliminarItem(itemId: string): Promise<void> {
|
||||
await this.graphql<{ delete_item: { id: string } }>(
|
||||
`mutation ($itemId: ID!) { delete_item(item_id: $itemId) { id } }`,
|
||||
{ itemId },
|
||||
)
|
||||
}
|
||||
|
||||
/** Item en el tablero Ventas (se crea cuando una oportunidad pasa a 'Ganado') */
|
||||
async crearVenta(datos: DatosVenta): Promise<string> {
|
||||
const boardId = config.monday.boards.ventas
|
||||
@@ -773,6 +980,14 @@ export interface DatosActividad {
|
||||
leadItemId?: string // item del tablero Leads relacionado (se omite si no aplica)
|
||||
}
|
||||
|
||||
export interface DatosLead {
|
||||
nombre: string
|
||||
telefono?: string | undefined
|
||||
email?: string | undefined
|
||||
origenLabel?: string | undefined // label real de la columna status 'Origen' del board Leads
|
||||
notas?: string | undefined
|
||||
}
|
||||
|
||||
/** Singleton usado por los controllers (los tests instancian el suyo) */
|
||||
export const mondayService = new MondayService()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user