feat: API Gateway (Express 5 + Prisma + Monday) y conexion de apps al API

- api-gateway: servicio Monday (retry 429/complejidad, paginacion cursor,
  column IDs por titulo), endpoints unidades/cotizaciones/clientes/planes,
  webhook con handshake challenge, Prisma SQLite dev, 55 tests
- cotizador: inventario desde /api/unidades con fallback a seed
- alta-clientes: POST /api/clientes + upload multipart de documentos
- cobranza: persistencia via API con respaldo offline en localStorage
- .env.example con board IDs del workspace Frasa-CAS
This commit is contained in:
2026-08-21 23:39:17 +00:00
parent ecd4edac02
commit 0546f35d2a
48 changed files with 7129 additions and 66 deletions

View File

@@ -6,20 +6,24 @@ interface UseUnidadesResult {
unidades: Unidad[]
cargando: boolean
error: string | null
/** true cuando el inventario viene del seed local (sin conexión al API) */
usandoSeed: boolean
}
/** Carga el inventario de unidades (hoy desde seed; mañana desde el API Gateway) */
/** Carga el inventario de unidades desde el API Gateway, con fallback al seed local */
export function useUnidades(): UseUnidadesResult {
const [unidades, setUnidades] = useState<Unidad[]>([])
const [cargando, setCargando] = useState(true)
const [error, setError] = useState<string | null>(null)
const [usandoSeed, setUsandoSeed] = useState(false)
useEffect(() => {
let activo = true
getUnidades()
.then((data) => {
.then(({ unidades, usandoSeed }) => {
if (activo) {
setUnidades(data)
setUnidades(unidades)
setUsandoSeed(usandoSeed)
setCargando(false)
}
})
@@ -34,5 +38,5 @@ export function useUnidades(): UseUnidadesResult {
}
}, [])
return { unidades, cargando, error }
return { unidades, cargando, error, usandoSeed }
}

View File

@@ -37,7 +37,7 @@ const campoInputError = `${campoInputBase} border-red-400`
const etiquetaCampo = 'mb-2 block text-xs font-bold uppercase tracking-widest text-neutral-500'
export default function CotizadorPage() {
const { unidades, cargando, error } = useUnidades()
const { unidades, cargando, error, usandoSeed } = useUnidades()
const cotizacion = useCotizacion()
const {
unidad,
@@ -99,6 +99,9 @@ export default function CotizadorPage() {
<aside className="space-y-16">
<section className="space-y-8 border border-neutral-200 bg-white p-6">
{error && <p className="text-xs text-red-700">{error}</p>}
{usandoSeed && !cargando && (
<p className="text-xs text-amber-700">Datos de demostración (sin conexión al servidor)</p>
)}
{cargando ? (
<p className="text-sm text-neutral-500">Cargando unidades…</p>
) : (

View File

@@ -0,0 +1,67 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { getUnidades } from './api'
import { UNIDADES_SEED } from '../data/unidades'
import type { Unidad } from '../types'
const unidadApi: Unidad = {
codigo: 'U-101',
modelo: '2RA',
fechaEntrega: '2027-10-08',
supEstacionamiento: 28.62,
supConstruccion: 69.485,
supExcedente: 21.336,
precioSinAcabados: 4415000,
precioConAcabados: 4579000,
status: 'DISPONIBLE',
desarrollo: 'DIAGONAL',
}
function respuestaOk(body: unknown): Response {
return new Response(JSON.stringify(body), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
afterEach(() => {
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
describe('getUnidades', () => {
it('devuelve las unidades del API cuando la respuesta es OK', async () => {
const fetchMock = vi.fn().mockResolvedValue(respuestaOk([unidadApi]))
vi.stubGlobal('fetch', fetchMock)
const resultado = await getUnidades()
expect(fetchMock).toHaveBeenCalledWith('http://192.168.10.123:3000/api/unidades')
expect(resultado.usandoSeed).toBe(false)
expect(resultado.unidades).toEqual([unidadApi])
})
it('hace fallback al seed local cuando la respuesta no es OK', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(new Response('error', { status: 500 })),
)
const resultado = await getUnidades()
expect(resultado.usandoSeed).toBe(true)
expect(resultado.unidades).toEqual(UNIDADES_SEED)
expect(warn).toHaveBeenCalledOnce()
})
it('hace fallback al seed local cuando falla la red', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('fetch failed')))
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const resultado = await getUnidades()
expect(resultado.usandoSeed).toBe(true)
expect(resultado.unidades).toEqual(UNIDADES_SEED)
expect(warn).toHaveBeenCalledOnce()
})
})

View File

@@ -1,10 +1,28 @@
import type { Unidad } from '../types'
import { UNIDADES_SEED } from '../data/unidades'
// TODO produccion: '/api' same-origin detras de NGINX
const API_URL = import.meta.env.VITE_API_URL ?? 'http://192.168.10.123:3000/api'
export interface GetUnidadesResult {
unidades: Unidad[]
/** true cuando se usó el seed local por no poder contactar el API */
usandoSeed: boolean
}
/**
* Devuelve el inventario de unidades.
* TODO: reemplazar por fetch('/api/unidades') cuando el API Gateway esté disponible
* Intenta GET {API_URL}/unidades; si falla (red o respuesta no OK),
* hace fallback al seed local con console.warn.
*/
export async function getUnidades(): Promise<Unidad[]> {
return UNIDADES_SEED
export async function getUnidades(): Promise<GetUnidadesResult> {
try {
const resp = await fetch(`${API_URL}/unidades`)
if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
const unidades = (await resp.json()) as Unidad[]
return { unidades, usandoSeed: false }
} catch (err) {
console.warn('[api] No se pudo obtener el inventario del API; usando seed local.', err)
return { unidades: UNIDADES_SEED, usandoSeed: true }
}
}

View File

@@ -8,6 +8,7 @@ export interface Unidad {
precioSinAcabados: number // MXN
precioConAcabados: number // MXN
status: 'DISPONIBLE' | 'APARTADA' | 'VENDIDA'
desarrollo?: string // lo agrega el API Gateway (Monday); el seed local no lo trae
}
export interface Cliente {