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()
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@ import { describe, it, expect } from 'vitest'
|
||||
import { MODULOS } from './modulos'
|
||||
|
||||
describe('MODULOS', () => {
|
||||
it('expone los 5 módulos del ecosistema', () => {
|
||||
expect(MODULOS).toHaveLength(5)
|
||||
expect(MODULOS.map((m) => m.id)).toEqual(['cotizador', 'alta-clientes', 'cobranza', 'agente-ia', 'tableros'])
|
||||
it('expone los 6 módulos del ecosistema', () => {
|
||||
expect(MODULOS).toHaveLength(6)
|
||||
expect(MODULOS.map((m) => m.id)).toEqual(['cotizador', 'alta-clientes', 'cobranza', 'agente-ia', 'tableros', 'mi-dia'])
|
||||
})
|
||||
|
||||
it('cada módulo tiene nombre, descripción y URL válida', () => {
|
||||
@@ -22,6 +22,7 @@ describe('MODULOS', () => {
|
||||
expect(urls['cobranza']).toBe('/pay/')
|
||||
expect(urls['agente-ia']).toBe('/ai/')
|
||||
expect(urls['tableros']).toBe('/dash/')
|
||||
expect(urls['mi-dia']).toBe('/hoy/')
|
||||
})
|
||||
|
||||
it('no hay ids ni URLs duplicadas', () => {
|
||||
|
||||
@@ -37,4 +37,10 @@ export const MODULOS: Modulo[] = [
|
||||
descripcion: 'KPIs comerciales, inventario y cobranza en tiempo real',
|
||||
url: '/dash/',
|
||||
},
|
||||
{
|
||||
id: 'mi-dia',
|
||||
nombre: 'Mi día',
|
||||
descripcion: 'Agenda del vendedor: leads, actividades y captura rápida',
|
||||
url: '/hoy/',
|
||||
},
|
||||
]
|
||||
|
||||
12
apps/mi-dia/index.html
Normal file
12
apps/mi-dia/index.html
Normal file
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>FRASA Desarrollos — Mi día</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
3897
apps/mi-dia/package-lock.json
generated
Normal file
3897
apps/mi-dia/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
27
apps/mi-dia/package.json
Normal file
27
apps/mi-dia/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "mi-dia",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"test": "vitest run",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/inter": "^5.3.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.0.0",
|
||||
"@types/react": "^19.0.2",
|
||||
"@types/react-dom": "^19.0.2",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "~5.6.3",
|
||||
"vite": "^6.0.7",
|
||||
"vitest": "^2.1.8"
|
||||
}
|
||||
}
|
||||
38
apps/mi-dia/src/components/AuthGate.tsx
Normal file
38
apps/mi-dia/src/components/AuthGate.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { getSesion, logout, type Sesion } from '../services/auth'
|
||||
import LoginScreen from './LoginScreen'
|
||||
|
||||
/**
|
||||
* Gate de autenticación: sin sesión solo se ve el login; con sesión se ve la
|
||||
* app con una barra discreta "nombre · rol" y botón "Salir".
|
||||
*/
|
||||
export default function AuthGate({ children }: { children: ReactNode }) {
|
||||
const [sesion, setSesion] = useState<Sesion | null>(() => getSesion())
|
||||
|
||||
if (!sesion) {
|
||||
return <LoginScreen onLogin={() => setSesion(getSesion())} />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-white text-neutral-900">
|
||||
<div className="border-b border-neutral-200">
|
||||
<div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-2">
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
{sesion.usuario.nombre} · {sesion.usuario.rol}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
logout()
|
||||
setSesion(null)
|
||||
}}
|
||||
className="text-xs font-bold uppercase tracking-widest text-accent transition-colors duration-150 hover:text-accent-hover"
|
||||
>
|
||||
Salir
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
11
apps/mi-dia/src/components/KpiCard.tsx
Normal file
11
apps/mi-dia/src/components/KpiCard.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
export default function KpiCard({ titulo, valor, detalle }: { titulo: string; valor: ReactNode; detalle?: string }) {
|
||||
return (
|
||||
<div className="border border-neutral-200 bg-white p-6">
|
||||
<p className="text-xs font-bold uppercase tracking-widest text-neutral-500">{titulo}</p>
|
||||
<p className="mt-2 text-3xl font-light text-neutral-900">{valor}</p>
|
||||
{detalle && <p className="mt-2 text-xs text-neutral-500">{detalle}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
88
apps/mi-dia/src/components/LoginScreen.tsx
Normal file
88
apps/mi-dia/src/components/LoginScreen.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { login, ErrorLogin, type UsuarioSesion } from '../services/auth'
|
||||
|
||||
/** Pantalla de login StudioBlank: marca FRASA, usuario + contraseña, Enter envía */
|
||||
export default function LoginScreen({ onLogin }: { onLogin: (usuario: UsuarioSesion) => void }) {
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [cargando, setCargando] = useState(false)
|
||||
|
||||
async function enviar(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
setError(null)
|
||||
setCargando(true)
|
||||
try {
|
||||
onLogin(await login(username, password))
|
||||
} catch (err) {
|
||||
setError(err instanceof ErrorLogin ? err.message : 'Usuario o contraseña incorrectos')
|
||||
} finally {
|
||||
setCargando(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-white px-4">
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="mb-10 text-center">
|
||||
<p className="text-lg font-bold tracking-widest">FRASA</p>
|
||||
<p className="mt-2 text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
Acceso al ecosistema
|
||||
</p>
|
||||
</div>
|
||||
<form onSubmit={enviar} className="space-y-6">
|
||||
<div>
|
||||
<label
|
||||
htmlFor="login-usuario"
|
||||
className="mb-2 block text-xs font-bold uppercase tracking-widest text-neutral-500"
|
||||
>
|
||||
Usuario
|
||||
</label>
|
||||
<input
|
||||
id="login-usuario"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
autoComplete="username"
|
||||
autoFocus
|
||||
required
|
||||
className="w-full border border-neutral-300 px-4 py-3 text-sm focus:border-accent focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label
|
||||
htmlFor="login-password"
|
||||
className="mb-2 block text-xs font-bold uppercase tracking-widest text-neutral-500"
|
||||
>
|
||||
Contraseña
|
||||
</label>
|
||||
<input
|
||||
id="login-password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
className="w-full border border-neutral-300 px-4 py-3 text-sm focus:border-accent focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p
|
||||
role="alert"
|
||||
className="border border-red-700 px-4 py-3 text-xs font-bold uppercase tracking-widest text-red-700"
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={cargando}
|
||||
className="w-full bg-accent px-5 py-3 text-xs font-bold uppercase tracking-widest text-white transition-colors duration-150 hover:bg-accent-hover disabled:opacity-50"
|
||||
>
|
||||
{cargando ? 'Entrando…' : 'Entrar'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
23
apps/mi-dia/src/index.css
Normal file
23
apps/mi-dia/src/index.css
Normal file
@@ -0,0 +1,23 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
|
||||
--color-accent: #1B4332;
|
||||
--radius-sm: 0;
|
||||
--radius-md: 0;
|
||||
--radius-lg: 0;
|
||||
--radius-xl: 0;
|
||||
--radius-2xl: 0;
|
||||
--radius-3xl: 0;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
@apply bg-white text-neutral-900 antialiased;
|
||||
}
|
||||
|
||||
*:focus-visible {
|
||||
outline: 2px solid #1B4332;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
64
apps/mi-dia/src/lib/mi-dia.test.ts
Normal file
64
apps/mi-dia/src/lib/mi-dia.test.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
esActividadVencida,
|
||||
esRolConEquipo,
|
||||
formatoFechaCorta,
|
||||
hoyLocal,
|
||||
MOTIVOS_NO_COMPRA,
|
||||
ORIGENES_LEAD,
|
||||
textoDiasRestantes,
|
||||
} from './mi-dia'
|
||||
|
||||
describe('catálogos', () => {
|
||||
it('orígenes = labels reales de la columna Origen del board Leads', () => {
|
||||
expect([...ORIGENES_LEAD]).toEqual(['WhatsApp', 'Web', 'Recomendado', 'Facebook', 'Otro'])
|
||||
})
|
||||
|
||||
it('motivos de descarte = vocabulario CRM (igual que el API)', () => {
|
||||
expect(MOTIVOS_NO_COMPRA).toContain('Precio')
|
||||
expect(MOTIVOS_NO_COMPRA).toContain('Timing')
|
||||
expect(MOTIVOS_NO_COMPRA).toHaveLength(7)
|
||||
})
|
||||
})
|
||||
|
||||
describe('esRolConEquipo', () => {
|
||||
it('coordinador, corporativo y admin ven equipo; vendedor no', () => {
|
||||
expect(esRolConEquipo('coordinador')).toBe(true)
|
||||
expect(esRolConEquipo('corporativo')).toBe(true)
|
||||
expect(esRolConEquipo('admin')).toBe(true)
|
||||
expect(esRolConEquipo('vendedor')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatoFechaCorta', () => {
|
||||
it('recorta el año', () => {
|
||||
expect(formatoFechaCorta('2026-08-29')).toBe('29/08')
|
||||
})
|
||||
|
||||
it('tolera cadenas mal formadas devolviéndolas tal cual', () => {
|
||||
expect(formatoFechaCorta('sin-fecha')).toBe('sin-fecha')
|
||||
})
|
||||
})
|
||||
|
||||
describe('textoDiasRestantes', () => {
|
||||
it('hoy, mañana y n días', () => {
|
||||
expect(textoDiasRestantes(0)).toBe('Vence hoy')
|
||||
expect(textoDiasRestantes(1)).toBe('Vence mañana')
|
||||
expect(textoDiasRestantes(5)).toBe('Vence en 5 días')
|
||||
})
|
||||
})
|
||||
|
||||
describe('esActividadVencida', () => {
|
||||
it('compara contra la fecha de hoy', () => {
|
||||
expect(esActividadVencida('2026-08-27', '2026-08-28')).toBe(true)
|
||||
expect(esActividadVencida('2026-08-28', '2026-08-28')).toBe(false)
|
||||
expect(esActividadVencida('2026-08-29', '2026-08-28')).toBe(false)
|
||||
expect(esActividadVencida('', '2026-08-28')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hoyLocal', () => {
|
||||
it('devuelve YYYY-MM-DD', () => {
|
||||
expect(hoyLocal()).toMatch(/^\d{4}-\d{2}-\d{2}$/)
|
||||
})
|
||||
})
|
||||
96
apps/mi-dia/src/lib/mi-dia.ts
Normal file
96
apps/mi-dia/src/lib/mi-dia.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
// Tipos y transformaciones de la app "Mi día" (espejo del contrato del API)
|
||||
|
||||
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 // 'YYYY-MM-DD'
|
||||
estado: string
|
||||
}
|
||||
|
||||
export interface ApartadoPorVencer {
|
||||
id: string
|
||||
nombre: string
|
||||
unidadCodigo: string
|
||||
fechaLimite: string // 'YYYY-MM-DD'
|
||||
estado: string
|
||||
diasRestantes: number
|
||||
}
|
||||
|
||||
export interface ResumenMiDia {
|
||||
generadoEn: string
|
||||
sinMapeoMonday: boolean
|
||||
misLeads: LeadMiDia[]
|
||||
misActividadesHoy: ActividadMiDia[]
|
||||
apartadosPorVencer: ApartadoPorVencer[]
|
||||
misOportunidades: { porEtapa: Record<string, number> } | null
|
||||
notaOportunidades: string | null
|
||||
conteos: {
|
||||
leadsNuevosSemana: number
|
||||
actividadesAbiertas: number
|
||||
}
|
||||
equipo?: {
|
||||
leadsNuevosSinAsignar: number
|
||||
porVendedor: { mondayUserId: number; nombre: string | null; leadsAsignados: number }[]
|
||||
}
|
||||
}
|
||||
|
||||
// Labels reales de la columna status 'Origen' del board Leads (verificados en Monday)
|
||||
export const ORIGENES_LEAD = ['WhatsApp', 'Web', 'Recomendado', 'Facebook', 'Otro'] as const
|
||||
|
||||
// Categorías del dropdown Motivo No Compra (vocabulario CRM FRASA, igual que el API)
|
||||
export const MOTIVOS_NO_COMPRA = [
|
||||
'Precio',
|
||||
'Producto',
|
||||
'Ubicacion',
|
||||
'Financiamiento',
|
||||
'Competencia',
|
||||
'Cliente',
|
||||
'Timing',
|
||||
] as const
|
||||
|
||||
export type MotivoNoCompra = (typeof MOTIVOS_NO_COMPRA)[number]
|
||||
|
||||
const ROLES_CON_EQUIPO = ['coordinador', 'corporativo', 'admin']
|
||||
|
||||
/** ¿El rol ve la sección de equipo? (misma regla que el API) */
|
||||
export function esRolConEquipo(rol: string): boolean {
|
||||
return ROLES_CON_EQUIPO.includes(rol)
|
||||
}
|
||||
|
||||
/** 'YYYY-MM-DD' → 'dd/mm' (sin año: la agenda es de esta semana) */
|
||||
export function formatoFechaCorta(fecha: string): string {
|
||||
const [, m, d] = fecha.split('-')
|
||||
if (!m || !d) return fecha
|
||||
return `${d}/${m}`
|
||||
}
|
||||
|
||||
/** Texto de urgencia de un apartado según los días que faltan */
|
||||
export function textoDiasRestantes(dias: number): string {
|
||||
if (dias <= 0) return 'Vence hoy'
|
||||
if (dias === 1) return 'Vence mañana'
|
||||
return `Vence en ${dias} días`
|
||||
}
|
||||
|
||||
/** ¿La fecha de una actividad ya pasó? (vencida, para marcarla en la lista) */
|
||||
export function esActividadVencida(fecha: string, hoy: string): boolean {
|
||||
return fecha !== '' && fecha < hoy
|
||||
}
|
||||
|
||||
/** Fecha local 'YYYY-MM-DD' de hoy (para comparar contra las del API) */
|
||||
export function hoyLocal(): string {
|
||||
const d = new Date()
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0')
|
||||
const dd = String(d.getDate()).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${m}-${dd}`
|
||||
}
|
||||
17
apps/mi-dia/src/main.tsx
Normal file
17
apps/mi-dia/src/main.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import '@fontsource/inter/300.css'
|
||||
import '@fontsource/inter/400.css'
|
||||
import '@fontsource/inter/500.css'
|
||||
import '@fontsource/inter/700.css'
|
||||
import './index.css'
|
||||
import AuthGate from './components/AuthGate'
|
||||
import MiDiaPage from './pages/MiDiaPage'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<AuthGate>
|
||||
<MiDiaPage />
|
||||
</AuthGate>
|
||||
</StrictMode>,
|
||||
)
|
||||
484
apps/mi-dia/src/pages/MiDiaPage.tsx
Normal file
484
apps/mi-dia/src/pages/MiDiaPage.tsx
Normal file
@@ -0,0 +1,484 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from 'react'
|
||||
import KpiCard from '../components/KpiCard'
|
||||
import {
|
||||
esActividadVencida,
|
||||
esRolConEquipo,
|
||||
formatoFechaCorta,
|
||||
hoyLocal,
|
||||
MOTIVOS_NO_COMPRA,
|
||||
ORIGENES_LEAD,
|
||||
textoDiasRestantes,
|
||||
type LeadMiDia,
|
||||
type MotivoNoCompra,
|
||||
type ResumenMiDia,
|
||||
} from '../lib/mi-dia'
|
||||
import { cambiarEstadoLead, crearLead, descartarLead, fetchResumenMiDia } from '../services/mi-dia'
|
||||
import { getSesion } from '../services/auth'
|
||||
|
||||
function TituloSeccion({ children }: { children: string }) {
|
||||
return <h2 className="mb-4 text-xs font-bold uppercase tracking-widest text-neutral-500">{children}</h2>
|
||||
}
|
||||
|
||||
function EstadoVacio({ mensaje }: { mensaje: string }) {
|
||||
return (
|
||||
<div className="flex h-24 items-center justify-center border border-dashed border-neutral-300">
|
||||
<p className="text-xs font-bold uppercase tracking-widest text-neutral-400">{mensaje}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const CLASE_BOTON_ACCION =
|
||||
'border border-accent px-3 py-1.5 text-xs font-bold uppercase tracking-widest text-accent transition-colors duration-150 hover:bg-accent hover:text-white disabled:opacity-50'
|
||||
|
||||
/** Modal de descarte: motivo (dropdown CRM) + comentario opcional */
|
||||
function ModalDescartar({
|
||||
lead,
|
||||
onCancelar,
|
||||
onConfirmar,
|
||||
enviando,
|
||||
}: {
|
||||
lead: LeadMiDia
|
||||
onCancelar: () => void
|
||||
onConfirmar: (motivo: MotivoNoCompra, comentario: string) => void
|
||||
enviando: boolean
|
||||
}) {
|
||||
const [motivo, setMotivo] = useState<MotivoNoCompra>(MOTIVOS_NO_COMPRA[0])
|
||||
const [comentario, setComentario] = useState('')
|
||||
return (
|
||||
<div className="fixed inset-0 z-10 flex items-center justify-center bg-black/40 px-4" role="dialog" aria-modal="true">
|
||||
<div className="w-full max-w-md border border-neutral-300 bg-white p-6">
|
||||
<p className="text-xs font-bold uppercase tracking-widest text-neutral-500">Descartar lead</p>
|
||||
<p className="mt-2 text-lg font-light">{lead.nombre}</p>
|
||||
<form
|
||||
className="mt-6 space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
onConfirmar(motivo, comentario.trim())
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<label htmlFor="motivo-descarte" className="mb-2 block text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
Motivo
|
||||
</label>
|
||||
<select
|
||||
id="motivo-descarte"
|
||||
value={motivo}
|
||||
onChange={(e) => setMotivo(e.target.value as MotivoNoCompra)}
|
||||
className="w-full border border-neutral-300 px-4 py-3 text-sm focus:border-accent focus:outline-none"
|
||||
>
|
||||
{MOTIVOS_NO_COMPRA.map((m) => (
|
||||
<option key={m} value={m}>
|
||||
{m}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="comentario-descarte" className="mb-2 block text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
Comentario (opcional)
|
||||
</label>
|
||||
<textarea
|
||||
id="comentario-descarte"
|
||||
value={comentario}
|
||||
onChange={(e) => setComentario(e.target.value)}
|
||||
rows={3}
|
||||
className="w-full border border-neutral-300 px-4 py-3 text-sm focus:border-accent focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancelar}
|
||||
disabled={enviando}
|
||||
className="border border-neutral-300 px-5 py-2 text-xs font-bold uppercase tracking-widest text-neutral-500 transition-colors duration-150 hover:border-neutral-500 disabled:opacity-50"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={enviando}
|
||||
className="bg-accent px-5 py-2 text-xs font-bold uppercase tracking-widest text-white transition-colors duration-150 hover:bg-accent-hover disabled:opacity-50"
|
||||
>
|
||||
{enviando ? 'Descartando…' : 'Descartar'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Fila de lead con acciones rápidas (contactado / intento / cita / descartar) */
|
||||
function FilaLead({
|
||||
lead,
|
||||
onAccion,
|
||||
onDescartar,
|
||||
enviando,
|
||||
}: {
|
||||
lead: LeadMiDia
|
||||
onAccion: (estado: string, fecha?: string) => void
|
||||
onDescartar: () => void
|
||||
enviando: boolean
|
||||
}) {
|
||||
const [conCita, setConCita] = useState(false)
|
||||
const [fechaCita, setFechaCita] = useState('')
|
||||
return (
|
||||
<li className="border border-neutral-200 p-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium">{lead.nombre}</p>
|
||||
<p className="mt-1 text-xs text-neutral-500">
|
||||
{lead.telefono || 'Sin teléfono'}
|
||||
{lead.origen ? ` · ${lead.origen}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
<span className="border border-neutral-300 px-2 py-1 text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
{lead.estado || 'Sin estado'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
<button type="button" disabled={enviando} onClick={() => onAccion('CONTACTADO')} className={CLASE_BOTON_ACCION}>
|
||||
Contactado
|
||||
</button>
|
||||
<button type="button" disabled={enviando} onClick={() => onAccion('Intento de contacto')} className={CLASE_BOTON_ACCION}>
|
||||
Intento
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={enviando}
|
||||
onClick={() => (conCita ? onAccion('AGENDA CITA', fechaCita || undefined) : setConCita(true))}
|
||||
className={CLASE_BOTON_ACCION}
|
||||
>
|
||||
{conCita ? 'Confirmar cita' : 'Agenda cita'}
|
||||
</button>
|
||||
{conCita && (
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Fecha de la cita"
|
||||
value={fechaCita}
|
||||
onChange={(e) => setFechaCita(e.target.value)}
|
||||
className="border border-neutral-300 px-2 py-1.5 text-xs focus:border-accent focus:outline-none"
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={enviando}
|
||||
onClick={onDescartar}
|
||||
className="border border-red-700 px-3 py-1.5 text-xs font-bold uppercase tracking-widest text-red-700 transition-colors duration-150 hover:bg-red-700 hover:text-white disabled:opacity-50"
|
||||
>
|
||||
Descartar
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
export default function MiDiaPage() {
|
||||
const nombreVendedor = getSesion()?.usuario.nombre ?? ''
|
||||
const rol = getSesion()?.usuario.rol ?? 'vendedor'
|
||||
const [resumen, setResumen] = useState<ResumenMiDia | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [cargando, setCargando] = useState(true)
|
||||
const [enviando, setEnviando] = useState(false)
|
||||
const [aviso, setAviso] = useState<string | null>(null)
|
||||
const [descartando, setDescartando] = useState<LeadMiDia | null>(null)
|
||||
|
||||
// Captura rápida
|
||||
const [capNombre, setCapNombre] = useState('')
|
||||
const [capTelefono, setCapTelefono] = useState('')
|
||||
const [capOrigen, setCapOrigen] = useState<string>(ORIGENES_LEAD[0])
|
||||
const [capNotas, setCapNotas] = useState('')
|
||||
const [capEnviando, setCapEnviando] = useState(false)
|
||||
const [capMensaje, setCapMensaje] = useState<{ tipo: 'ok' | 'error'; texto: string } | null>(null)
|
||||
|
||||
const cargar = useCallback(async () => {
|
||||
setCargando(true)
|
||||
try {
|
||||
setResumen(await fetchResumenMiDia())
|
||||
setError(null)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'No se pudo cargar tu día')
|
||||
} finally {
|
||||
setCargando(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void cargar()
|
||||
}, [cargar])
|
||||
|
||||
/** Ejecuta una acción sobre un lead y refresca el resumen */
|
||||
async function ejecutar(accion: () => Promise<unknown>, mensajeError: string) {
|
||||
setEnviando(true)
|
||||
setAviso(null)
|
||||
try {
|
||||
await accion()
|
||||
await cargar()
|
||||
} catch (err) {
|
||||
setAviso(err instanceof Error ? err.message : mensajeError)
|
||||
} finally {
|
||||
setEnviando(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function enviarCaptura(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
setCapEnviando(true)
|
||||
setCapMensaje(null)
|
||||
try {
|
||||
await crearLead({
|
||||
nombre: capNombre.trim(),
|
||||
...(capTelefono.trim() !== '' ? { telefono: capTelefono.trim() } : {}),
|
||||
...(capOrigen !== '' ? { origen: capOrigen } : {}),
|
||||
...(capNotas.trim() !== '' ? { notas: capNotas.trim() } : {}),
|
||||
})
|
||||
setCapMensaje({ tipo: 'ok', texto: 'Lead registrado, se asignará por round-robin' })
|
||||
setCapNombre('')
|
||||
setCapTelefono('')
|
||||
setCapNotas('')
|
||||
} catch (err) {
|
||||
setCapMensaje({ tipo: 'error', texto: err instanceof Error ? err.message : 'No se pudo registrar el lead' })
|
||||
} finally {
|
||||
setCapEnviando(false)
|
||||
}
|
||||
}
|
||||
|
||||
const hoy = hoyLocal()
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-6xl px-4 py-8">
|
||||
<div className="mb-8 flex items-end justify-between">
|
||||
<div>
|
||||
<p className="text-xs font-bold uppercase tracking-widest text-accent">FRASA · Mi día</p>
|
||||
<h1 className="mt-2 text-3xl font-light text-neutral-900">{nombreVendedor}</h1>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void cargar()}
|
||||
disabled={cargando}
|
||||
className="border border-accent px-5 py-2 text-xs font-bold uppercase tracking-widest text-accent transition-colors duration-150 hover:bg-accent hover:text-white disabled:opacity-50"
|
||||
>
|
||||
{cargando ? 'Actualizando…' : 'Actualizar'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p role="alert" className="mb-8 border border-amber-700 px-4 py-3 text-xs font-bold uppercase tracking-widest text-amber-700">
|
||||
Sin datos del API — {error}
|
||||
</p>
|
||||
)}
|
||||
{aviso && (
|
||||
<p role="alert" className="mb-8 border border-red-700 px-4 py-3 text-xs font-bold uppercase tracking-widest text-red-700">
|
||||
{aviso}
|
||||
</p>
|
||||
)}
|
||||
{resumen?.sinMapeoMonday && (
|
||||
<p className="mb-8 border border-neutral-300 px-4 py-3 text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
Tu usuario aún no está vinculado a Monday; las acciones siguen funcionando
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!resumen && cargando && <EstadoVacio mensaje="Cargando…" />}
|
||||
|
||||
{resumen && (
|
||||
<>
|
||||
<section aria-label="Indicadores del día" className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<KpiCard titulo="Leads asignados" valor={resumen.misLeads.length} />
|
||||
<KpiCard
|
||||
titulo="Actividades de hoy"
|
||||
valor={resumen.misActividadesHoy.length}
|
||||
detalle={`${resumen.conteos.actividadesAbiertas} abiertas en total`}
|
||||
/>
|
||||
<KpiCard titulo="Apartados por vencer" valor={resumen.apartadosPorVencer.length} detalle="próximos 7 días" />
|
||||
<KpiCard titulo="Leads nuevos esta semana" valor={resumen.conteos.leadsNuevosSemana} />
|
||||
</section>
|
||||
|
||||
<section aria-label="Mis actividades" className="mt-12">
|
||||
<TituloSeccion>Mis actividades</TituloSeccion>
|
||||
{resumen.misActividadesHoy.length === 0 ? (
|
||||
<EstadoVacio mensaje="Sin actividades para hoy" />
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{resumen.misActividadesHoy.map((a) => (
|
||||
<li key={a.id} className="flex items-center justify-between gap-3 border border-neutral-200 px-4 py-3">
|
||||
<p className="text-sm">
|
||||
{a.nombre}
|
||||
{a.tipo ? <span className="ml-2 text-xs uppercase tracking-widest text-neutral-400">{a.tipo}</span> : null}
|
||||
</p>
|
||||
<span
|
||||
className={`text-xs font-bold uppercase tracking-widest ${
|
||||
esActividadVencida(a.fecha, hoy) ? 'text-red-700' : 'text-neutral-500'
|
||||
}`}
|
||||
>
|
||||
{formatoFechaCorta(a.fecha)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{resumen.apartadosPorVencer.length > 0 && (
|
||||
<section aria-label="Apartados por vencer" className="mt-12">
|
||||
<TituloSeccion>Apartados por vencer</TituloSeccion>
|
||||
<ul className="space-y-2">
|
||||
{resumen.apartadosPorVencer.map((a) => (
|
||||
<li key={a.id} className="flex flex-wrap items-center justify-between gap-3 border border-neutral-200 px-4 py-3">
|
||||
<p className="text-sm">
|
||||
{a.nombre}
|
||||
{a.unidadCodigo ? <span className="ml-2 text-xs text-neutral-400">{a.unidadCodigo}</span> : null}
|
||||
</p>
|
||||
<span
|
||||
className={`text-xs font-bold uppercase tracking-widest ${
|
||||
a.diasRestantes <= 1 ? 'text-red-700' : 'text-amber-700'
|
||||
}`}
|
||||
>
|
||||
{textoDiasRestantes(a.diasRestantes)} · {formatoFechaCorta(a.fechaLimite)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section aria-label="Mis leads" className="mt-12">
|
||||
<TituloSeccion>Mis leads</TituloSeccion>
|
||||
{resumen.misLeads.length === 0 ? (
|
||||
<EstadoVacio mensaje="Sin leads asignados" />
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{resumen.misLeads.map((lead) => (
|
||||
<FilaLead
|
||||
key={lead.id}
|
||||
lead={lead}
|
||||
enviando={enviando}
|
||||
onAccion={(estado, fecha) => void ejecutar(() => cambiarEstadoLead(lead.id, estado, fecha), 'No se pudo actualizar el lead')}
|
||||
onDescartar={() => setDescartando(lead)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section aria-label="Captura rápida de lead" className="mt-12">
|
||||
<TituloSeccion>Captura rápida de lead</TituloSeccion>
|
||||
<form onSubmit={enviarCaptura} className="grid gap-4 border border-neutral-200 p-6 sm:grid-cols-2">
|
||||
<div>
|
||||
<label htmlFor="cap-nombre" className="mb-2 block text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
Nombre
|
||||
</label>
|
||||
<input
|
||||
id="cap-nombre"
|
||||
type="text"
|
||||
value={capNombre}
|
||||
onChange={(e) => setCapNombre(e.target.value)}
|
||||
required
|
||||
className="w-full border border-neutral-300 px-4 py-3 text-sm focus:border-accent focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="cap-telefono" className="mb-2 block text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
Teléfono
|
||||
</label>
|
||||
<input
|
||||
id="cap-telefono"
|
||||
type="tel"
|
||||
value={capTelefono}
|
||||
onChange={(e) => setCapTelefono(e.target.value)}
|
||||
className="w-full border border-neutral-300 px-4 py-3 text-sm focus:border-accent focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="cap-origen" className="mb-2 block text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
Origen
|
||||
</label>
|
||||
<select
|
||||
id="cap-origen"
|
||||
value={capOrigen}
|
||||
onChange={(e) => setCapOrigen(e.target.value)}
|
||||
className="w-full border border-neutral-300 px-4 py-3 text-sm focus:border-accent focus:outline-none"
|
||||
>
|
||||
{ORIGENES_LEAD.map((o) => (
|
||||
<option key={o} value={o}>
|
||||
{o}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="cap-notas" className="mb-2 block text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
Notas
|
||||
</label>
|
||||
<input
|
||||
id="cap-notas"
|
||||
type="text"
|
||||
value={capNotas}
|
||||
onChange={(e) => setCapNotas(e.target.value)}
|
||||
className="w-full border border-neutral-300 px-4 py-3 text-sm focus:border-accent focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
{capMensaje && (
|
||||
<p
|
||||
role="status"
|
||||
className={`border px-4 py-3 text-xs font-bold uppercase tracking-widest sm:col-span-2 ${
|
||||
capMensaje.tipo === 'ok' ? 'border-accent text-accent' : 'border-red-700 text-red-700'
|
||||
}`}
|
||||
>
|
||||
{capMensaje.texto}
|
||||
</p>
|
||||
)}
|
||||
<div className="sm:col-span-2">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={capEnviando}
|
||||
className="bg-accent px-5 py-3 text-xs font-bold uppercase tracking-widest text-white transition-colors duration-150 hover:bg-accent-hover disabled:opacity-50"
|
||||
>
|
||||
{capEnviando ? 'Registrando…' : 'Registrar lead'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{esRolConEquipo(rol) && resumen.equipo && (
|
||||
<section aria-label="Equipo" className="mt-12">
|
||||
<TituloSeccion>Equipo</TituloSeccion>
|
||||
<p className="mb-4 text-sm text-neutral-500">
|
||||
Leads nuevos sin asignar: <strong>{resumen.equipo.leadsNuevosSinAsignar}</strong>
|
||||
</p>
|
||||
{resumen.equipo.porVendedor.length === 0 ? (
|
||||
<EstadoVacio mensaje="Sin leads asignados en el equipo" />
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{resumen.equipo.porVendedor.map((v) => (
|
||||
<li key={v.mondayUserId} className="flex items-center justify-between border border-neutral-200 px-4 py-3">
|
||||
<p className="text-sm">{v.nombre ?? `Monday #${v.mondayUserId}`}</p>
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
{v.leadsAsignados} lead(s)
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{descartando && (
|
||||
<ModalDescartar
|
||||
lead={descartando}
|
||||
enviando={enviando}
|
||||
onCancelar={() => setDescartando(null)}
|
||||
onConfirmar={(motivo, comentario) => {
|
||||
const lead = descartando
|
||||
setDescartando(null)
|
||||
void ejecutar(
|
||||
() => descartarLead(lead.id, motivo, comentario === '' ? undefined : comentario),
|
||||
'No se pudo descartar el lead',
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
77
apps/mi-dia/src/services/auth.ts
Normal file
77
apps/mi-dia/src/services/auth.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
// Sesión de autenticación contra el API Gateway (JWT guardado en localStorage)
|
||||
const API_URL = import.meta.env.VITE_API_URL ?? 'http://192.168.10.123:3000/api'
|
||||
const STORAGE_KEY = 'frasa_auth'
|
||||
|
||||
export interface UsuarioSesion {
|
||||
nombre: string
|
||||
rol: string
|
||||
asignacion: string | null
|
||||
}
|
||||
|
||||
export interface Sesion {
|
||||
token: string
|
||||
usuario: UsuarioSesion
|
||||
}
|
||||
|
||||
/** Error de login con mensaje genérico (no filtra si el usuario existe) */
|
||||
export class ErrorLogin extends Error {
|
||||
constructor(message = 'Usuario o contraseña incorrectos') {
|
||||
super(message)
|
||||
this.name = 'ErrorLogin'
|
||||
}
|
||||
}
|
||||
|
||||
export function getSesion(): Sesion | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return null
|
||||
const sesion = JSON.parse(raw) as Sesion
|
||||
if (typeof sesion?.token !== 'string' || !sesion.usuario) return null
|
||||
return sesion
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken(): string | null {
|
||||
return getSesion()?.token ?? null
|
||||
}
|
||||
|
||||
export function logout(): void {
|
||||
localStorage.removeItem(STORAGE_KEY)
|
||||
}
|
||||
|
||||
/** POST /auth/login; guarda token + usuario en localStorage */
|
||||
export async function login(username: string, password: string): Promise<UsuarioSesion> {
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch(`${API_URL}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
})
|
||||
} catch {
|
||||
throw new ErrorLogin('No se pudo conectar con el servidor')
|
||||
}
|
||||
if (!res.ok) throw new ErrorLogin()
|
||||
const data = (await res.json()) as Sesion
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify({ token: data.token, usuario: data.usuario }))
|
||||
return data.usuario
|
||||
}
|
||||
|
||||
/**
|
||||
* Agrega Authorization: Bearer a un RequestInit si hay sesión.
|
||||
* Sin token devuelve el init tal cual (las llamadas siguen iguales que antes).
|
||||
*/
|
||||
export function conAuth(init: RequestInit = {}): RequestInit {
|
||||
const token = getToken()
|
||||
if (!token) return init
|
||||
return { ...init, headers: { ...(init.headers as Record<string, string>), Authorization: `Bearer ${token}` } }
|
||||
}
|
||||
|
||||
/** Si el API responde 401: cierra sesión y recarga para volver al login */
|
||||
export function manejar401(res: Response): void {
|
||||
if (res.status !== 401) return
|
||||
logout()
|
||||
if (typeof window !== 'undefined') window.location.reload()
|
||||
}
|
||||
54
apps/mi-dia/src/services/mi-dia.ts
Normal file
54
apps/mi-dia/src/services/mi-dia.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
// Cliente del API para la app "Mi día" (mismas convenciones que las demás apps)
|
||||
import type { ResumenMiDia } from '../lib/mi-dia'
|
||||
import { conAuth, manejar401 } from './auth'
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL ?? 'http://192.168.10.123:3000/api'
|
||||
|
||||
async function fetchJson<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const res = await fetch(`${API_URL}${path}`, conAuth(init))
|
||||
manejar401(res)
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => null)) as { error?: string } | null
|
||||
throw new Error(body?.error ?? `Error ${res.status}`)
|
||||
}
|
||||
return (await res.json()) as T
|
||||
}
|
||||
|
||||
export function fetchResumenMiDia(): Promise<ResumenMiDia> {
|
||||
return fetchJson<ResumenMiDia>('/mi-dia/resumen')
|
||||
}
|
||||
|
||||
export interface LeadCreado {
|
||||
id: string
|
||||
estado: string
|
||||
}
|
||||
|
||||
/** Crea un lead; en duplicado (409) lanza Error con el mensaje del API */
|
||||
export async function crearLead(datos: {
|
||||
nombre: string
|
||||
telefono?: string
|
||||
origen?: string
|
||||
notas?: string
|
||||
}): Promise<LeadCreado> {
|
||||
return fetchJson<LeadCreado>('/leads', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(datos),
|
||||
})
|
||||
}
|
||||
|
||||
export function cambiarEstadoLead(itemId: string, estado: string, fecha?: string): Promise<unknown> {
|
||||
return fetchJson(`/leads/${itemId}/estado`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(fecha !== undefined && fecha !== '' ? { estado, fecha } : { estado }),
|
||||
})
|
||||
}
|
||||
|
||||
export function descartarLead(itemId: string, motivo: string, comentario?: string): Promise<unknown> {
|
||||
return fetchJson(`/leads/${itemId}/descartar`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(comentario !== undefined && comentario !== '' ? { motivo, comentario } : { motivo }),
|
||||
})
|
||||
}
|
||||
22
apps/mi-dia/tsconfig.app.json
Normal file
22
apps/mi-dia/tsconfig.app.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true,
|
||||
"types": ["vite/client"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
7
apps/mi-dia/tsconfig.json
Normal file
7
apps/mi-dia/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
19
apps/mi-dia/tsconfig.node.json
Normal file
19
apps/mi-dia/tsconfig.node.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts", "vitest.config.ts"]
|
||||
}
|
||||
9
apps/mi-dia/vite.config.ts
Normal file
9
apps/mi-dia/vite.config.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
// La app se sirve detrás de NGINX bajo el prefijo /hoy
|
||||
export default defineConfig({
|
||||
base: '/hoy/',
|
||||
plugins: [react(), tailwindcss()],
|
||||
})
|
||||
8
apps/mi-dia/vitest.config.ts
Normal file
8
apps/mi-dia/vitest.config.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
// Config de tests separada para no mezclar los tipos de Vite y Vitest
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: 'node',
|
||||
},
|
||||
})
|
||||
@@ -41,6 +41,11 @@ server {
|
||||
try_files $uri $uri/ /dash/index.html;
|
||||
}
|
||||
|
||||
location /hoy/ {
|
||||
alias /root/frasa-ecosystem/apps/mi-dia/dist/;
|
||||
try_files $uri $uri/ /hoy/index.html;
|
||||
}
|
||||
|
||||
# Landing (raíz)
|
||||
location / {
|
||||
root /root/frasa-ecosystem/apps/landing/dist;
|
||||
|
||||
Reference in New Issue
Block a user